0

I am planning to write a routine to achieve below functionality: According to the "method", and "before" and "after", compute the expense. Not sure if passing a json as an input of the function is a good practice? Does it mean the function is trying to achieve too much? When I assign a default value to "target", Pycharm gives warning "mutable object as default argument".

def assign_expense(target={'fly':{'before':'US', 'after':'JP'}, 'walk':{'before':'blockA', 'after':'blockB'})
  method, before, after = abstract_param_from_json(target)
  if method='fly':
      if before=='US', after=='JP':
          func_fly_US_JP

      elif before=='MXN', after=='CAD':
          func_fly_MX_CAD
  if method='walk':
      if before=='blockA', after=='blockB':
               func_A_to_B

      if before=='blockC', after=='blockZ':
               func_C_to_Z
Lisa
  • 4,126
  • 12
  • 42
  • 71
  • 1
    You should be very careful about [mutable default arguments](https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments). They don't necessarily behave the way you think they should (hence the warning from Pycharm). – Jonah Bishop Nov 27 '18 at 01:47

1 Answers1

2

Regarding your warning mutable object as default argument

Please refer the following

https://docs.quantifiedcode.com/python-anti-patterns/correctness/mutable_default_value_as_argument.html

"Least Astonishment" and the Mutable Default Argument

Mutable objects as default arguments behave like a static variable

And regarding passing JSON as function input, I don't think it is a bad practice by itself unless the function is doing many things on the JSON.

Ex: If you need to delete/process a particular set of keys in the JSON, you need to pass JSON to the function that does the job.

Krishna
  • 924
  • 1
  • 7
  • 28