__name__Intermediate Examples

The name of a module; equals '__main__' when run as a script

__name__ with custom classes

Working with __name__ in your own classes.

python
# Using __name__ with custom classes
class Registry:
    def __init__(self):
        self._items = {}

    def register(self, cls):
        self._items[cls.__name__] = cls
        return cls

    def get(self, name):
        return self._items.get(name)

registry = Registry()

@registry.register
class Widget:
    pass

@registry.register
class Button:
    pass

print(registry._items)
print(registry.get("Widget"))

Custom classes interact with __name__ in specific ways that are useful to understand.

Want to try these examples interactively?

Open Intermediate Playground