Want stdout from your Python program to go elsewhere? Assign sys.stdout to a writeable file. (Don’t forget to keep the original around!) Better: print’s file kwarg.
After you import a Python module, its repr (printed representation) shows its name and the loaded file. But some modules don’t have files; they were “frozen” into Python. They have no __file__ attribute, and show “frozen” in their __loader__.
Want Python to import modules in non-default dirs? You could do this: But: It doesn’t scale across many programs. And what if the dir changes? Better: Set the PYTHONPATH environment variable — scalable and set in one place.
sys.path tells Python where to look when importing a module. Think of it as a list of directories. But it also handles zipfiles. A zipfile in sys.path is treated as a directory. Files in the zipfile can be imported.
You say “import mymod”. Where does Python look? Check sys.path, a list of directory names (strings) where it searches. By default: – Current dir (empty string)– Standard library– site-packages The first match wins, which can lead to unpleasant surprises — be careful!
In Python, import always defines a variable. But it only loads the module once. sys.modules, a dict, tracks already-loaded modules: – keys are strings, the module names– values are module objects If you say “import pandas as pd”, sys.modules has a key ‘pandas’, not ‘pd’.
“sys” is where Python keeps vital info about its runtime environment. So why import it? Not to load it; sys is loaded when Python starts. Rather, the import just defines “sys” as a global variable. Importing “sys” takes almost no time, and provides useful info.
Find the version of Python: To use it in a program, you want version_info:
Want a Python Enum, but don’t care about the values? Use auto: You can now use Days.SUN and Days.MON. With auto, you care the Enum’s values are different, not what they are.
Want to iterate over a Python Enum? __members__ returns a dict-like object, and it supports items(): SUN: 1MON: 2TUE: 3[etc]