tags:

views:

221

answers:

6

Is it possible to make a user-defined Python function act like a statement? In other words, I'd like to be able to say:

myfunc

rather than:

myfunc()

and have it get called anyway -- the way that, say, print would.

I can already hear you all composing responses about how this is a horrible thing to do and I'm stupid for asking it and why do I want to do this and I really should do something else instead, but please take my word that it's something I need to do to debug a problem I'm having and it's not going to be checked in or used for, like, an air traffic control system.

+8  A: 

No, it is not possible.

As you can see from the Language Reference, there is no room left for extensions of the list of simple statements in the specification.

Moreover, print as a statement no longer exists in Python 3.0 and is replaced by the print() builtin function.

hop
+3  A: 

If what you're looking for is to add a new statement (like print) to Python's language, then this would not be easy. You'd probably have to modify lexer, parser and then recompile Python's C sources. A lot of work to do for a questionable convenience.

DzinX
+2  A: 

Not if you want to pass in arguments. You could do something build an object that ABUSES the __str__ method, but it is highly not recommended. You can also use other operators like overload the << operator like cout does in C++.

Evan Fosmark
Sounds good. How would that work?
mike
Wouldn't it work in the interpreter only?
DzinX
@Mike, look at creating an object and overriding the __lshift__ method. This is the method that corrosponds to the << operator. It takes in one argument which is the element being "shifted" into it.@DzinX, no it would work anywhere.
Evan Fosmark
How about abusing the __str__ method? Would that only work with "print myfunc" as opposed to just "myfunc" on its own?
mike
wouldn't even work in the interactive interpreter
hop
You can override __repr__ and it will work in the interactive interpreter. Doesn't work in general, though -- at least, not with my testing (python 2.5.1).
John Fouhy
+1  A: 

In Python 2.x print is not a function it is a statement just as if, while and def are statements.

David Locke
+2  A: 

I would not implement this, but if I was implementing this, I would give code with myfunc a special extension, write an import hook to parse the file, add the parenthesis to make it valid Python, and feed that into the interpreter.

joeforker
A: 

This probably isn't going to cover your problem, but I'll mention it anyway. If myfunc is part of a module, and you are using it like this:

from mymodule import myfunc
myfunc # I want this to turn into a function call

Then you could instead do this:

import mymodule
mymodule.myfunc # I want this to turn into a function call

You could then remove myfunc from mymodule and overload the module so it calls a particular function each time the myfunc member is requested.

too much php