Running Python code only when file executed directly - Hives/weather-station-rpi Wiki

if name == 'main' whats this???

You should get in the habit of using this almost always.


class WeatherDataSender:
    def __init(self, ... ):
        # etc...
    def push_data(self):
        # etc...

# and then at the bottom:

if __name__ == "__main__":

__name__ is a special variable in Python which is set to the name of the current module, except when the module has been executed directly, in which case it is set to __main__. That means that anything that comes in the if __name__ == '__main__': block will be run only when you explicitly run your file, e.g. from the command line, like this:

> python3

However, if you import elsewhere:


then __name__ is set to the name of the module, i.e. weather_data_sender, and nothing in the if __name__ == '__main__': block will be called.

So by doing this we can run our program by executing the file explicitly, but it won't run when we run our tests because in that situation it's being imported from a different file.