Do not call function if None Return value

Suppose you have a function that can return an object or None:

def foobar(arg):
   if arg == 'foo':
       return None
   else:
       return 'bar'

Now you call this method and want to do something with the object, for this example I get str, so I can call the function upper(). There are currently two possible cases where the second will fail because None has no methodupper()

foobar('sdfsdgf').upper()
foobar('foo').upper() 

of course, now this is easy to fix:

tmp = foobar('foo')
if tmp is not None:
    tmp.upper()
# or
try:
    foobar('foo').upper()
except ArgumentError:
    pass
# or
caller = lambda x: x.upper() if type(x) is str else None
caller(foobar('foo'))

but the exception handling is probably not abstract enough, and it may happen that I catch an exception that can be important (= debugging gets harder), while the first method is good, but it can lead to code increase, and the third option looks pretty good but you have to do this for all possible functions, so method one is probably the best.

, - , ?

+4
3

:

(foobar('foo') or '').upper()

, foobar() falsy.

None . None, , if .upper(), None.

+13

, , .

pymaybe maybe, None:

from pymaybe import maybe
maybe(foobar('foo')).upper()

Martijn Pieters, , None , , falsey.

, , PEP 505 , , # ?. . , , .

+4

- / :

def forward_none(func):
    def wrapper(arg):
        return None if arg is None else func(arg)
    return wrapper

, - , , , :

forward_none(str.upper)(foobar('foo'))

:

@forward_none
def do_interesting_things(value):
    # code that assumes value is not None...

do_interesting_things(None) # ignores the original code and evaluates to None
do_interesting_things("something") # as before decoration

Although in practice, if I had to, I would probably do what Martyn offers. And I would try very hard not to do this; getting into this situation is the smell of code, suggesting that we should throw an exception, and not return Nonein the first place. :)

0
source

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


All Articles