6

I am using python for one of my projects, and i want to define some variables like #define in C so that if i want to change the value i can change it only at one place.

I know that we can use global variables. But, I don't want to specify the keyword "global" in all the functions where I use the variables.

Actually I want something like this.(This is just a random example!)

DEFINE_MAX = 100

def function1(num):
    return num < DEFINE_MAX

def function2(num):
    return num > DEFINE_MAX

The variable DEFINE_MAX might be used through out the application. So I want to define it at one common place.

So how can I do this in python?

1
  • 7
    In future, try running your code first - you have literally solved your own question. Commented Jul 29, 2014 at 7:35

1 Answer 1

14

First, if your functions don't need write access to the global variables then there is no need to declare them global inside the functions. They will be found by the usual three-namespace (local, global, builtins) name resolution search. If you ARE writing to global variables then please reconsider your design.

The code sample you provided is perfectly good Python and effectively gives you the central control you appear to need over program parameters.

Just to throw in a bit of jargon, such values are often referred to as symbolic or manifest constants.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I did not know that, only in write access to the global variable i need to define it as global.
Now you do. Isn't Stackoverflow great?
System such as Django go one further and define a settings module that any code needing access to application settings can import.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.