0

In Python, is it possible to make mandatory to name required arguments of a function when the function is invoked, without giving the arguments a default value?

for example:

def return_apparence(eyes_color, shirt_color):
    print("my eyes are %s.\n" % eyes_color)
    print("my shirt is %s." % shirt_color)

I would like to re-write this function without giving its arguments a default value and so that when it is invoked, arguments must be named with specific keywords (such as eyes_color, shirt_color)? like this:

return_apparence(eyes_color="blue", shirt_color="red")

my eyes are blue
my shirt is red

How can I do it?

Why I am asking this

This because I would like to avoid the function to be called by mistake with inverted arguments, like this:

def return_apparence(eyes_color, shirt_color):
    print("my eyes are %s.\n" % eyes_color)
    print("my shirt is %s." % shirt_color)

return_apparence("red", "blue")

my eyes are red ---- (this can't be)
my shirt is blue

Tms91
  • 3,456
  • 6
  • 40
  • 74
  • AFAIK, I don't think that's possible. To avoid the confusion I think you should just write proper documentation for your function (with examples if necessary) and clearly understood argument names (with type hints, if necessary). – Mubin Sep 07 '21 at 13:37
  • 1
    I confirm this question is duplicate of https://stackoverflow.com/questions/2965271/forced-naming-of-parameters-in-python (my bad!), and in my case, the solution is to put the bare asterisk at the beginning of the arguments tuple, like so: `def return_apparence(*, eyes_color, shirt_color):` , so that the developer is forced to name `eyes_color` and `shirt_color` when invoking the function – Tms91 Sep 07 '21 at 14:21

0 Answers0