In my main file of my Python3 project, I want to display dotted definition path of imported class as string.
My imported class:
Is named WoodCuting
and is located in constants/dimensions.py
.
class WoodCuting():
WIDTH = 12
HEIGHT = 12
What I want:
Dotted definition path of imported class as a string - constants.dimensions.WoodCuting
.
What I tried:
str(type(WoodCuting))
returns constants.dimensions.WoodCuting
- which is exactly what I want. However it is not reliable solution.
Any Ideas?
You can do this with the object's __module__
and __qualname__
attributes.
>>> '.'.join((WoodCuting.__module__, WoodCuting.__qualname__))
'constants.dimensions.WoodCuting'
Using __qualname__
rather than __name__
means you get the correct result for nested objects.
Say this class is in the module:
class Foo:
class Bar:
pass
>>> '.'.join((constants.dimensions.Foo.Bar.__module__, constants.dimensions.Foo.Bar.__qualname__))
'constants.dimensions.Foo.Bar'
Assuming WoodCuting
is located in constants/dimensions.py
:
from constants.dimensions import WoodCuting
def get_full_name(c):
return c.__class__.__module__ + '.' + c.__class__.__name__
print(get_full_name(WoodCuting()))
returns constants.dimensions.WoodCuting
.
Try this
import inspect
class WoodCuting():
WIDTH = 12
HEIGHT = 12
a=inspect.getfile(WoodCuting)
print (a)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With