conditional passing of arguments to methods in python

  • Last Update :
  • Techknowledgy :

If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:

>>> def func(a = 0, b = 10):
   ...
   return a + b
      ...
      >>>
      args = {
         'a': 15,
         'b': 15
      } >>>
      func( ** args)
30
   >>>
   args = {
      'a': 15
   } >>>
   func( ** args)
25
   >>>
   args = {
      'b': 6
   } >>>
   func( ** args)
6
   >>>
   args = {} >>>
   func( ** args)
10

or just:

>>> func( ** {
   'a': 7
})
17

You can add a decorator that would eliminate None arguments:

def skip_nones(fun):
   def _( * args, ** kwargs):
   for a, v in zip(fun.__code__.co_varnames, args):
   if v is not None:
   kwargs[a] = v
return fun( ** kwargs)
return _

@skip_nones
def func(a = 10, b = 20):
   print a, b

func(None, None) # 10 20
func(11, None) # 11 20
func(None, 33) # 10 33

Going by the now-deleted comments to the question that the check is meant to be for the variables being None rather than being falsey, change func so that it handles the arguments being None:

def func(a = None, b = None):
   if a is None:
   a = 0
if b is None:
   b = 10

to solve your specific question I would do:

args = {
   'a': a,
   'b': b
}
for varName, varVal in args.items():
   if not varVal:
   del args[varName]
f( ** args)

But the most pythonic way would be to use None as the default value in your function:

f(a = None, b = None):
   a = 10
if a is None
else a
   ...

Consider the following:

>>> def func(a,b):
... a = a if a else 0
... b = b if b else 10
... return a+b
...
>>> a = b = None
>>> func(a,b)
10
>>> a = 5
>>> b = 2
>>> func(a,b)
7
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
      TypeError: func() takes exactly 2 arguments (0 given)

However in your snippet, because you have given them defaults in the method signature they look like they are optional, but in fact they just have defaults assigned to them.

>>> def func(a = 0, b = 10):
   ...
   return a + b
      ...
      >>>
      func()
10

You can confirm this by checking the argument list inside the body of the method:

>>> def func(a = b, b = 10):
   ...print locals().keys()
   ...
   >>>
   func()['a', 'b']

Why not pass that logic to the function?

def func(a, b):
   a = a or 0
b = b or 10
return a + b

Suggestion : 2

I have a function with two optional parameters:,Python – Argparse optional positional arguments,If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:,Python – Does Python have a ternary conditional operator

I have a function with two optional parameters:

def func(a = 0, b = 10):
   return a + b

Somewhere else in my code I am doing some conditional argument passing like:

if a and b:
   return func(a, b)
elif a:
   return func(a)
elif b:
   return func(b = b)
else:
   return func()

I may have several functions like func: func1, func2 and func3 would all contain the

a = a or 0
b = b or 10

If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:

>>> def func(a = 0, b = 10):
   ...
   return a + b
      ...
      >>>
      args = {
         'a': 15,
         'b': 15
      } >>>
      func( ** args)
30
   >>>
   args = {
      'a': 15
   } >>>
   func( ** args)
25
   >>>
   args = {
      'b': 6
   } >>>
   func( ** args)
6
   >>>
   args = {} >>>
   func( ** args)
10

or just:

>>> func( ** {
   'a': 7
})
17

Suggestion : 3

If / and * are not present in the function definition, arguments may be passed to a function by position or by keyword.,The first function definition, standard_arg, the most familiar form, places no restrictions on the calling convention and arguments may be passed by position or keyword:,The second function pos_only_arg is restricted to only use positional parameters as there is a / in the function definition:,Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names or you want to prevent users relying on the position of the argument being passed.

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42 >>>
   if x < 0:
   ...x = 0
   ...print('Negative changed to zero')
   ...elif x == 0:
   ...print('Zero')
   ...elif x == 1:
   ...print('Single')
   ...
   else:
      ...print('More')
      ...
      More
>>> # Measure some strings:
   ...words = ['cat', 'window', 'defenestrate'] >>>
   for w in words:
   ...print(w, len(w))
   ...
   cat 3
window 6
defenestrate 12
# Create a sample collection
users = {
   'Hans': 'active',
   'Éléonore': 'inactive',
   '景太郎': 'active'
}

