Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to default parameter of function

Tags:

python

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.

like image 871
reox Avatar asked Aug 30 '26 02:08

reox


1 Answers

>>> 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]))
like image 180
unutbu Avatar answered Aug 31 '26 18:08

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!