liveBook · Manning

__name__ attribute

As explained in Python Workout: 50 ten-minute exercises

A Python attribute containing the name associated with a module or class.

Python uses __name__ to identify the current module or class. For modules, it distinguishes code run directly from code imported elsewhere: a directly run module receives __main__, while an imported module receives its module name. section 8.7

if __name__ == '__main__':

Use the familiar guard to execute code only when a module runs directly, rather than when another module imports it. section 8.7

Identify a class dynamically

For an object, self.__class__.__name__ produces a string containing the object's current class name. This supports assigning class-based information without asking the user to provide it. section 9.27

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains module execution, namespace assignment, and dynamic class-name lookup, stopping short of broader attribute internals.
Examples
Uses the __name__ guard and self.__class__.__name__ to demonstrate module control flow and class identification.
What it assumes
Assumes working knowledge of modules, imports, objects, and classes.
What you can do after
Apply it via a direct-execution guard or dynamic class-name lookup.
How it connects
Connects modules, imports, namespaces, classes, inheritance, and abstract base classes.

Also explained in

Compare how 2 books explain __name__ attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.