Discover fixes

Backport the fix for discovery in packages from Python bugtracker.
Is this code all original, or has it been adapted from somewhere?