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?
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.