Skip to content

Define __slots__ for object as Iterable[str] / Iterable[Union[str, unicode]] - #780

Merged
ambv merged 2 commits into
python:masterfrom
TrueBrain:slots
Dec 19, 2016
Merged

ambv merged 2 commits into
python:masterfrom
TrueBrain:slots

Conversation

@TrueBrain

Copy link
Copy Markdown
Contributor

No description provided.

Comment thread stdlib/2/__builtin__.pyi Outdated
class object:
__doc__ = ... # type: Optional[str]
__class__ = ... # type: type
__slots__ = ... # type: Optional[Iterable[Union[str, unicode]]]

@ambv ambv Dec 19, 2016 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested with different types of iterables, including generators, this works. However, there is one surprise in the API of __slots__. Consider:

>>> class C(object):
...   __slots__ = 'one'
...
>>> c = C()
>>> c.one = 'valid'
>>> c.o = 'invalid'
Traceback (most recent call last):
...
AttributeError: 'C' object has no attribute 'o'

Your type hint supports this use case implicitly because a string is also an iterable of strings. However, this suggests to the reader that providing 'one' should be equivalent to providing ('o', 'n', 'e') and it's not. I think it would be clearer to list the "str" and "unicode" types explicitly for that very reason.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not expect that it would work the way it does :D Python 3 works in same manner, so I changed them both into Unions. Tnx!

Comment thread stdlib/2/__builtin__.pyi
class object:
__doc__ = ... # type: Optional[str]
__class__ = ... # type: type
__slots__ = ... # type: Optional[Union[str, unicode, Iterable[Union[str, unicode]]]]

@ambv ambv Dec 19, 2016 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: since you're already doing a Union, it would be better to say:
Union[None, str, unicode, Iterable[str], Iterable[unicode]]

Much shorter :) Well, at least much flatter :)

@ambv
ambv merged commit 7e89fc0 into python:master Dec 19, 2016
@ambv

ambv commented Dec 19, 2016

Copy link
Copy Markdown
Contributor

Thanks! 🍰

@gvanrossum

Copy link
Copy Markdown
Member

Hm, apparently this went too far -- while __slots__ can legitimately be a single string (sadly, I should add) it cannot be None. See #1853.

hswong3i pushed a commit to alvistack/python-typeshed that referenced this pull request May 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants