chrisyeh96 / chrisyeh96.github.io

Personal website
https://chrisyeh96.github.io
MIT License
21 stars 22 forks source link

Syntax error for pkgutil.iter_modules use case in The Definitive Guide to Python import Statements post #4

Closed PritishSehzpaul closed 5 years ago

PritishSehzpaul commented 5 years ago

search_path should have been set to a list for the example to work. The current case gives the following error: ValueError: path must be None or list of paths to look for modules in.

Correct syntax should be:

search_path = ['.'] # set to None to see all modules importable from sys.path
all_modules = [x[1] for x in pkgutil.iter_modules(path=search_path)]
chrisyeh96 commented 5 years ago

Interesting. When search_path is a str, it still works for me on Windows 10 on both Python 2.7 and 3.6. Oddly, I saw weird behavior on Ubuntu 16.04. If I set search_path = '/path/to/dir/', it would only return an empty list, whereas if I set search_path = '/path/to/dir/. (with a trailing .), it would properly return the packages from that directory. In either case, if I enclosed the paths in a list, I got the desired behavior.

It seems like the error message you see was a change to the CPython API introduced in Python 3.7 link

I've updated my post to use the list for search_path since that seems to be the proper way to call iter_modules.

chrisyeh96 commented 5 years ago

Fixed in commit 11bd0f3c