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

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

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

# weather_data_sender.py

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

# and then at the bottom:

if __name__ == "__main__":
    WeatherDataSender().push_data()

__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 weather_data_sender.py

However, if you import weather_data_sender.py elsewhere:

import weather_data_sender.py

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.