1

See: create method

class ExampleClass():

    def example_method(self, a: str, *, b: str) -> str:
       .
       . 
       .

I am not sure what the * means inside of the method argument list. Does this mean that there are more arguments in between a and b?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
zinglax
  • 118
  • 4

1 Answers1

2

A single * in the method/function definition makes the positional arguments, that are given to the right of the *, keyword-only arguments. That is, they are like keyword-arguments that are required.

If we simplify your example, we can see this further:

class ExampleClass:
    def example_method(self, a, *, b):
        return a, b

print(ExampleClass().example_method("First", b="Second"))
#Output: ('First', 'Second')

If we try to call the method using just positional arguments, the program crashes:

print(ExampleClass().example_method("First", "Second"))
Traceback (most recent call last):
  File ".\test4.py", line 5, in <module>
    print(ExampleClass().example_method("First", "Second"))
TypeError: example_method() takes 2 positional arguments but 3 were given

We can also still use optional keyword-arguments as well:

class ExampleClass:
    def example_method(self, a, *, b, c="c was not set"):
        return a, b, c

print(ExampleClass().example_method("First", b="Second"))
# Output: ('First', 'Second', 'c was not set')
Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20
  • Thanks so much, this definitely clears things up. That is good to know that you can still set default values for these arguments `c="c was not set"`. The syntax is misleading a bit when you first come across it, but makes sense now! THX – zinglax Dec 09 '20 at 12:34