views:

174

answers:

3

In python is it possible to have the above code without raising an exception ?

def myfunc():
    pass

# TypeError myfunc() takes no arguments (1 given)
myfunc('param')

Usually in php in some circumstances I launch a function without parameters and then retrieve the parameters inside the function.

In practice I don't want to declare arguments in myfunc and then passing some arguments to it. The only one solution I found is myfunc(*arg). Are there any other methods ?

+4  A: 

Sure can!

You can define variable length parameter lists like so:

def foo(*args):
    print len(args)

args is a tuple of your parameters so calling:

foo(1,2)

gives you the tuple (1, 2) inside your function.

Dana
`args` will actually be a tuple.
Mike Graham
Oh yeah! Fixed!
Dana
+6  A: 

There are two ways to pass args in

By Position

>>> def myfunc(*args):
...  print "args", args
...
>>> myfunc("param")
args ('param',)

By Keyword

>>> def myfunc(**kw):
...  print "kw", kw
... 
>>> myfunc(param="param")
kw {'param': 'param'}

And you can use a combination of both

>>> def myfunc(*args, **kw):
...  print "args", args
...  print "kw", kw
... 
>>> myfunc("param")
args ('param',)
kw {}
>>>
>>> myfunc(param="param")
args ()
kw {'param': 'param'}
>>>
>>> myfunc("param", anotherparam="anotherparam")
args ('param',)
kw {'anotherparam': 'anotherparam'}
gnibbler
+3  A: 
>>> def myFunc(*args, **kwargs):
...   # This function accepts arbitary arguments:
...   # Keywords arguments are available in the kwargs dict;
...   # Regular arguments are in the args tuple.
...   # (This behaviour is dictated by the stars, not by
...   #  the name of the formal parameters.)
...   print args, kwargs
...
>>> myFunc()
() {}
>>> myFunc(2)
(2,) {}
>>> myFunc(2,5)
(2, 5) {}
>>> myFunc(b = 3)
() {'b': 3}
>>> import dis
>>> dis.dis(myFunc)
  1           0 LOAD_FAST                0 (args)
              3 PRINT_ITEM
              4 LOAD_FAST                1 (kwargs)
              7 PRINT_ITEM
              8 PRINT_NEWLINE
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

And to actually answer the question: no, I do not believe there are other ways.

The main reason is pretty simple: C python is stack based. A function that doesn't require parameters will not have space allocated for it on the stack (myFunc, instead, has them in position 0 and 1). (see comments)

An additional point is, how would you access the parameters otherwise?

badp
The stack comment is besides the point. Python is stack-based, but argument passing (and parsing) is not (arguments are always a single item on the stack, even when there are no arguments.) The reason Python doesn't ignore arguments is because it would **hide errors**.
Thomas Wouters
It's indeed quite possible I'm misreading what dis tells me :)
badp