# Strategy: Iterate over a copy
for user, status in users.copy().items():
   if status == 'inactive':
   del users[user]

# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
   if status == 'active':
   active_users[user] = status
>>>
for i in range(5):
   ...print(i)
   ...
   0
1
2
3
4
>>> list(range(5, 10))[5, 6, 7, 8, 9]

   >>>
   list(range(0, 10, 3))[0, 3, 6, 9]

   >>>
   list(range(-10, -100, -30))[-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>>
   for i in range(len(a)):
   ...print(i, a[i])
   ...
   0 Mary
1 had
2 a
3 little
4 lamb

Suggestion : 4

By Bernd Klein. Last modified: 29 Jun 2022.

def ref_demo(x):
   print("x=", x, " id=", id(x))
x = 42
print("x=", x, " id=", id(x))
x = 9
id(x)
140709692940944
ref_demo(x)
x = 9 id = 140709692940944
x = 42 id = 140709692942000
id(x)

Suggestion : 5

When you define an argument in the signature of the method, you explicity make it required. In your snippet, what you are doing is giving it a default value - not making them optional. ,By default, all methods in Python take variable arguments.,However in your snippet, because you have given them defaults in the method signature they look like they are optional, but in fact they just have defaults assigned to them.,In this snippet, both a and b are required, since I didn't define any default values. They are not optional.

If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:

>>> def func(a = 0, b = 10): ...
   return a + b... >>> args = {
      'a': 15,
      'b': 15
   } >>> func( ** args) 30 >>> args = {
      'a': 15
   } >>> func( ** args) 25 >>> args = {
      'b': 6
   } >>> func( ** args) 6 >>> args = {} >>> func( ** args) 10

or just:

>>> func( ** {
   'a': 7
}) 17

Going by the now-deleted comments to the question that the check is meant to be for the variables being None rather than being falsey, change func so that it handles the arguments being None:

def func(a = None, b = None): if a is None: a = 0
if b is None: b = 10

You can add a decorator that would eliminate None arguments:

def skip_nones(fun): def _( * args, ** kwargs): for a, v in zip(fun.__code__.co_varnames, args): if v is not None: kwargs[a] = v
return fun( ** kwargs) return _ @skip_nones def func(a = 10, b = 20): print a, b func(None, None) # 10 20 func(11, None) # 11 20 func(None, 33) # 10 33

to solve your specific question I would do:

args = {
   'a': a,
   'b': b
}
for varName, varVal in args.items(): if not varVal: del args[varName] f( ** args)

But the most pythonic way would be to use None as the default value in your function:

f(a = None, b = None): a = 10
if a is None
else a...

Consider the following:

>>> def func(a,b): ... a = a if a else 0 ... b = b if b else 10 ... return a+b ... >>> a = b = None >>> func(a,b) 10 >>> a = 5 >>> b = 2 >>> func(a,b) 7 >>> func() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: func() takes exactly 2 arguments (0 given)

However in your snippet, because you have given them defaults in the method signature they look like they are optional, but in fact they just have defaults assigned to them.

>>> def func(a = 0, b = 10): ...
   return a + b... >>> func() 10

You can confirm this by checking the argument list inside the body of the method:

>>> def func(a = b, b = 10): ...print locals().keys()... >>> func()['a', 'b']

Suggestion : 6

Last Updated : 04 Sep, 2021,GATE CS 2021 Syllabus

Output:

4
1099

Suggestion : 7

At a very basic level, you can define a function without parameters - an empty function. This function will return whatever you’ve specified after it is called.,Exercise 3: Write a function called first_word that takes a list of character strings as input and returns the first element of the list in alphabetical order. For example, your function should work like this:,In the above examples, we’ve created functions that print some result to our screen when called. Often, however, we want our functions to work as part of a larger workflow. This is accomplished with the return statement, which allows the output of functions to be assigned to a new variable.,Functions include a definition and parameters, and are specified with def as follows:

def myfunction(parameter1, parameter2, parameter3):
   ""
"Your code goes here"
""
myfunction(arg1, arg2, arg3)
def print_five():
   print(5)
print_five()
5
def divide_by_two(x):
   print(x / 2)

divide_by_two(11)