0

I want to arrange my function's variables. When i try to add to the first one default value i am getting a SyntaxError.

class a():
    def __init__(self,b = "hey",c,d):
        self.b = b
        self.c = c
        self.d = d
    def __init__(self,b = "hey",c,d):
                                ^
SyntaxError: non-default argument follows default argument

But when I try to add to the last one I don't get any error.

class a():
    def __init__(self,b,c,d = "hey"):
        self.b = b
        self.c = c
        self.d = d

I just want to edit the default value of a middle or first variable. How can i do it?

swarthy03
  • 5
  • 1
  • 1
    Does this answer your question? [Using default arguments before positional arguments](https://stackoverflow.com/questions/12332195/using-default-arguments-before-positional-arguments) – mkrieger1 Mar 06 '23 at 17:50
  • What you want would require Python to assign arguments to parameters differently depending on which end has the default value(s), rather than always assigning left to right as needed. But what if you defined `def __init__(self, b="hey", c, d="there")`. What would `a("foo", "bar")` assign its two arguments to? – chepner Mar 06 '23 at 18:12

1 Answers1

2

You can do this if you use keyword-only arguments, which you can specify by adding a * to the arg list:

class a():
    def __init__(self, *, b = "hey", c, d):
        self.b = b
        self.c = c
        self.d = d

If the arguments are specified positionally and some of them have defaults, it can be ambiguous which argument is which, which is why this is disallowed (unless all the defaults are at the end, in which case the ambiguity is resolved by rebinding all the defaults in order after the required arguments).

If the arguments are always specified as keyword arguments, there is no ambiguity because you always indicate which argument is which.

Samwise
  • 68,105
  • 3
  • 30
  • 44