Richard
Richard

Reputation: 61259

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?

Upvotes: 2

Views: 100

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

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.

Upvotes: 5

Related Questions