Instance(..., allow_none=False) is not typing-friendly #1673
Labels
component: core
Issues related to the core library
component: typing stubs
Issues related to the mypy typing stub files
type: enhancement
Given an
Instance
trait declaration that usesallow_none=False
, for example as in:it would be useful for typing tools to be able to deduce that if
a
is an instance ofA
thena.foo
is an instance ofSomeClass
, and in particular is notNone
.There are currently two problems with this:
Instance(...)
can't beNone
whenallow_none=False
allow_none=False
means thata.foo
can't beNone
: if no explicit default is given, and there's no_foo_default
method, then the default fora.foo
isNone
despite theallow_none=False
.The two problems are largely orthogonal, so perhaps this should be two issues.
For the first issue, one possible fix we might consider would be to introduce a trait type factory class
StrictInstance
, something like (with code stolen from @corranwebster):Then the type hints for
StrictInstance
can communicate thatStrictInstance(SomeClass)
always stores a non-None value.For the second issue, in almost all cases in practice the intended meaning of
allow_none=False
ought to be "the value of this trait is neverNone
"; we could consider changing the behaviour so that accessing the trait value before setting it raised an exception instead of producingNone
. This would likely break existing code, so would need to be done carefully, and likely only in a major release.The text was updated successfully, but these errors were encountered: