Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables across multiple files in python

I have a modules.py file :

global dns_server_ip
def SetVnetGlobalParameters():
    dns_server_ip = '192.168.3.120'

And I’m importing this file in say abc.py file

from modules import *
SetVnetGlobalParameters()
print(dns_server_ip)

But ‘dns_server_ip’ is still not accessible.

I want to set global parameters through Function only. Any help would be greatly appreciated! Thanks..

like image 661
ShitalSavekar Avatar asked Dec 12 '22 15:12

ShitalSavekar


2 Answers

As per your question I understand you are the beginner to the python.

While importing the modules you have use just module name and don't need to include the extension or suffix(py) and in your code you miss the starting single quote .

Here is your modified code: it is modules.py

dns_server_ip = ''
def SetVnetGlobalParameters():
    global dns_server_ip
    dns_server_ip = '192.168.3.120′

Here is your abc.py

import modules 
modules.SetVnetGlobalParameters()
print modules.dns_server_ip

Here through the global keyword we are telling the python interpreter to change or point out the global variable instead of local variable and always the variable would be either global or local If the variable is both (local and global) you will get python UnboundLocalError exception and if you did not put that global keyword

global dns_server_ip

The dns_server_ip will be created as a new local variable . The keyword global intended to with in the functions only

you can check global keyword,python modules

like image 152
neotam Avatar answered Feb 09 '23 02:02

neotam


In modules.py

dns_server_ip = None
def SetVnetGlobalParameters():
    global dns_server_ip
    dns_server_ip = '192.168.3.120'

In abc.py

import modules
modules.SetVnetGlobalParameters()
print(modules.dns_server_ip)
like image 41
Zangetsu Avatar answered Feb 09 '23 03:02

Zangetsu