How much memory does a Python list use? sys.getsizeof will tell you, sort of: It reports the memory used by the list, but not its elements:
Want stderr in your Python program to go somewhere else? Use redirect_stderr in contextlib:
Writing a bunch to non-stdout in Python? You might want to use redirect_stdout from contextlib:
Want to print to stderr, not stdout, in a Python program? Use sys.stderr and the “file” kwarg: stdout and stderr often look identical in a terminal — but they aren’t!
Normally, “print” in Python writes to stdout. Write elsewhere with the “file” keyword argument:
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!