Pycache creation

when is pycache created? is it created for all imports? does pycache sit in standard location when python is installed? what would happen if we remove pycache present in standard location?

will doing a simple import like

import pip

or running pip3 --list in terminal create a pycache?

thank you in advance.

The __pycache__ folder and it contents are created the first time python imports a module.

When pip installs a module, it will create __pycache__ directories automatically in the install location.

Also, as @barry-scott said, the first time you import a local module, the Python interpreter itself creates __pycache__ (and if you modify the module and import it afterwards, it will update it).

Usually, yes, but there are special cases. For example, it can be explicitly disabled by passing the -B option to the python command.

Yes, the standard library has precompiled __pycache__ directories.

Just don’t.

No. pip creates __pycache__s when you install/upgrade packages.

1 Like

Thank you, Barry.

Thank you for the info Jean,

@jeanas what would happen if we remove pycache from standard location? won’t it regenerate again? so what’s the issue here?

Bad things.

  • pip might get confused not to find it.
  • If that folder requires admin access to modify (which is normally the case when Python is installed for all users), Python won’t be able tl recreate it, unless you run it with admin access.
  • The Python startup process relies on having some modules precompiled (it cannot compile them while it hasn’t booted its byte-compiler). So, if you remove these, Python will no longer work at all.

noted, thanks for the help @jeanas.