Skip to content

Implement _from_iterable on builtins.set andbuiltins.frozenset #144557

@randolf-scholz

Description

@randolf-scholz

Proposal:

collections.abc.{Set, MutableSet} implement a _from_iterable method, documented here: https://docs.python.org/3/library/collections.abc.html

However, builtins.frozenset and builtins.set, which are marked as inherting from Set and MutableSet, do not implement this constructor, therefore typeshed is kind of blocked from adding these methods in the stubs, as it would lead to unsafe code:

def f(x: MutableSet) -> MutableSet:
    # passes type checking if _from_iterable is added to MutableSet
    return type(x)._from_iterable(x)  

f( {1,2,3} )   # Error at runtime

Alternatives

typeshed could just decide to never add the _from_iterable method, people can still override it regardless to get the desired runtime behavior on types that use the Set and MutableSet mixins that rely on this method.

Has this already been discussed elsewhere?

python/typeshed#15298

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)pendingThe issue will be closed if no feedback is providedtopic-typingtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions