Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variables(Macro) in Python

Tags:

python

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?

like image 670
user2109788 Avatar asked Jul 29 '14 07:07

user2109788


People also ask

How do you define a macro in Python?

A macro is a compile-time function that transforms a part of the program to allow functionality that cannot be expressed cleanly in normal library code. The term “syntactic” means that this sort of macro operates on the program's syntax tree.

Which command is used to define a macro variable?

Direct Assignment of Macro Variables (DEFINE-! ENDDEFINE command) The expression must be either a single token or enclosed in parentheses. The macro variable !


1 Answers

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.

like image 166
holdenweb Avatar answered Oct 27 '22 00:10

holdenweb