Lanfear
Lanfear

Reputation: 325

Is it possible to reload a python module as something?

Messing around in the interpreter, it would be useful for me to be able to do something along the lines of reload(foo) as f, though I know it is not possible. Just like I do import foo as f, is there a way to do it?

Using Python 2.6

Thanks!

Upvotes: 9

Views: 3344

Answers (4)

eric
eric

Reputation: 8019

Python 3 Answer

As others have said, just reload using the name you used as an alias. However, since imp is deprecated in Python 3, you should now do this with importlib. Let's say your original import used an alias as follows:

import fullLibName as aliasName

Then to reload the alias:

importlib.reload(aliasName)

Or (more standard usage):

from importlib import reload
...
reload(aliasName)

Upvotes: 4

jmetz
jmetz

Reputation: 12773

The imp module gives you more access to import internals, and you can import any source file (i.e. it doesn't need to be in the path).

E.g.

anyname = imp.load_source("SOME NAME", FILEPATH)

Upvotes: 0

SimonPJ
SimonPJ

Reputation: 766

If you import as import foo as f in the first place, then the reload call can be reload(f)

Upvotes: 13

scandinavian_
scandinavian_

Reputation: 2576

import foo
f = reload(foo)

This should work, if I understand your question right.

If you don't actually need to reload the library, you can do as Martijn suggested, and just re-assign foo.

f = foo

Upvotes: 1

Related Questions