How to get class path in Python

Viewed 2985

In Python, we can define a class and print it as such:

class a:
    num = 1

b = a()

print(b)

And we would get the output:

<class '__main__.a'>

I'm trying to identify unique classes, and I have some classes with longer paths. I would like to extract the "class path", or __main__.a in the case above. For example, if I print some longer class I would get:

<class 'django_seed.tests.Game'>
<class 'django_seed.tests.Player'>
<class 'django_seed.tests.Action'>

And I would like to extract:

'django_seed.tests.Game'
'django_seed.tests.Player'
'django_seed.tests.Action'

Since I can cast <class 'django_seed.tests.Game'> to a string, I can substring it quite easily with '<class 'django_seed.tests.Game'>'[8:-2], but I'm sure there must be a cleaner way. Thanks!

2 Answers

The __module__ attribute can be used to access the "path" of a class (where it was defined) and the __name__ attribute returns the name of the class as a string

print(f'{YourClass.__module__}.{YourClass.__name__}')

You can use inspect:

import inspect

print((inspect.getmodule(a).__file__))
Related