Explain Codes LogoExplain Codes Logo

How can I get a list of all classes within current module in Python?

python
functions
best-practices
collections
Nikita BarsukovbyNikita Barsukov·Feb 10, 2025
TLDR

To swiftly procure a list of classes from your current module, efficiently use the inspect and sys modules with the following command:

import inspect, sys # one-liner magic ✨ classes = [cls for _, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass) if cls.__module__ == __name__]

Remember to import inspect and sys before execution. This will screen out classes that are defined in the module itself, and not the imported ones.

Let's dissect the magic spell!

The immediate solution works like a charm! But it's always a good idea to understand the mechanism behind the magic.

Plan B: globals()

Explore another trick using globals(), a function that returns a dictionary of current module's attributes.

classes = [global_ for global_ in globals().values() if inspect.isclass(global_) and global_.__module__ == __name__]

Hocus pocus! We've filtered globals() to only include classes that were conjured up within your module.

The Magic Trunk: dir()

The magic trunk dir() holds all names defined in the module. To morph these names back to their original form (objects) and sort out the classes, use this incantation:

classes = [getattr(sys.modules[__name__], name) for name in dir(sys.modules[__name__]) if inspect.isclass(getattr(sys.modules[__name__], name)) and getattr(sys.modules[__name__], name).__module__ == __name__]

dir() opens the trunk, and getattr() transforms the names to objects belonging to your module.

Caution: Spell casting in progress!

When you brave through globals() or similar territories, remember to wield a copy to prevent misfire:

for name, obj in globals().copy().items(): if inspect.isclass(obj) and obj.__module__ == __name__: # don't touch! magic in progress 🧙‍♂️

Tips from Master Wizards

Shield spell: Error handling

Every wizard needs a shield. When your magic goes awry, catch it gracefully:

try: # magic spell goes here except Exception as error: print(f"Oops! You summoned an error: {error}")

The Wizard Council: itertools.chain()

For a council of modules or a complex mission that needs listing classes across modules, invoke the itertools:

import itertools modules = [sys.modules[__name__], other_module] classes = list(itertools.chain.from_iterable( inspect.getmembers(module, inspect.isclass) for module in modules ))

Voila! Let the magic of itertools bring it all together.

Globe-trotter's charm: Platform compatibility

Ensure your scrolls can be read across realms (all platforms):

# magic spell that transcends realms (platform-independent)

The secret: module attribute

The secret to ensuring you're conjuring classes from the correct module lies in the __module__ attribute:

# the '__module__' reveals the origin of the class

Beware ye pitfalls

Taming the shapeshifter: global variables

Tread lightly when dealing with globals(). It's a shapeshifter and can create duplicates or disappear when summoned directly. Always use a clone:

# cloning globals just to make sure they don't play tricks globals_copy = globals().copy()

Clearing the haze: namespace pollution

A cluttered workspace can summon unwanted demons. Make sure to cleanse your namespace to avoid accidentally invoking undesired classes. The __module__ attribute will guide you forth.

Spell translation: dir() output

Remember, dir() only whispers the names, not the entities themselves. Use getattr() to translate these murmurs into entities.

Unveil classes with pyclbr

The pyclbr module gracefully reveals all class names within a .py scroll. Note: this spell doesn't work in an interactive session:

import pyclbr class_names = list(pyclbr.readmodule(__name__).keys())

pyclbr foretells class names devoid of additional spellcasting or incantations required for live object inspection.