Example Explanation of Judge Global Variable Assignment in python Module

  • 2021-10-16 02:20:27
  • OfStack

1. In the module, we need to determine whether __name__ is assigned as "__main__".


python fibo.py <arguments>

2. In the case of script execution, the module's __name__ attribute will be assigned to __main__, which is why.


$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34

3. If you import as a module, you will not execute:


>>> import fibo
>>>

Extension of knowledge points:

Python Dynamic Declare Variable Assignment Code Instance

Through exec (), globals (), and locals ()


#  Pass exec()
for i in range(1, 4):
 #  No. 1 1 Sub-cycle  i=1  Hour , Executes the python Statement  ex1 = "exec1", And so on 
 exec(f'ex{i} = "exec{i}"')

#  Pass globals() And locals()
def test():
 # globals()
 for i in range(1, 4):
  #  No. 1 1 Sub-cycle  i=1  Hour , Execute  globals()['gb1'] = 'global1', globals() Yes 1 A dict
  globals()[f'gb{i}'] = f'global{i}'

 # locals()
 for i in range(1, 4):
  locals()[f'lc{i}'] = f'local{i}'

 #  Try to print locals Variables of 
 try:
  print(lc1, lc2, lc3) #  Will report an error 
 except Exception as e:
  print(e)
  print(locals()['lc1'], locals()['lc2'], locals()['lc3']) #  Through key-value pairs 

if __name__ == '__main__':
 #  Execute 
 test()
 print('---------------------')
 #  Print the global variables defined by the function 
 print(gb1, gb2, gb3)
 print('---------------------')
 #  Print through exec() Defined variables 
 print(ex1, ex2, ex3)

Output:


name 'lc1' is not defined
local1 local2 local3
---------------------
global1 global2 global3
---------------------
exec1 exec2 exec3

Related articles: