Patchwork [7,of,7] typing: add pseudo localstr.__init__() to help pytype

login
register
mail settings
Submitter Yuya Nishihara
Date Nov. 16, 2019, 11:59 a.m.
Message ID <221dd5f33efa47895ee0.1573905583@mimosa>
Download mbox | patch
Permalink /patch/43299/
State Accepted
Headers show

Comments

Yuya Nishihara - Nov. 16, 2019, 11:59 a.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1573889128 -32400
#      Sat Nov 16 16:25:28 2019 +0900
# Node ID 221dd5f33efa47895ee0f2afc2681b0ffbfe3ae5
# Parent  e958a138ca580a7ab1565df30e3737dbf04a5a34
typing: add pseudo localstr.__init__() to help pytype

Apparently, pytype failed to parse localstr.__new__()? This fixes the
following errors:

  line 126, in __hash__: No attribute '_utf8' on localstr [attribute-error]
  line 188, in tolocal: Function localstr.__init__ was called with the wrong
  arguments [wrong-arg-types]
  Expected: (self, string: str, ...)
  Actually passed: (self, string: bytes, ...)

Patch

diff --git a/mercurial/encoding.py b/mercurial/encoding.py
--- a/mercurial/encoding.py
+++ b/mercurial/encoding.py
@@ -20,11 +20,14 @@  from . import (
 
 from .pure import charencode as charencodepure
 
+_TYPE_CHECKING = False
+
 if not globals():  # hide this from non-pytype users
     from typing import (
         Any,
         Callable,
         List,
+        TYPE_CHECKING as _TYPE_CHECKING,
         Text,
         Type,
         TypeVar,
@@ -117,11 +120,17 @@  class localstr(bytes):
     round-tripped to the local encoding and back'''
 
     def __new__(cls, u, l):
-        # type: (Type[_Tlocalstr], bytes, bytes) -> _Tlocalstr
         s = bytes.__new__(cls, l)
         s._utf8 = u
         return s
 
+    if _TYPE_CHECKING:
+        # pseudo implementation to help pytype see localstr() constructor
+        def __init__(self, u, l):
+            # type: (bytes, bytes) -> None
+            super(localstr, self).__init__(l)
+            self._utf8 = u
+
     def __hash__(self):
         return hash(self._utf8)  # avoid collisions in local string space