A quick handy reference to some python snippets

Find path to a package or module

import os
print os.path.dirname(packagename.__file__)

List all modules inside a package

import pkgutils
import os
[name for _, name, _ in pkgutil.iter_modules([os.path.dirname(packagename.__file__)])

The Unicode mess

All computation should occur on unicode¬†objects. Understand that ‘utf-8’ is an encoding and should only be used while printing out to a file or the terminal. That can be achieved with a simple blah.encode(‘utf-8’) Do not use such encoding for internal string processing. Also, “str” literally means byte in python so avoid use, and instead use unicode(blah), wherever you might be tempted to use str(blah)

Share This