I want to define a function without anything in it body. In C++, I can
do something like the following because I can use "{}" to denote an
empty function body. Since python use indentation, I am not sure how
to do it. Can somebody let me know how to do it in python?
void f() {
}
Regards,
Peng
Syntactically, there has to be something in the function definition. It can
be a `pass` statement, or a doc string, though:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... "empty function"
...
>>> f()
>>> print f()
None
>>> def g():
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
>>> def h():
... pass
...
>>> print h()
None
>>>
Cheers, Mel.
def rubbish_do_nothing():
pass
- Hendrik
Python has two possibilities to create an empty function. The others
already told you aber the pass statement. The other way is a function
with a doc string
def func():
"""No op function
"""
Surprised no one has mentioned this yet, but since it's a function, and
in python all functions return values (whether explicitly or implicitly,
a simple "return" works and, to me, does much more to inform the reader
that "this function does nothing".
def f():
return
> Hi,
>
> I want to define a function without anything in it body.
[...]
I usually define void functions as:
def myfunction():
raise NotImplementedError("You forgot to implement me!")
so I keep safe from leaving orphaned functions all over my code.
There are more than just two possibilities. Here are three trivial
variations on the same technique:
def func():
return
def func():
return None
lambda: None
and two slightly more complex variations:
new.function(compile("", "", "exec"), {})
# given some existing function f:
type(f)(compile("", "", "exec"), {})
--
Steven