Discover fixes

Backport the fix for discovery in packages from Python bugtracker.
I don't understand what this clause (the `else` branch) is for. Could you please add a comment, or extract to a usefully-named function?