Skip to content

Perhaps declare a __new__ instead of an __init__ for str and other similar types #4514

Closed

Description

@Hibou57

At

class str(Sequence[str], _str_base):
, an __init__ is declared for str

As I understand it, str has no proper __init__, it only has a proper __new__.

I came to this, thinking again about this issue in another repository: python/mypy#9405

Activity

  1. srittau commented on Sep 6, 2020

    @srittau
    Collaborator

    A short test indicates to me that str has both __init__() and __new__(), so we should define both in typeshed. (After checking with the implementation, of course.)

    Edit:

    Python 3.7.3 (default, Jul 25 2020, 13:03:44) 
    [GCC 8.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> str.__new__
    <built-in method __new__ of type object at 0x81ec40>
    >>> str.__init__
    <slot wrapper '__init__' of 'object' objects>
    >>> 
  2. srittau commented on Sep 6, 2020

    @srittau
    Collaborator

    @JelleZijlstra pointed to #1352 and #1464, where this was (unsuccessfully) tried before.

  3. srittau commented on Sep 6, 2020

    @srittau
    Collaborator

    FWIW, I just checked the following example from #1464:

    from enum import Enum
    from typing import TYPE_CHECKING
    
    if not TYPE_CHECKING:
        reveal_type = print
    
    class I(int, Enum):
        a = 1
    reveal_type(I['a'])  # E: Revealed type is '__main__.I'
    
    class S(str, Enum):
        a = '1'
    reveal_type(S['a'])  # E: Revealed type is '__main__.S'
    
    class F(float, Enum):
        a = 1.0
    reveal_type(F['a'])  # E: Revealed type is '__main__.F'

    It still works when I add the following definitions to str:

            @overload
            def __new__(cls: Type[_T], o: object = ...) -> _T: ...
            @overload
            def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ...

    (No guarantee that these are the correct definitions for str, though.) This makes me hopeful that the original underlying problem is solved.

  4. added a commit that references this issue on Sep 17, 2020
    89b34c7
  5. added a commit that references this issue on Sep 30, 2020
    27dfbf6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions