2

I know that a module can be reloaded by issuing:

reload(module_name)

Suppose that I do not import the whole module but just one function of it.

from module_name import one_function 

How can you reload that specific function when you have made changes to it.

Thanks in advance.

3
  • Why not reload whole module? Why you want to reload only one function ? Commented Sep 20, 2014 at 12:58
  • 1
    By the way, when you use from module_name import one_function the whole module is loaded, just like import module_name. The only difference is what names get added to the global namespace. Commented Sep 20, 2014 at 13:02
  • Lafada, this raises a NameError. I haven't explicitly imported the module (i.e import <module name>) Commented Sep 20, 2014 at 13:44

2 Answers 2

4

You'll have to re-import the one name to rebind it; you can reach the cached module object in sys.modules:

reload(sys.modules['module_name'])
from module_name import one_function
Sign up to request clarification or add additional context in comments.

Comments

1

You can use inspect.getmodule to get the module that owns a function:

import inspect
from math import sqrt
from importlib import reload

math = reload(inspect.getmodule(sqrt))
sqrt = math.sqrt

Using __qualname__ you can automate this process:

def reload_attr(attribute):
    obj = reload(inspect.getmodule(attribute))
    for name in attribute.__qualname__.split("."):
        try:
            obj = getattr(obj, name)
        except NameError:
            raise ValueError("Unable to find attribute.")
    return obj

reload_attr(sqrt)
#>>> <built-in function sqrt>

Note that this isn't guaranteed to work; not all attributes are trivial to locate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.