Search code examples
pythonfunctionintdefault

Set default value and type for parameter


How can I do something like this:

def profile(request, pk=0 : int):
    #to do

I need pk to be int (without converting in function).

Like this:

def profile(request, pk: int):

If pk empty - set value to 0 and type to int.


Solution

  • My code works for any input type of pk: integer, string with integer, string without integer

    import re
        def intCheck(pk):
          contains_number = bool(re.search(r'\d', pk))
          if contains_number:
            return int(re.search(r'\d+', pk).group())
          else:
            return 0
    
    def profile(request, pk=0):
        pk = intCheck(pk)
        print(request + " " + str(pk))
    
    profile('request', "232")
    profile('request', 123)
    profile('request', "no number")
    

    Output:

    request 232
    request 123
    request 0