Is there any way to say that python function gets default value or keyword parameter?

def func(a, b = 100): return a + b func(a) func(a,b = 100) 

Is there a way to tell when the func function is called, the value 100 is taken from the default parameter or keyword?

+4
source share
6 answers

No, not the way you wrote your code. However, you can do:

 def func(a, b=None): if b is None: b = 100 return a + b 
+4
source

An anonymous object is a way to cover all possible cases.

 def foo(a, b=object()): if b is foo.func_defaults[0]: # no value was passed # do whatever 
+4
source

This is not very useful for business. But you can default to None instead.

 def func(a, b=None): if b is None: # b = default b b = 100 return a + b 
+2
source

You can use the object as the default, for example

 dummy = object() def func(a, b=dummy): used_default = b is dummy if used_default: b = 100 print used_default func(0) # prints True func(0, None) # prints False func(0, object()) # prints False 
+1
source

If you intend to check if b matches the default value, then do not use the default value! If you do not have to leave b optional, send a special value (possibly -1 ) to indicate an unusual case, and be sure to pay attention to this in __doc__ . Just make sure that you cannot achieve exceptional value with daily use and that exceptions written with this logic do not change sensitive areas of your code.

0
source

An alternative to other suggestions is to use the kwargs parameter, and then do something like this:

 def func(a, **kwargs): if 'b' in kwargs: print 'b was passed in' b = kwargs['b'] else: print 'b was not passed in' b = 100 return a + b a = 50 func(a) func(a, b = 100) 

Output:

 b was not passed in 150 b was passed in 150 

Since kwargs is a dictionary containing all optional parameters, you can examine this dictionary to determine what was / was not passed.

You can make search b more efficient, rather than searching kwargs twice if necessary.

0
source

Source: https://habr.com/ru/post/1398732/


All Articles