Implementing #define macros similar to C on python

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Nov 16 01:22:25 CET 2013


On 15/11/2013 23:36, JL wrote:
> Thanks! This is the answer which I am seeking. However, I am not able to get the following line to work. I am using python 2.7.5
>
> debug_print = print
>
> Can we assign a function into a variable in this manner?
>
> On Friday, November 15, 2013 11:49:52 AM UTC+8, Chris Angelico wrote:
>> On Fri, Nov 15, 2013 at 1:29 PM, JL <lightaiyee at gmail.com> wrote:
>>
>>> One of my favorite tools in C/C++ language is the preprocessor macros.
>>
>>>
>>
>>> One example is switching certain print messages for debugging use only
>>
>>>
>>
>>> #ifdef DEBUG_ENABLE
>>
>>> DEBUG_PRINT   print
>>
>>> #else
>>
>>> DEBUG_PRINT
>>
>>>
>>
>>> Is it possible to implement something similar in python? Thank you.
>>
>>
>>
>> There are usually other ways to do things. For instance, you can
>>
>> define a function to either do something or do nothing:
>>
>>
>>
>> if debug_mode:
>>
>>      debug_print = print
>>
>> else:
>>
>>      debug_print = lambda: None
>>
>>
>>
>> debug_print("This won't be shown unless we're in debug mode!")
>>
>>
>>
>> But as Dave says, you could write a preprocessor if you need one.
>>
>>
>>
>> ChrisA

Yes but please don't top post.  Actually print is a statement in Python 
2 so your code should work if you use

from __future__ import print_function

at the top of your code.

Would you also be kind enough to read and action this 
https://wiki.python.org/moin/GoogleGroupsPython to prevent the double 
line spacing shown above, thanks.

-- 
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence




More information about the Python-list mailing list