main is just some function in the program, however, it’s just the dunder variable __name__ that we’re interested in here.
What does this mean for things with dunder names?
Dunder names are used to denote variables and functions that cover the inner-workings of Python. A lot of what goes on under the hood is described by dunder functions, variables and methods.__name__ is actually a very good example. This is a built-in variable that takes on different values depending on how the code it is in is being run.
- When code is run as a script
__name__is set to'__main__', which is the name of the top-level environment of the program. - When code is imported as a module,
__name__is set to the name of the module file
if statement above. In other words, if you run a python file as a script the if block gets called, but if you just wanted to re-use the functions and classes in it you can import the file as a module and the if block will not be triggered. Pretty neat!
How do dunder methods apply to classes?
When one performs various actions using classes in Python that don’t explicitly use dot notation to call a method, a dunder method is likely being called in the background to do that thing. The best example of this is class instantiation and the__init__ method. When you create an instance of class, as we have in previous Parts, like below, the __init__ method is called when the class is created.
dataclass hides this for us, but we can actually create the same class without it, using __init__.
print I added to the second. If you don’t believe me, try them out and see for yourself! Well, mostly equivalent. dataclass adds a bunch of additional things for us as well, including a human-readable string representation of the class when printing. In the second example we would have to manually add that ourselves using other dunders. Day-to-day we just don’t need to bother and dataclass handles most of the common use cases without any trouble.
Another example of a dunder method on classes is the __add__ method which is called when the + operator is used on a class instance.
Coordinate(x=2, y=2). There are dunders for all sorts of operations and behaviours in Python and messing with them can be dangerous. You don’t really want to change things in ways you aren’t fully confident with. For example, in the code just presented, you may have noticed that other can be any type and if it’s a Coordinate it will fail. Perhaps it should, perhaps it shouldn’t, but either way it is up to you as the implementer to make it do the ‘correct’ thing. Often it’s best to leave well alone.