__spec__Easy Examples

The module spec used to import the module

Accessing __spec__

How to access and use __spec__.

python
# __spec__ holds module spec information
import json
print(json.__spec__)
print(json.__spec__.name)

__spec__ is a special attribute that the module spec used to import the module.

__spec__ in practice

Using __spec__ in everyday code.

python
# More __spec__ examples
print("__spec__ is a special Python attribute")

# Every object has certain dunder attributes
obj = object()
attrs = [a for a in dir(obj) if a.startswith("__")]
print(f"object has {len(attrs)} dunder attributes")

Understanding __spec__ helps you introspect and debug Python objects.

Want to try these examples interactively?

Open Easy Playground