-1

I see many similar questions, but nothing that is exactly the same as my problem, so I have done my research.

I'm trying to access this variable operatingSystem from my main file in my function install. Now, I know I could pass it with install(operatingSystem) but I have 10 other variables like it and I don't want to pass them all.

The variable is defined at the start of the file as global operatingSystem then later assigned a string (either osx, win, or linux) when my main file gets the operating system.

However when I try to use operatingSystem in my install function then it just errors. Do I need to call it as global operatingSystem inside my function? Or do I have to do something else?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
STFLightning
  • 83
  • 1
  • 1
  • 7
  • 1
    How exactly do you *"try to use `operatingSystem`"*? Can you be more specific than *"it just errors"*? Please see http://stackoverflow.com/help/mcve – jonrsharpe Apr 02 '15 at 10:37
  • `global operatingSystem`, is the way, IMO. – pnv Apr 02 '15 at 10:38
  • 2
    @pnv `global` is almost never *"the way"*; if you have lots of parameters, consider refactoring into a Parameter Object: http://sourcemaking.com/refactoring/introduce-parameter-object – jonrsharpe Apr 02 '15 at 10:39
  • I meant you can make a global of those variables, something like `global_var_to_be_access_dict` and then access that in desired function. – pnv Apr 02 '15 at 10:46
  • 2
    @pnv but there is no need to use the `global` keyword in that case. – Daniel Roseman Apr 02 '15 at 10:47
  • Or I didn't get the question, will read the link. – pnv Apr 02 '15 at 10:48

2 Answers2

1

A global variable can be freely read in a function. To modify it, you need to use the "global" keyword. It's all there. That is if I understand your question correctly.

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print globvar     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1
Community
  • 1
  • 1
rfmind
  • 58
  • 1
  • 6
0

I didnt get actually what you are expecting.Assuming

In main.py

operatingSystem = "linux"

In yourfile.py

from main import operatingSystem
>>>operatingSystem
"linux"

That is no need of global here.So

install(operatingSystem) #is possible
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49