Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - Get definition path of object

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?

like image 794
Fusion Avatar asked Mar 04 '19 16:03

Fusion


3 Answers

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'
like image 57
snakecharmerb Avatar answered Oct 10 '22 14:10

snakecharmerb


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.

like image 21
Lukasz Tracewski Avatar answered Oct 10 '22 14:10

Lukasz Tracewski


Try this

import inspect

class WoodCuting():
    WIDTH = 12
    HEIGHT = 12

a=inspect.getfile(WoodCuting)
print (a)
like image 28
Hasee Amarathunga Avatar answered Oct 10 '22 15:10

Hasee Amarathunga