Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reload file

I have a script that computes some stuff. It uses inputs from a separate file 'inputs.py'.

In 'inputs.py' are only a few variables:

A = 2.3
B = 4.5
C = 3.0

In the main file I import them with

from inputs import *

If I now change something in 'inputs.py' and execute the script again it still uses the old values instead of the new ones. How can I reload the file?

reload(inputs)

does not work.

Many thanks in advance!

like image 370
Sebastian Avatar asked Jul 14 '15 15:07

Sebastian


People also ask

How do you reload a file in Python?

The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

What does reload mean in Python?

The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax "import moduleName". It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again.

What is Importlib reload?

When reload() is executed: Python module's code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module's dictionary by reusing the loader which originally loaded the module.


1 Answers

If you are using Python 3.x , then to reload the names that have been imported using from module import name , you would need to do -

import importlib
import inputs #import the module here, so that it can be reloaded.
importlib.reload(inputs)
from inputs import A # or whatever name you want.

For Python 2.x , you can simply do -

import inputs   #import the module here, so that it can be reloaded.
reload(inputs)
from inputs import A # or whatever name you want.
like image 128
Anand S Kumar Avatar answered Oct 12 '22 23:10

Anand S Kumar