Patchwork D11466: typing: add a fake `__init__()` to bytestr to distract pytype

login
register
mail settings
Submitter phabricator
Date Sept. 21, 2021, 3:38 p.m.
Message ID <differential-rev-PHID-DREV-gluwxo3lxxncaxlfr2ez-req@mercurial-scm.org>
Download mbox | patch
Permalink /patch/49782/
State Superseded
Headers show

Comments

phabricator - Sept. 21, 2021, 3:38 p.m.
mharbison72 created this revision.
Herald added a reviewer: hg-reviewers.
Herald added a subscriber: mercurial-patches.

REVISION SUMMARY
  I'm not sure what changed before pytype 09-09-2021 (from 04-15-2021), but these
  started getting flagged.  This wrapping an exception in a `bytestr` pattern has
  been flagged before, and I've fixed it then with `stringutil.forcebytestr()`.
  But that doesn't work here, because it would create a circular import.
  
  I suspect the issue is `bytes.__new__()` wants `Iterable[int]`, so it just
  assumes the subclass will also take that.  The referenced pytype bug isn't an
  exact match, but seems related and the suggested workaround helps.
  
  The specific warnings fixed are:
  
    File "/mnt/c/Users/Matt/hg/mercurial/encoding.py", line 212, in tolocal: Function bytestr.__init__ was called with the wrong arguments [wrong-arg-types]
             Expected: (self, ints: Iterable[int])
      Actually passed: (self, ints: LookupError)
      Attributes of protocol Iterable[int] are not implemented on LookupError: __iter__
    Called from (traceback):
      line 353, in current file
    File "/mnt/c/Users/Matt/hg/mercurial/encoding.py", line 240, in fromlocal: Function bytestr.__init__ was called with the wrong arguments [wrong-arg-types]
             Expected: (self, ints: Iterable[int])
      Actually passed: (self, ints: UnicodeDecodeError)
      Attributes of protocol Iterable[int] are not implemented on UnicodeDecodeError: __iter__

REPOSITORY
  rHG Mercurial

BRANCH
  default

REVISION DETAIL
  https://phab.mercurial-scm.org/D11466

AFFECTED FILES
  mercurial/pycompat.py

CHANGE DETAILS




To: mharbison72, #hg-reviewers
Cc: mercurial-patches, mercurial-devel

Patch

diff --git a/mercurial/pycompat.py b/mercurial/pycompat.py
--- a/mercurial/pycompat.py
+++ b/mercurial/pycompat.py
@@ -222,6 +222,15 @@ 
         >>> assert type(t) is bytes
         """
 
+        # Trick pytype into not demanding Iterable[int] be passed to __new__(),
+        # since the appropriate bytes format is done internally.
+        #
+        # https://github.com/google/pytype/issues/500
+        if TYPE_CHECKING:
+
+            def __init__(self, s=b''):
+                pass
+
         def __new__(cls, s=b''):
             if isinstance(s, bytestr):
                 return s