Home > Enterprise >  Unable to understand what "*" does if specified without variable name
Unable to understand what "*" does if specified without variable name

Time:06-27

class Field:

    def __init__(self, *, read_only=False, write_only=False):
        do_something()

what's the use of specifying "*" and how it is different from using *args?

CodePudding user response:

It means the constructor does not accept positional arguments but only keyword arguments.

class Field:

    def __init__(self, *, read_only=False, write_only=False):
        pass
>>> Field(True, False)
...
TypeError: __init__() takes 1 positional argument but 3 were given

>>> Field(read_only=True, write_only=False)
<__main__.Field at 0x7f3cd95fde20>

CodePudding user response:

According to the docs.

In the following example, parameters a and b are positional-only, while c or d can be positional or keyword, and e or f are required to be keywords:

def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

So according to your code, the constructor can only take keyword arguments.

  • Related