Reputation: 61259
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:
type(v).__name__
gives ndarray
without the np
.type(v).__qualname__
gives ndarray
without the np
.type(v).__module__
gives numpy
not np
.How can I get np.ndarray
back?
Upvotes: 2
Views: 100
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