473,387 Members | 1,540 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

c macros in python.

Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?

May 6 '07 #1
6 2569
no*************@gmail.com a écrit :
Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?
First: Python has no macro facility.

But in this particular case, it is very simple. Just add:
o = outfile.write
after the variable outfile is initialized.
It is not a macro (just another name for a function object)
but it looks the same...

--
Amaury
May 6 '07 #2
On May 7, 7:01 am, noagbodjivic...@gmail.com wrote:
Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?
Functions and methods are first-class citizens in Python; all you have
to do is:

o = outfile.write
o('blah blah\n')
o('etc\n')

Bonus: your code will run (measurably but almost imperceptibly)
faster, because you save a method lookup every time you use it.This
would not happen with a text-substituting macro approach.

HTH,
John

May 6 '07 #3
Great python!!!
May 6 '07 #4
ici
On May 7, 12:01 am, noagbodjivic...@gmail.com wrote:
Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?
All in Python is pointer to object, and functions too, so

o = outfile.write
o("Some Text")

You can redirect print to file also:

print >outfile, "Text", var1, var2[2:]
or
o = outfile
print >o, "Text", var1, var2[2:]
:)
May 6 '07 #5
On 2007-05-06, no*************@gmail.com <no*************@gmail.comwrote:
Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?
Just in case you don't know, you can write an arbitrary number of lines in one
write. Below is how I format a usage() message of a program in one write call:

def usage(fp):
fp.write("Usage: convert options [infile] [outfile]\n"
"with\n"
" options\n"
"\t--prefix=<name-prefix>\t(obligatory)\n"
"\t--write-size\t\tWrite a line containing the size\n"
"\t--append-zero\t\tAppend a terminating 0 byte\n")

ie one multi-line write call. Pyhon concatenates two consequtive string
literals for us. Unfortunately, this gets less pretty when inserting variable
values.


In other code generation code, I normally use a list of lines. Rather than
writing everything directly to file, I make a list data structure containing
lines, then dump the list to file, as in:

lines = []
gencode_first(lines)
gencode_second(lines)
lines.append("the end")
write_lines(lines)

where write_lines() is

def write_lines(lines):
for line in lines:
outfile.write(line)
outfile.write('\n')

(i left out the opening and closing of outfile).
I normally do not include the \n in the list but instead add it while writing
it to file. This makes life much easier since there are no special last-value
problems in the code generator itself.
The nice thing here is that 'lines' is a normal data structure which you can
manipulate if you like.


For more demanding code generators (ie C or C++ code) I use the concept
'sections'. At a global level, the generated code has an 'include',
'declarations', 'definitions', and 'main' section, each section is a list of
lines.
I use a dictionary for this, like

output = { 'incl': [], 'decl': [], 'def': [], 'main': [] }

then pass around this in the code generator.
Each part of the generator can write in each section, for example when defining
a C function, you can write the declaration in the decl section and the
definition in the def section at the same time.
For example

def write_c_function(output):
output['decl'].append('int mycfunc(void);')
output['def'].extend(['int myfunc(void)', '{' 'return 131;', }' ])

Reducing such a dictionary to a list is then something like

def make_lines(sec_list, output):
lines = []
for sec in sec_list:
lines.extend(output[sec])
return lines

And outputting the code is then something like

write_lines(make_lines(['incl', 'decl', 'def', 'main'], output))

In this way you can abstract away from the order of code as required by the
target language and instead generate code in a nicer order.
Note that this section trick can be done recursively. for example, a function
can be thought of as a number of sections like

funcoutput = { 'header': [], 'opening-bracket' : [], 'localvars':[], 'closing-bracket': [] }

so you can generate a function using sections as well, then at the end reduce
funcoutput to a list of lines, and insert that in a section of the global
'output'.


Last but not least, if you replace the lists by an object, you can do much
smarter things. For example, in general you don't want to have double #include
lines in the 'incl' section. Instead of worrying about generation of doubles,
just make an object that behaves like a list but silently drops doubles.
In the same way, you can create a list-like object that handles indenting for
you.

The possibilities here are endless!!
Good luck with your code generation problem, I hope I gave you some ideas of
alternative solutions that are available.

Albert

May 7 '07 #6
In article <f1**********@talisker.lacave.net>,
Amaury Forgeot d'Arc <af*******@neuf.frwrote:
>no*************@gmail.com a écrit :
>Hey,

I'm writing a script to generate code. I'm a bit tired of typing
outfile.write(....). Does python have a way to c-like macros? Every
instance of o(...) in the code will be replaced by outfile.write(...)?

First: Python has no macro facility.
May 7 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Chris Reedy | last post by:
For everyone - Apologies for the length of this message. If you don't want to look at the long example, you can skip to the end of the message. And for the Python gurus among you, if you can...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
16
by: mike420 | last post by:
Tayss wrote: > > app = wxPySimpleApp() > frame = MainWindow(None, -1, "A window") > frame.Show(True) > app.MainLoop() > Why do you need a macro for that? Why don't you just write
0
by: Mark Asbach | last post by:
Hi Python-Pros, I'm working on a project using an embedded and extended python interpreter. We use autoconf/automake/libtool and have our own autoconf macros for detecting a python installation....
37
by: michele.simionato | last post by:
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any...
37
by: seberino | last post by:
I've been reading the beloved Paul Graham's "Hackers and Painters". He claims he developed a web app at light speed using Lisp and lots of macros. It got me curious if Lisp is inherently faster...
28
by: liorm | last post by:
Hi everyone, I need to write a web app, that will support millions of user accounts, template-based user pages and files upload. The client is going to be written in Flash. I wondered if I coudl...
3
by: dan_roman | last post by:
Hi, I developed a script with a nice interface in Tkinter that allows me to edit some formulas and to generate an Excel worksheet with VBA macros within it. The script runs perfectlly in Office...
5
by: sturlamolden | last post by:
Hello The Lisp crowd always brags about their magical macros. I was wondering if it is possible to emulate some of the functionality in Python using a function decorator that evals Python code...
1
by: Lawrence D'Oliveiro | last post by:
Has anyone been able to run user-defined Python macros in OpenOffice.org 3.0? I had one in ~/.ooo-2.0/user/Scripts/python/try.py which did work under Ooo2.x. So I put the same thing in...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.