-1

I have a json sample getting it from a function, and have to pass some of it's parameters to my function but if they exist.

def myfunction(var1=None):
    some code
    return

if myjson['parameter1'] == 'somestring':
    var1 = myjson['parameter1']['sub1']j

myfunction(var1=var1)

If the condition is not true, var1 will be undefined and leads to unbound local error. So what do I have to do? Is there any way to check existance in function input?

if 'var1' not in globals():
    var1 = None

I know I can use ablve code to assign var1. But I want to know if there is any better design or pythonic way pattern to do this.

I tried

myfunction(var1=var1 if 'var1' in globals())

but doesn't work.

1
  • 2
    You shouldn't have conditionally declared variables. var1 should always exist, but may have a None value. So in this case, you can always pass var1, as a None value is also the default parameter value.
    – deceze
    Commented May 28 at 13:07

2 Answers 2

2

Just always define var1 on the default None. Then only set the value if it's passed so it the function will retrieve None or myjson['parameter1']['sub1']


def myfunction(var1=None):
    some code
    return

var1 = None
if myjson['parameter1'] == 'somestring':
    var1 = myjson['parameter1']['sub1']

myfunction(var1)
1

A commonly seen arrangement is to collect arguments in a list, and then splat that list as the function's argument.

args = []
if something:
   args.append('the winner is foobar!')
if something_else():
   args.append('but you lost')
...
somefunction(*args)

You should also know about **kwargs:

kwargs = {}
if something:
    kwargs["foo"] = "with onions"
if something_else();
    kwargs["bar"] = "too much beer"
...
somefunction(**kwargs)

which is basically equivalent to

somefunction(foo="with onions", bar="too much beer")

if both conditions were true.

1
  • even better... as a dict with **kwargs
    – Anentropic
    Commented May 28 at 13:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.