reloading python modules using exec function | applied electronics engineering

Latest

reloading python modules using exec function

By Applied Electronics - Monday, May 9, 2016 No Comments
In python programming language, modules are programs and they are combined to form a larger program. The main program or the main modules imports the other modules. The different modules contains statements of attributes, functions of objects. However, one of the problem while working with Python programming language is that once you have imported them, at the beginning, and later on you make some changes in some module, it is not reflected in the main program/module. That is the main program will not know that changes has been made in one of its module. So in order to avoid this pitfall, you have to reload the module if you make any changes to it.

We have described two methods how you can reload a module. See the tutorials How to reload module in Python and Reloading python modules using import imp for these two methods.

Here we describe a third method- using exec function to reload modules in Python program.

It's is very simple. The syntax is:

>>> exec(open('M').read())

where M is the module name with .py extention. Don't forget the .py extention.

Let's us show you this with some Python code. First make a simple helloworld.py file with a simple single print statement.

print("Hello World")

Now if you are in interactive phyton console like IDLE or PyCharm and you typle the following:

>>> import helloworld

it returns,
Hello World

Then change the print statement to "Hello You" and type again:

>>> import helloworld

it will show nothing because it still has stored to old values.

So in order to reload the module, write the following command:
 
>>> exec(open('helloworld.py').read())

And you will see:

Hello You


That's it. Don't forget to see the other reload methods in Python.


No Comment to " reloading python modules using exec function "