Best way to avoid stale * .pyc files?

What is the best way to avoid stale * .pyc files? Sometimes, especially when switching branches in version control, some * .pyc files remain there and are used by Python instead of the source files that I have.

What is the best strategy to ensure that I do not create or unknowingly use legacy * .pyc files?

+7
source share
5 answers

There is a useful environment variable for this: PYTHONDONTWRITEBYTECODE

export PYTHONDONTWRITEBYTECODE=true 
+2
source

Like khampson, git, and mercurial (and probably others), allow client-side hooks. You can sprinkle scripts that make

 find -iname "*.pyc" -exec rm -f {} \; 

on linux at least. Search for "git hooks" and "mercurial hooks" for more details.

+2
source

I would recommend a combined approach.

First add *.pyc to your .gitignore file, which should help avoid problems when switching branches (at least in cases where the reason is that the .pyc file was somehow fixed), usually I always add as *.pyc , and *.log in your .gitignore , so as not to accidentally commit any of these files, and therefore they will not clutter up my git status output.

Secondly, create a shell-wrapper script that first removes all .pyc files (recursively if your source directory structure calls it) and then calls your actual script. This should ensure that all resulting .pyc files are re-created using the current source.

i.e. something like (without & if you want the script to wait):

 #!/bin.sh rm -f *.pyc ./foo.py & 
+1
source

Another solution would be imp.reload() . I think in 2.7 you can do the following (check later)

 >>> import sys >>> reload(sys) <module 'sys' (built-in)> >>> 

The disadvantage of this method is that versions of your * .pyc files will still be in the repository and updated every time a commit occurs. However, this will protect you from legacy * .pyc versions.

Another solution would be to force git to ignore * .pyc files as well as delete them. Another solution would be to ignore the pycache directory. From the book of Mark Lutz :

In version 3.2 and later, Python instead saves its .pyc bytecode files in a subdirectory called pycache, located in the directory in which the source files are located, and in files whose names identify the version of Python that created them (for example, a script .cpython-33. Pyc). The new pycache subdirectory helps avoid clutter, and the new bytecode file naming convention prevents different versions of Python installed on the same computer from overwriting each other’s stored bytecode.

+1
source

If you call your own modules, for any module folder you need to prevent .pyc files, you can use the following code in your __init__.py file:

 import sys sys.dont_write_bytecode = True 
0
source

Source: https://habr.com/ru/post/980104/


All Articles