Closed BerendKemper closed 2 weeks ago
You are not allowed to use variables within a type expression. Since _Filters
is a variable, it cannot be used in the type expression used to define FilterList
in your example.
You can use quoted type expressions (forward references) within the functional form of a TypedDict definition and for NewType
definitions.
FilterList = NewType("FilterList", list[Union[FilterEntry, "Filters"]])
With this change to your code, pylance provides the completion suggestions you're looking for.
For more details about allowed type expressions, refer to this section of the Python typing spec.
Wauw i thaught i had tried that before already. Guess the previous time i still had something wired up wrong. This time it worked like you said it does. Thanks
Here is a situation where i am trying to provide type hinting for Mongo DB query parameters (as an example). A lot of Mongo DB query properties are prefixed by
$
. Python class syntax does not allow properties that are prefixed by$
and additionallyand
andor
are special reserved language keys. For those reasons i am bound to implement a TypedDict in the form of a TypedDict constructor instead of class extension. However, below i did provided two approuches to define a TypedDict that takes a few Mongo DB query properties.The approuch where class extension is used
class Filters(TypedDict)
provides type hinting even when circular referenced TypedDicts are implemented. But this approuch is incorrect because the properties are defined as_and
,_or
and must be$and
,$or
and that is not possible.The other approuch where TypedDict constructor function is used
Filters = TypedDict('Filters', {'$and': FilterList, '$or': FilterList})
is not providing type hinting when arriving at the first circular referenced Filters TypedDict.Is there a feature that can apply type hinting where circular referenced TypedDicts are used?
If not is it possible to provide a feature that can deal with the above code?