![]() when read from standard input, a script, or an interactive prompt), the _name_ attribute is set to ' _main_'. The important thing to remember is that when Python is running as a top-level executable code (i.e. For example, if you import the NumPy module, you’ll see that its attribute _name_ will be equal to numpy: In any module you import, its name will be set to the name of the file. The key attribute of each module is its name – or more precisely, _name_. Module objects in Python are characterized by various attributes that are prefixed and postfixed by a double underscore ('_'). It includes hundreds of coding challenges covering this language’s basics as well as more advanced concepts for writing optimized Python applications. In this article, I’ll discuss how to avoid this situation by adhering to the Python best practice of separating code that should be executed only when it is run as a script (but not when it’s imported).Īfter you read this guide, I encourage you to start practicing right away with the interactive learning track Learn Programming with Python. However, if a module with runnable code is imported from a different module, this code would execute itself when it is imported. You can include runnable code in modules. ![]() With a custom module in Python, you can define variables, functions, or even create your own classes. It is sometimes challenging for beginners to understand the difference between these concepts, but basically they’re all forms of organizing Python code.įor example, a module is a bunch of related code saved in a file with the extension. The Python ecosystem is very rich in modules, packages, libraries, and frameworks. In this guide, I’ll explain how including a main() function, though not required in Python, can structure your programs in a logical way and ensure that your functions are executed only when expected. If you are just starting with Python, you might not be aware yet of the best practice of defining functions.
0 Comments
Leave a Reply. |