No macros in Python

Mike Meyer mwm at mired.org
Mon Dec 16 15:01:14 EST 2002


Lulu of the Lotus-Eaters <mertz at gnosis.cx> writes:

> The function can be implemented along the lines of:
> 
>     def with_output_to_file(fname, stmts):
>         import sys
>         orig = sys.stdout
>         sys.stdout = open(fname,'w')
>         for stmt in stmts: exec stmt
>         sys.stdout = orig
> 
> I don't know exactly how many characters might be in the hypothetical
> macro definition, but Meyer's version really doesn't seem to get you
> ANYTHING other than using a colon instead of parentheses.

First of all, you've got three bugs(*), which is why this kind of
thing should be bundled into a macro instead of forcing every
programmer to write it themselves.

Second, you've hidden the difference in the format of the statement
list. You seem to like playing formatting games with the code to make
a point rather than trying to deal with the issues. Adding that in
means you've got the parens, a list notation, and having to quote -
and compile if you want load-time syntax checking - all the
statements.

Third, what you've written is a macro. It's just that the invocation
syntax is really, *really* ugly - as described above - because you
have to kludge it.


> |> But I am opposed down to my bones to a ternary
> |> operator defined by an individual programmer in whatever idiosyncratic,
> |> perhaps inadequately tested, fashion she chooses.n
> |As opposed to having binary operators defined by an individual
> |programmer in whatever idiosyncratic, perhaps inadequately tested
> |fashion she chooses?
> The difference here is that it is the OBJECTS, not the operator, that is
> changed.  Macros change the operator itself, which I find disturbing.

In other words, it's not really the binary vs. ternary that's the
problem. It's someone potentially mucking with the meaning of things
you "know" what mean. But that's bad practice.

And you can do that with functions, to. I can define my own version of
len, and then the statement len([1, 2, 3]) won't do what you think it
should. The thing is, you're *used* to that happening with
functions. I have no problems with it happening to operators - except
that it's bad style to do that.

BTW, if you really want a ternary operator, you can do it in
Python. It's just really ugly because python doesn't have macros.

        <mike

*) 1: not closing the file. 2: not handling exceptions in the
statement list. 3: evaluating the statements in the context of
with_output_to_file instead of in the context of the invoking
function. All these can be fixed.

-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list