8

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!

1 Answer 1

13

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__}') 
Sign up to request clarification or add additional context in comments.

1 Comment

@ReinstateMonica If the class was defined in __main__ then cls.__module__ returns __main__

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.