SnippedPaws
SnippedPaws

Reputation: 73

How to get "name" from module when using "import module as name"

I can't seem to find where the actual name that a module has been bound to is stored. For example:

import re as my_re

print my_re.__name__ # Output is "re," not "my_re"

I would like to be able to get the name that I imported the module as rather than the actual name of the module.

My use case is that I have a function that takes a function object as an argument and needs to be able to determine what name it is bound to. Here is a more thorough example:

import module as my_module

def my_func(in_func):
    print in_func.__bound-name__ # Or something to this effect

my_func(my_module.function1) # Should print "my_module.function1"

Upvotes: 3

Views: 226

Answers (2)

sanyassh
sanyassh

Reputation: 8550

There is no way to do exactly what you want because string my_re is not stored anywhere, it is only a name of a variable. PEP221 which proposed the syntax for import ... as statement explains that the following lines are equal:

import re as my_re

and

import re
my_re = re
del re

Upvotes: 1

Osman Mamun
Osman Mamun

Reputation: 2882

I would pass the module name as string and then use globals() to fetch the module for use within the function. Suppose you pass 'np' to the function, then globals()['np'] will return the function.

In [22]: import numpy as np
In [23]: def demo(A):
    ...:     a = globals()[A]
    ...:     print(a.array([i for i in range(10)]))
    ...:

In [24]: demo('np')
[0 1 2 3 4 5 6 7 8 9]

Upvotes: 1

Related Questions