[Tutor] 42
Roeland Rengelink
roeland.rengelink at chello.nl
Sat Jun 12 05:10:33 EDT 2004
Adelein and Jeremy wrote:
>--- Roeland Rengelink <roeland.rengelink at chello.nl> wrote:
>
>
>>Gregor Lingl wrote:
>>
>>
>>
>>>What is the most convincing way to mimick this in Python?
>>>
>>>#include <stdio.h>
>>>
>>>#define SIX 1 + 5
>>>#define NINE 8 + 1
>>>
>>>int main(void) {
>>> printf("What do you get if you multiply six by nine: %d\n", SIX
>>>
>>>
>>*
>>
>>
>>> NINE);
>>> return 0;
>>>}
>>>
>>>
>>Since macro's are substituted before compilation in C. You'd have
>>to
>>substitute before iterpretation in Python. This works:
>>
>> >>> SIX = '1+5'
>> >>> NINE = '8+1'
>> >>> eval('%s*%s' % (SIX, NINE))
>>42
>>
>>
>>
>
>Then again, does this actually mimick macros? Or was the point simply
>to mimick the "amazing result"?
>
Well, it does not mimick macros in any meaningful sense of the word. My
point was basically to illustrate how macros work in C. Macro's are
handled by a preprocessor, and the compiler never 'sees' them. In this
example, the string formatting mimicks a preprocessor, and eval()
mimicks a compiler. Note that eval doesn't 'see' the string substitution
either.
Python of course, does not have a preprocessor. Hence, no macros.
Fortunately, you don't need macros. String substitution is better
handled by code. For example:
SIX = 1+5
NINE = 8+1
print SIX*NINE
Conditional 'compilation' works too. For example:
if sys.platform()=='nt':
def a_func():
"""Use this on windows""""
...
else:
def a_func():
"""Use this one elsewhere""""
...
> This is very interesting, using eval
>to do this - I figured it might be possible with eval but I wasn't
>comfortable enough with the behavior of it nor with the behavior of
>the string formatting, apparently. Learned something new.
>
>
>
As long as you didn't learn how to do macros in Python, I'm happy :)
Cheers,
Roeland
More information about the Tutor
mailing list