1

Maybe a weird question. Say I have code like this:

def foo():
  print "Foo"

def bar(x):
  print x

func = foo
func()
func = bar
arg = 'a'
func(arg)

is there a way to have an "empty" argument, so that I can call assign foo() to func and then still call func(arg)?

Not just a workaround like

if arg is None:
   func()
else:
   func(arg)

3 Answers 3

4

Sure, if you use tuples/lists and argument unpacking.

def foo():
  print "Foo"

def bar(x):
  print x

args = ()
func = foo
func(*args)

func = bar
args = ('a',)
func(*args)

Result:

Foo
a
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, exactly what I was looking for
1

Yes, use the splat operator

args = []
func = foo
func(*args)
func = bar
args = ["Hello world!"]
func(*args)

"Hello World!"

You can even use dictionaries to do this sort of thing

funcs = (foo, bar)
func_dict = {func.__name__: func for func in funcs}
args = []
func_dict["foo"](*args)

Comments

0

try this

def foo(arg=None):
    print "Foo"

or use this

def foo(*arg):
    print "foo"

then you may call it how ever you want

arg = 'a'
func = foo
func(arg)
func = bar
func(arg)

or as others have pointed out use

arg=()
func=foo
func(*arg)
arg=('hello',)
func(*arg)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.