Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Preprocessor Macro equivalent for Python

I use to define macros (not just constants) in C like

#define loop(i,a,b) for(i=a; i<b; ++i)
#define long_f(a,b,c) (a*0.123 + a*b*5.6 - 0.235*c + 7.23*c - 5*a*a + 1.5)

Is there a way of doing this in python using a preprocess instead of a function?

*By preprocess I mean something that replaces the occurrences of the definition before running the code (actually not the whole code but the rest of the code, because since it's part of the code, I guess it will replace everything during runtime).

If there is, worth it? Will there be a significant difference in run time?

like image 619
Carlos Pinzón Avatar asked Apr 08 '16 04:04

Carlos Pinzón


People also ask

Does Python have a preprocessor?

A macro preprocessor based on the Python language - PYM - has been introduced, that makes it possible to use Python for defining macros for arbitrary other languages or text files.

Is there a macro in Python?

You can write an Excel macro in python to do whatever you would previously have used VBA for. Macros work in a very similar way to worksheet functions. To register a function as a macro you use the xl_macro decorator. Macros are useful as they can be called when GUI elements (buttons, checkboxes etc.)

What is the equivalent of #define in Python?

In Python, defining the function works as follows. def is the keyword for defining a function. The function name is followed by parameter(s) in ().

Is macro and preprocessor same?

Preporcessor: the program that does the preprocessing (file inclusion, macro expansion, conditional compilation). Macro: a word defined by the #define preprocessor directive that evaluates to some other expression. Preprocessor directive: a special #-keyword, recognized by the preprocessor.


1 Answers

Is there a way? Yes. There's always a way. Should you do it? Probably not.

Just define a function that does what you want. If you are just concerned about code getting really long and want a one-liner, you can use a lambda function.

long_f = lambda a,b,c: a*0.123 + a*b*5.6 - 0.235*c + 7.23*c - 5*a*a + 1.5
long_f(1,2,3) == 28.808

And of course your first example is already way prettier in Python.

for i in range(a,b):
    ...

Edit: for completeness, I should answer the question as asked. If you ABSOLUTELY MUST preproccess your Python code, you can use any programming language designed for templating things like web pages. For example, I've heard of PHP being used for preprocessing code. Instead of HTML, you write your code. When you want something preprocessesed, you do your PHP blocks.

like image 54
phsyron Avatar answered Oct 19 '22 19:10

phsyron