简体   繁体   中英

Get the import name of a module

I have the following:

import numpy as np
v = np.ndarray([1,2,3,4,5])

I'm interested in examining v and somehow recovering that it is of type np.ndarray .

What doesn't work:

  1. type(v).__name__ gives ndarray without the np .
  2. type(v).__qualname__ gives ndarray without the np .
  3. type(v).__module__ gives numpy not np .

How can I get np.ndarray back?

One way is to look up the alias used for the module in globals() .

def name_of(x):
    t = type(x)
    alias = next(
        k
        for k, v in globals().items()
        if hasattr(v, "__name__") and v.__name__ == t.__module__
    )
    return f"{alias}.{t.__name__}"

Example usage:

>>> import numpy as np
>>> name_of(np.array([]))
'np.ndarray'

Furthermore, since dictionary iteration is insertion-ordered, this will return the alias that was first declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM