Calaf
Calaf

Reputation: 10837

Is it necessary to delete pyc files when upgrading Python **within** a major release?

TL;DR

If you switch back-and-forth between 3.6.6 and 3.7.0 before you adopt 3.7.0, there is no concern, the two sets of pyc files will cohabit and you'll be ok.

What if you switch back-and-forth between 3.6.4 and 3.6.6? Do you need to delete pyc files?

Long version

I see that the pyc files are specific for major releases only. For example I have:

__init__.cpython-36.pyc
__init__.cpython-37.pyc

which is presumably the result of PEP 3147.

And so it's clear enough. If I move back-and-forth during development between virtual environments in, say, 3.6.6 and 3.7.0, there is no concern. The two versions will cohabit in the __pycache__ directory because they are identified by the major version number.

Question: What about switching back-and-forth between, say, 3.6.4 and 3.6.6, do I indeed need to delete pyc files when switching from one version and another within the same major release?

Motivation for the question

The reason that I needed to switch virtual environments is that I thought that my code runs fine with some versions of Python 3, but not others. I was getting a multitude of

ImportError: No module named XYZ

errors.

But when I wipe out all pyc files and install one version of Python or another, set up a virtual environment

~/venv-362
~/venv-364
~/venv-366
~/venv-370

then all is well and the code runs fine.

Upvotes: 0

Views: 714

Answers (1)

ivan_pozdeev
ivan_pozdeev

Reputation: 36046

.pyc machinery is designed to be completely transparent to the user. In particular, as per Are Python 2.5 .pyc files compatible with Python 2.6 .pyc files?, a .pyc contains the Python version that was used to compile it.

So, though you can clean the old files so that you don't have obsolete data that won't be used anyway, they shouldn't affect execution is any way.

In particular, they shouldn't cause any import errors. You must be having a problem with your import path instead.


This doesn't mean you shouldn't regenerate them when updating -- as per python bytecode compatibility , Python makes no guarantees about bytecode compatibility between releases, even micro releases. Normally, they will be regenerated on demand, but if you don't have write access to the corresponding dir, you should do that during installation, or afterwards with e.g. compileall.

Upvotes: 1

Related Questions