So I started writing this pattern:
import typing as t
from pathlib import Path
class Foo:
def __init__(self, p:t.Optional[Path|str] = None) -> None:
self.path = p
@property
def foo(self) -> Path:
return self._path
@foo.setter
def foo(self, p:t.Optional[Path|str]) -> None:
if p is None:
self._path = Path("default", "path")
else:
self._path = Path(p)
f = Foo()
f.path # Path("default", "path")
g = Foo(Path("another"))
g.path # Path("another")
h = Foo("and/another")
h.path # Path("and", "another")
This is type safe, valid Python, that allows for flexibility in assignment (you can use a Path or a string, or pass None to get a default) but precision in output (a Path).
Sadly, there's a six-year-old issue that recognizes that a bug in mypy incorrectly marks the non-Path assignment as a type error: python/mypy#3004
So either I need to stop using this pattern (which I kinda like - we do a lot of element.get("attr"):t.Optional[str] that's nice to assign to a property we want to be a path without doing the conversion manually) or we need to not require MyPy enforcement.
So I started writing this pattern:
This is type safe, valid Python, that allows for flexibility in assignment (you can use a Path or a string, or pass None to get a default) but precision in output (a Path).
Sadly, there's a six-year-old issue that recognizes that a bug in mypy incorrectly marks the non-Path assignment as a type error: python/mypy#3004
So either I need to stop using this pattern (which I kinda like - we do a lot of
element.get("attr"):t.Optional[str]that's nice to assign to a property we want to be a path without doing the conversion manually) or we need to not require MyPy enforcement.