How Python Import statements work. Application: Energy
Import statements in Energy
Software engineering projects in Energy, like every other software engineering project, include lots of modules (Python files) and import statements. Let’s look at some examples.
The Variations of Import
Let’s assume that we have a file called main.py. Python allows us to import code into this file. By the way a “module” is a .py file;
import module: This imports the entire module (.py file) into our main.pyfrom module import something: This imports specific parts of a module.
When we are building energy models import statements help us to keep the code organised. We can place code in the modules (.py files) where it logically belongs to. This is what we call “clean code”.
A Practical Example: Energy Calculations
I’ve created a project structure with three Python files (modules):
solar.py- Solar energy calculationswind.py- Wind energy calculationsmain.py- Our main module. We could have called our main modulestart.py, or something else, but the convention is to call itmain.py.
This mirrors how we organize a large-scale energy analysis project, where different electricity generation sources (solar, wind, nuclear, etc.) get their own modules. Here, our sources for electricity generation are a solar photovoltaics farm and a wind farm.
The importance of if __name__ == “__main__”
Inside the main.py we typically include the following piece of code.
if __name__ == “__main__”:
main()Also inside main.py we have a function, which we call main(), which starts calling the functions across our modules.
The if __name__ == “__main__” statement is incredibly useful. Here is why we need it:
Assume that the file solar.py has the line import main (currently it does not have it, but let’s assume that it does). Also, let’s assume that main.py does not have the above statement, and simply has main() — that is, it simply calls main() without having the if __name__ == “__main__” statement.
So we open solar.py and run it. It imports main.py. Remember that when we import a file, this file runs once. So we have just run solar.py, and it also imports main.py, so main.py will run once, meaning that it will call main(), which will start calling functions around all other modules.
Most likely we do not want main() to run if we run solar.py. We prefer main() to run only when we run main.py.
So, if we now place the above statement (i.e., if __name__ == “__main__”: main()) in main.py, then when we run solar.py, the main() won’t run!
The idea is that if we want to run main(), then we will run it from main.py. And when we want to run other files like solar.py, we do not want to also run main().
This is essential for building modular, testable code.
The Complete Code Example
Now let’s see the actual implementation. I’ll show you the three files and explain how they work together.
Join our community! Visit skool.com, search for “Energy Data Scientist”


