3

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"
2
  • When you run print my_re.__name__, you already know the actual name is my_re because that is how you call the command Commented Oct 21, 2018 at 4:26
  • Right, but in my case, I have a function that takes a module as an argument, and I need to determine the name the module was imported as dynamically. I should have been more clear about that in my original question. Commented Oct 21, 2018 at 4:30

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

broken though if you do import numpy as np; a = b = c = np -- OP is most likely asking for something that's not a good idea ;)
fair enough. It's not a good idea to use globals() anyway. But that's the only work around I can think of. Or maybe the OP can set the repr (I'm not sure)
That's an interesting option and not too far off of something that I had experimented with earlier. It seems like there should be some place where that mapping (between the actual module name and an alias) must be stored... That is what I am really hoping to find.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.