Search code examples
pythongoogle-app-enginewebapp2

Setting a default variable value if param is not defined


I want to assign a default value if url parameter is not set. Something like this:

try: 
    limit = self.request.get('limit')
except NameError:
    limit = 10

Of course that didn't work, that's why I'm asking. With this code, the default (10) is not being assigned.


Solution

  • dictionary.get method help says: get(...) D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

    Then, the solution is:

    try:
        limit_default_value = 10
        limit = int(self.request.get('limit', limit_default_value))
    except ValueError: #catch a string that does not like decimal
        limit = limit_default_value