Back to Blog
Special variables coppercube7/27/2023 ![]() We then have two scopes: one of importingScript and the second scope of nameScript. The code in importingScript.py could be as follows: import nameScript as ns ns.myFunction() If we want to re-use myFunction in another script, for example importingScript.py, we can import nameScript.py as a module. Scenario 2 - Import the script in another script Because the condition evaluates to true, the main function is called. After that, the main and myFunction def statements are run. If you run nameScript.py, the process below is followed.īefore all other code is run, the _name_ variable is set to _main_. Suppose we wrote the script nameScript.py as follows: def myFunction(): print 'The value of _name_ is ' + _name_ def main(): myFunction() if _name_ = '_main_': main() Let us take a look at these two use cases and describe the process with two illustrations. When you import the containing script, it will contain the name of the script. When you run your script, the _name_ variable equals _main_. What values can the _name_ variable contain? Or that you want to import the functions defined in the script. Thanks to this special variable, you can decide whether you want to run the script. In Python, you can import that script as a module in another script. Sometimes you write a script with functions that might be useful in other scripts as well. It gets its value depending on how we execute the containing script. The _name_ variable (two underscores before and after) is a special Python variable. In this article, I want to show you how you can make use of this variable to create modules in Python. Below you see an example code snippet of how it may look: if _name_ = '_main_': main() ![]() You’ve most likely seen the _name_ variable when you’ve gone through Python code. An introduction to the _ _name_ _ variable and its usage in Python ![]()
0 Comments
Read More
Leave a Reply. |