3

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
paskalnikita
  • 153
  • 1
  • 3
  • 12

3 Answers3

4

You can't really specify it directly in the argument field, but you can convert it right after the function declaration:

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

It will throw an error if the passed value for pk cannot be converted to an int

EDIT: I spoke too soon, apparently you can do exactly as you did, just change things around:

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

BTW: I just did a quick research for "specify type of argument python". Please try to research easy things like so first before asking a question, you'll get an answer quicker :)

Kai
  • 398
  • 2
  • 11
0

In short, you can't guarantee types in python. When you set the default value of pk=0, you make its default value an int, but someone using your function could easily call

profile("Hello", pk="there")

which would make pk of type str. If you absolutely need to tell the user that pk must be of type int then you could do something like this:

if type(pk) != int:
    raise ValueError('pk must be of type int, got %s instead' % type(pk) )
killian95
  • 803
  • 6
  • 11
0

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
Sudarshan
  • 938
  • 14
  • 27