[Tutor] Anyway to do something like a #define in python?

lonetwin lonetwin@yahoo.com
Thu Jul 24 03:37:01 2003


Hi there,

On Thursday 24 Jul 2003 12:24 am, Jeff Shannon wrote:
> DORSEY_EDMUND_K@LILLY.COM wrote:
> > I think the subject is pretty self explanatory but how would you go
> > about doing something like this in python?  Is there a python
> > equivalent to the C #define?  Thanks! ~Ed
     That depends ....

> No, there isn't, and on the whole that's a good thing.  #define can be
> used in a variety of different ways, most of which have a more specific
> replacement in Python.
	That's true. There isn't any exact drop-in replacement for a #define, it=20
depends on what you need to do. Before we go into that, lets get one thing=
=20
clear.

 What is a '#define' in C ??
    It's a 'preprocessor' directive that replaces all occurrences of the=20
#defined name with whatever expression you provide. That means if you have

#define ADD(x, y) x+y
#define MAX 2000

=2E.then, *before* the actual compilation stage, all occurrences of ADD and=
 MAX=20
are simply rewritten with the expressions that you provided.

ie: if somewhere you had written

printf ('%d, %d', ADD(10, 20), MAX);

	that gets replaced by

printf ('%d, %d', 10+20, 2000);

      *before* the compilation stage. The bad part about all this is, this =
may=20
cause a lot of hard to trace bugs, because during the replacement=20
(preprocessing stage) no type checking or validation is done ...and you mig=
ht=20
already know the pitfalls of automatic type conversion or incorrect type=20
specification in C.

   Anyways, back to python. Since python is any interpreted language, there=
=20
isn't any preprocessing step. Nor is there a mechanism to replace occurrenc=
es=20
of a name with an expression. On the other hand you _do_ have the ability t=
o=20
assign expressions (even functions !!) to variables. So, although the=20
following statements might reflect similar behaviour to '#define', they are=
=20
not the same thing.

>>> ADD =3D lambda x, y: x+y
>>> MAX =3D 2000
>>> def hello_world():
=2E..     print "Hello, world !"
=2E..
>>> HELLO =3D hello_world
>>>
>>> ADD(10, 20)
30
>>> print MAX
2000
>>> HELLO()
Hello, world !
>>>

HTH
Peace
Steve

=2D-=20
Never stand between a fire hydrant and a dog
		-- Murphy's Laws on Sex n=B049