Make python () reload function read with .py instead of .pyc

I wrote a fairly large module that automatically compiles to a .pyc file when I import it.

When I want to test module functions in an interpreter, for example, class methods, I use the reload() function from the imp package.

The problem is that it reloads the .pyc file, not the .py file.

For example, I try to use a function in the interpreter, find out that it does not work properly, I would make changes to the .py file. However, if I reload the module in the interpreter, it reloads the .pyc file so that the changes are not reflected in the interpreter. I would have to exit the interpreter, start it again and use import to load the module (and create the .pyc file from the .py file). Or, alternatively, I would have to delete the .pyc file each time.

Is there a better way? For example, to make reload() preferable to .py files on top of .pyc files?

Here, with the exception of the interpreter session, which shows that reload() loads the .pyc file.

 >>> reload(pdb) <module 'pdb' from 'pdb.pyc'> 

EDIT: And even if I delete the .pyc file, a different .pyc file will be created with each reload, so every time I use reboot, I have to delete the .pyc file.

 >>> reload(pdb) <module 'pdb' from 'pdb.py'> >>> reload(pdb) <module 'pdb' from 'pdb.pyc'> 
+4
source share
3 answers

Yes. here you can use the -B command line -B :

 python -B 

or use the PYTHONDONTWRITEBYTECODE parameter:

 export PYTHONDONTWRITEBYTECODE=1 

they make sure that .pyc files are not generated first.

+3
source

If you are using ipython, you can make a shell command by specifying it first !

So you could do

 >>> !rm some_file.pyc >>> reload(some_file) 

Alternatively, you can define a quick function in the current shell:

 >>> import os >>> def reload(module_name): ... os.system('rm ' + module_name + '.pyc') ... reload(module_name) ... 

and just call it when you want to reload the module.

0
source

You do not need to remove obsoleted * .pyc because a reboot (module) does this automatically.

For this purpose, I usually use something like:

  import module def reinit(): try: reload(module) except: import traceback traceback.print_exc() call_later(1, reinit) reinit() 
0
source

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


All Articles