Search code examples
pythonmypy

mypy "too many arguments" when declaring @property function


I do not understand why mypy does not like this @property method declaration:

@property
def cc_lemmas_dict(self, tag_delim='+', max_cycles=0) -> Dict[str, Set[str]]:

When I run mypy on this module, I get a Too many arguments error:

$ mypy src/lexc_parser/
src/lexc_parser/lexicon.py:81: error: Too many arguments
Found 1 error in 1 file (checked 7 source files)

I have searched online, but I cannot find any reason why mypy doesn't like this. Any ideas?


Solution

  • Adding @property means that you call the method simply by accessing it (no parentheses needed). Here's a full example:

    class A:
        @property
        def f(self, x='+'):
            return x
    a = A()
    print(a.f)
    print(a.f('-'))  # error
    

    Note that a.f returns '+', meaning that a.f was called, though we did not supply parentheses. This is due to @property. This also means that any additional arguments to f are superfluous, as they cannot be specified. In effect, a.f(x) (with @property) corresponds to a.f()(x) (without property), leaving no room for supplying x as an argument to f. Indeed, in the example above, the error is

    'str' object is not callable

    as a.f() first returns x which is the string '+' (the a.f part), which then is called due to ().

    That mypy picks this up is nice!