Discover fixes

Backport the fix for discovery in packages from Python bugtracker.
It's original in my patch for Python itself; its a literal copy of the result of that patch, lightly adjusted for imports here. I should credit that more clearly.