Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting corresponding module from function

Tags:

python

I want to modify a module xyz and its functions like that:

def modify(fun):     modulename = fun.__module__ # this is string. ok, but not enough  import xyz modify(xzy.test) 

My problem is how to access the namespace of xzy inside modify. Sometimes

globals()[fun.__module__] 

works. But then I get problems if the definition modify is in a different file than the rest of the code.

like image 712
rocksportrocker Avatar asked Aug 11 '11 14:08

rocksportrocker


People also ask

How do you access the module of a function in Python?

Modules can define functions, classes, and variables that you can reference in other Python . py files or via the Python command line interpreter. In Python, modules are accessed by using the import statement.

How do I find the name of a module?

A module can find out its own module name by looking at the predefined global variable __name__.

How do you identify a function in a module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.

What is __ module __ in Python?

The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.


2 Answers

Use the inspect module:

import inspect  def modify(fun):     module = inspect.getmodule(fun) 

This is the same as polling the module from sys.modules using fun.__module__. Although getmodule tries harder even if fun does not have a __module__ attribute.

like image 179
driax Avatar answered Oct 31 '22 22:10

driax


You want to get the module object from its name? Look it up in the sys.modules dictionary that contains all currently loaded modules:

import sys  def modify(func):     module = sys.modules[func.__module__] 
like image 22
Ferdinand Beyer Avatar answered Oct 31 '22 22:10

Ferdinand Beyer