Python Frequently Asked Questions, Release 3.9.5 One reason that a$_{.pyc}$ file may not be created is a permissions problem with the directory containing the source file, meaning that the __pycache__ subdirectory cannot be created. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server. Unless the PYTHONDONTWRITEBYTECODE environment variable is set, creation of a .pyc file is automatic if you’re importing a module and Python has the ability (permissions, free space, etc…) to create a$_{__pycache__}$ subdi- rectory and write the compiled module to that subdirectory. Running Python on a top level script is not considered an import and no .pyc will be created. For example, if you have a top-level module$_{foo.py}$that imports another module$_{xyz.py}$ , when you run$_{foo}$ (by typing$_{python}$ foo.py as a shell command), a .pyc will be created for xyz because xyz is imported, but no .pyc file will be created for foo since foo.py isn’t being imported. If you need to create a$_{.pyc}$ file for$_{foo}$ – that is, to create a$_{.pyc}$ file for a module that is not imported – you can, using the py_compile and compileall modules. The py_compile module can manually compile any module. One way is to use the compile() function in that module interactively: This will write the .pyc to a __pycache__ subdirectory in the same location as foo.py (or you can override that with the optional parameter cfile ). You can also automatically compile all files in a directory or directories using the$_{compileall}$ module. You can do it from the shell prompt by running$_{compileall.py}$ and providing the path of a directory containing Python files to compile: python -m compileall. >>> import py_compile >>> py_compile .compile( 'foo.py') A module can find out its own module name by looking at the predefined global variable$_{__name__}$ . If this has the value$_{'__main__'}$ , the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking$_{__name__}$ : def main(): print('Running test... ') ... if __name__ =='__main__ ': main() 2.7.2 How do I find the current module name? 2.7.3 How can I have modules that mutually import each other? Suppose you have the following modules: foo.py: from bar import bar_var foo_var=1 bar.py: from foo import foo_var bar_var=2 The problem is that the interpreter will perform the following steps: • main imports foo 33 2.7. Modules