vmp
vmp

Reputation: 2420

How to reload a file and being able to call it without prefixing by the module name in python?

I have a function:

def f():
   print('hi')

saved in a file example.py.

I start the prompt on windows and hit python

and type the following commands:

from importlib import reload
import example
from example import *

And then I change something in the file example.py and hit reload(example). But it only works when I call example.f(). Do I always have to add an extra from example import * to be able to call just f() after reloading? Is there a better way to achieve that?

Upvotes: 2

Views: 112

Answers (2)

blueteeth
blueteeth

Reputation: 3555

If you're still thinking about this, you may benefit from IPython, and the autoreload extension.

IPython is a powerful interactive shell and alternative Python interpreter with features like code completion, and syntax highlighting.

From the autoreload module page: (https://ipython.org/ipython-doc/3/config/extensions/autoreload.html)

IPython extension to reload modules before executing user code.

autoreload reloads modules automatically before entering the execution of code typed at the IPython prompt.

This makes for example the following workflow possible:

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43

The module was reloaded without reloading it explicitly, and the object imported with from foo import ... was also updated.

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

No, there is no other way to achieve that other than doing an explicit from example import * after you reload the module. On the other hand, it's never a good practice in general (namespace pollution) to import anything other than a module. Importing classes and functions directly is a bad practice in general and you should always avoid that, especially from A import *. Never do that.

Upvotes: 1

Related Questions