kernel dies after @property in python

Question:

I am running the following code in Jupyter:

from typing import List

class dummy:
    def __init__(self, dum: List =[]):
        self.dum = dum

    @property
    def dum(self) -> List:
        return self.dum

    @dum.setter
    def dum(self, value: List) -> None:
        self.dum = value

When I run the following:

dummy(dum=[1,2,3])

The kernel dies without telling me much about the possible error. What is going on?

Asked By: marcos

||

Answers:

@property
def dum(self) -> List:
    return self.dum

This creates an infinite recursion.

  • The attribute itself should have a different name. As per convention, it is usually the name of the property prefixed with an underscore.

  • While we are at it, default mutable arguments should be avoided.

  • mypy does not like implicit Optional annotations, so List = None should be Optional[List] = None.

from typing import List, Optional

class dummy:
    def __init__(self, dum: Optional[List] = None):
        self.dum = dum if dum is not None else []

    @property
    def dum(self) -> List:
        return self._dum

    @dum.setter
    def dum(self, value: List) -> None:
        self._dum = value
Answered By: DeepSpace
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.