= Try to exclude the template?

I find this design template a lot:

try: year = int(request.GET['year'])
except: year = 0

A block trycan either fail because the key does not exist, or because it is not int, but I don't care. I just need a reasonable value at the end.

Shouldn't there be a better way to do this? Or at least a way to do this on the same line? Sort of:

year = int(request.GET['year']) except 0

Or do you use this template too?


Before answering, I already know about request.GET.get('year',0), but you can still get a value error. Wrapping this in a try / catch block to catch a value error means that the default value appears in my code twice. IMO is even worse.

+3
source share
4 answers

:

def get_int(request, name, default=0):
    try:
        val = int(request.GET[name])
    except (ValueError, KeyError):
        val = default
    return val

year = get_int(request, 'year')

try/catch , .

+5

, get()

year = int(request.GET.get("year", 0))

, - . GET ['year'], , 0. KeyError, ValueError .GET ['year'], int.

(try/except), Python EAFP.

EDIT:

, :

def myGet(obj, key, type, defaultval):
    try:
        return type(obj.get(key, defaultval))
    except ValueError:
        return defaultval



# In your code
year = myGet(request.GET, 'year', int, 0)
+10

?

- ""...:

def safeget(adict, key, type, default):
    try: return type(adict.get(key, default))
    except (ValueError, TypeError): return default

year = safeget(request.GET, 'year', int, 0)

FWIW, , - "" - , , , ( , - , , 201o ( 0 o , ), , 0. , - .

, safeget, , ( , , !), , ""! -)

+6

( ), , get():

try:
    year = int(request.GET.get("year", 0))
except ValueError:
    year = 0

, , .

+2

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


All Articles