2

is it possible to append to a default function parameter or to get the value of the function parameter from outside?

for example:

def foo(bar, foo="baz"):
    print(bar, foo)

foo("hello", "world") # print "hello world"
foo("hello", foo="world") # print "hello world" as well
foo("hello") # print "hello baz"
foo("hello", foo<append it>"bla") # how? want to print "hello bazbla"
print("default value of foo's foo parameter:", [magic here])

i dont think this is a good practise but I'm curious.

reox
  • 5,036
  • 11
  • 53
  • 98
  • What's wrong about calling `foo("hello", "bazbla")`? Do you want to modify the function itself? – bereal Jul 01 '14 at 08:51
  • 1
    possible duplicate of [Get a function argument's default value?](http://stackoverflow.com/questions/12627118/get-a-function-arguments-default-value) – Jacobo de Vera Jul 01 '14 at 08:52

1 Answers1

2
>>> foo.__defaults__
('baz',)

The __defaults__ attribute is documented here.


So, to alter the foo parameter using the default value, you could use string formatting:

foo("hello", foo="{}bla".format(foo.__defaults__[0]))
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677