0

How to set optional parameter of function to a list?

def fun1(text, where = my_list):
    #my_list.append(text)
    where.append(text)
    print(where)
    #return where

my_list = []
fun1('hi')
print(my_list)

# currently
#['hi']
#[]
# expected
#['hi']
#['hi']

I am getting an undefined name my_list error in Spyder.

rtep
  • 13
  • 3
  • 3
    You **don't** want to do that. https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – DeepSpace Jan 26 '20 at 14:31
  • put this line `my_list = []` before your `def`. but you should avoid having a mutable as a default argument, that's a pretty common "gotcha" in python – Nullman Jan 26 '20 at 14:32
  • It's very bad architectural solution, **don't do that**. – Olvin Roght Jan 26 '20 at 14:32
  • Why is it bad from design pov? If I call the function m times and n times it concerns my_list where n is close to m, it makes kind of sense? – rtep Jan 26 '20 at 14:35
  • Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – AMC Jan 26 '20 at 21:31
  • _Why is it bad from design pov?_ Did you read what @DeepSpace shared? – AMC Jan 26 '20 at 21:32

2 Answers2

1

you should use **kwargs to set any unexpected argument in your function.And use kwargs['where'] to achieve the 'where' key,like this :

def fun1(text, **kwargs):
    kwargs['where'].append(text)
    print(kwargs['where'])

my_list = []
fun1('hi',where=my_list)
print(my_list)
Negar37
  • 352
  • 1
  • 8
0

I think that you should define your list before your function like this:

my_list = []
def fun1(text, where = my_list):
  #my_list.append(text)
  where.append(text)
  print(where)
  #return where
fun1('hi')

And don't use print(my_list) if you want to have it printed out once. You print it as where inside of fun1()