by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Ivan Levkivskyi
    @ilevkivskyi
    Please move to typing, this channel is closed.
    Azeem Haider
    @axeemhaider_twitter
    Hi, I created repo for Firestore called FireO Please check it and give some feedback
    Azeem Haider
    @axeemhaider_twitter
    Hi, I create Repo for Firestore. It's an ORM model for Firestore.
    Please check it and give some feedback FireO
    Jacek Wielemborek
    @d33tah
    Hi! I have an issue and I'm not sure if it's the target library or mypy - could someone take a quick look? alliefitter/boto3_type_annotations#13
    Ethan Smith
    @ethanhs
    Hi! Btw the room has changed to https://gitter.im/python/typing. I responded to the issue
    Jacek Wielemborek
    @d33tah
    thanks @ethanhs!
    Thomas Grainger
    @graingert
    is there a way to get mypy to check untyped defs with associated .pyi files?
    Ethan Smith
    @ethanhs
    @graingert the chat moved to https://gitter.im/python/typing !
    Thomas Grainger
    @graingert
    oh dang
    I know that too
    Ethan Smith
    @ethanhs
    happens :P
    Ozan Catal
    @catalozan_gitlab

    Hi, don't know if this is the right place to ask

    but is there a way to let mypy only check if function signatures are correct and just leave the function body be
    we are currently using mypy as a way to check if api contracts are not broken, but we don't really care about what happens inside a function body as long as the correct input and output types are respected

    An example of what causes mypy to fail while we would want it to not fail:

    def __init__(self, foo: Foo):
            self._foo = foo
            self._recording = False
            self._period = 0.1
            self._chunk_size = 100
            self._file = None
            self._datasets = {}
            self._timestamps = {}

    mypy will trip about the final two lines, whilst in our case it is perfectly sensible to just initialize empty generic dictionaries

    Marti Raudsepp
    @intgr

    I was wondering if it's possible to declare a decorator like @cached_property as Protocol. This somewhat does what I need, instance attributes infer the correct type:

    class _CachedProperty(Protocol):
        def __call__(self, func: Callable[..., _T], name: Optional[str] = ...) -> _T: ...
    cached_property: _CachedProperty

    However, it's missing the class-member attributes like name and func.

    Marti Raudsepp
    @intgr
    Oh this is pretty good already :)
    class _cached_property(Generic[_T]):
        func: Callable[..., _T] = ...
        __doc__: Any = ...
        name: str = ...
        def __get__(self, instance: Any, cls: Type[Any] = ...) -> _T: ...
    
    class _CachedProperty(Protocol):
        def __call__(self, func: Callable[..., _T], name: Optional[str] = ...) -> _cached_property[_T]: ...
    
    cached_property: _CachedProperty
    class Foo:
        @cached_property
        def attr(self) -> List[str]: ...
        reveal_type(attr)      # ✅ Revealed type is 'utils.functional._cached_property[builtins.list*[builtins.str]]'
        reveal_type(attr.name) # ✅ Revealed type is 'builtins.str'
    reveal_type(Foo.attr)      # ❌ Revealed type is 'builtins.list*[builtins.str]'
    reveal_type(Foo.attr.name) # ❌ error: "List[str]" has no attribute "name"
    f = Foo()
    reveal_type(f.attr)        # ✅ Revealed type is 'builtins.list*[builtins.str]'
    Marti Raudsepp
    @intgr
    Amazing, using @overload with __get__ works perfectly. I'm impressed Mypy is able to do this:
    class _cached_property(Generic[_T]):
        func: Callable[..., _T] = ...
        __doc__: Any = ...
        name: str = ...
        @overload
        def __get__(self, instance: None, cls: Type[Any] = ...) -> _cached_property[_T]: ...
        @overload
        def __get__(self, instance: object, cls: Type[Any] = ...) -> _T: ...
    class _CachedPropertyProtocol(Protocol):
        def __call__(self, func: Callable[..., _T], name: Optional[str] = ...) -> _cached_property[_T]: ...
    cached_property: _CachedPropertyProtocol
    Marti Raudsepp
    @intgr
    In fact, I could drop the Protocol class entirely, nice!
    Marti Raudsepp
    @intgr

    I don't understand why in some contexts Mypy seems to be ignoring my stub files (in other cases it seems to respect them). For example:

    % mypy drf_yasg/app_settings.py
    drf_yasg/app_settings.py:4: error: Need type annotation for 'SWAGGER_DEFAULTS'
    Found 1 error in 1 file (checked 1 source file)
    
    % head -n4 drf_yasg-stubs/app_settings.pyi
    from typing import Any, Optional, Dict, List
    
    SWAGGER_DEFAULTS: Dict[str, Any]    # Could use TypedDict here
    REDOC_DEFAULTS: Dict[str, Any]

    How do I debug stub file loading?

    Ethan Smith
    @ethanhs
    @intgr the chat has moved to https://gitter.im/python/typing
    Marti Raudsepp
    @intgr
    Ahh thanks
    Perry Goy
    @perrygoy
    Hello! I'm hoping someone can help me as i'm getting my library typed up. I'm running into an issue where i have a base class which only provides the required methods for the subclasses (and raises a NotImplementedError if those subclasses haven't defined them). Mypy is complaining that calling those required methods first has too few arguments, then also says that the first argument is the incorrect type. I'll type up an example quickly.
    oh i see other room, thanks autobot
    Mehdi GMIRA
    @mehdigmira

    Hello I have the following case:

    class A:
      def __init__(self, x: int = None) -> None:
          self.x = x
    
    reveal_type(A().x)
    reveal_type(A(x=1).x)

    How can I type this so that mypy infers A().x to be None and A(x=1).x to be int ?

    I've tried some approaches with generics and overloads but I can't manage to have something working
    Mykhailo Havelia
    @Arfey

    Hello, i don't find approach to use attributes from generic in other type.

    what do i want:

    class FlagsDefault:
        ENEBLE_SOME = True
        ENEBLE_SOME_ELSE = False
    
    
    class Flags:
        def __init__(self, flags):
            self._flags = flags
    
        def __getattr__(self, name: str):
            return getattr(self._flags, name)
    
        def my_inner_method(self):
            # do some
            pass
    
    class Client:
        def __init__(self, flags):
            self._flags = flags
    
        def flags(self):
            return Flags(self._flags)
    
    
    client = Client(FlagsDefault)
    
    client.flags().ENEBLE_SOME  # True
    client.flags().my_inner_method() # do some
    client.flags().BAD_FLAG # err: Flags has no attribute BAD_FLAG

    in typescript i can to do some like that:

    type FlagsType<T extends {}> = {
      [P in keyof T]: T[P];
    } & {myInnerMethod(): void};
    
    
    const FlagsDefault = {
        ENEBLE_SOME: true,
        ENEBLE_SOME_ELSE: false,
    };
    
    
    class FlagsClient<T extends {}> {
        _flags: T;
    
        constructor(flags: T) {
            this._flags = flags
        }
    
        flags(): FlagsType<T> {
            return {
                ...this._flags,
                myInnerMethod: () => {
                    // do some
                }
            }
        }
    }
    
    
    const client = new FlagsClient(FlagsDefault);
    
    client.flags().ENEBLE_SOME
    client.flags().myInnerMethod()

    but i don’t fined any approach to do some like that

    type FlagsType<T extends {}> = {
      [P in keyof T]: T[P];
    } & {myInnerMethod(): void};

    in mypy.

    please help me :)

    Marti Raudsepp
    @intgr
    It seems like you want "intersection types", which are not yet supported by mypy. See python/typing#213
    @Arfey ^
    Mykhailo Havelia
    @Arfey
    @intgr thx for the response. Can i solve my problem in another way?
    Marti Raudsepp
    @intgr
    Creating an intermediary class with multiple parents is the only way AFAIK. But I don't know if it's applicable to your situation.
    Mykhailo Havelia
    @Arfey
    thx
    will wait :)
    Marti Raudsepp
    @intgr
    Did you look at the examples in the issue I linked?
    Mykhailo Havelia
    @Arfey
    yes
    but if i understand correct it's only as idea
    Alex Jurkiewicz
    @alexjurkiewicz
    hello. it seems like with open(args.application_zip, "rb") as application_zip: gets typed as IO. How can I get it typed as BinaryIO?
    oh, it's being typed correctly, I was confused by an error coming from another incorrect type
    but I'm curious how you type a variable set in a with statement
    Bertrand Caron
    @bertrand-caron

    Hello well-typed people! I was wondering if anyone had reported issues with filters in list comprehensions. Specifically, this example looks like a false positive to me (the non-optionality is enforced by the filter). I am sure the walrus operator is not helping with the parsing:

    {match.group(1) for line in "Hello\nWorld".splitlines() if (match := re.match("ARG (.*)", line)) is not None}

    I am sure it's non-trivial to fix, just wondering if it would be worth be making an issue on Github?

    Ethan Smith
    @ethanhs
    @bertrand-caron please do make an issue! Also the chat has moved to https://github.com/python/typing
    Anthony
    @tribals

    Hi folks!

    Is there a way to deal with complete overridden method in subclass? I mean, the subclass overrides a method, and completely change it's signature.

    Here is example from real project, beautifulsoup4. I just generated stubs for it. mypy complains that subclass changed method signature. Superclass method:

    File: bs4/element.py
    981: class Tag(PageElement):
    <...>
    1451:     def decode(self, indent_level=None,
    1452:                eventual_encoding=DEFAULT_OUTPUT_ENCODING,
    1453:                formatter="minimal"):

    Subclass:

    File: bs4/__init__.py
    51: class BeautifulSoup(Tag):
    <...>
    658:     def decode(self, pretty_print=False,
    659:                eventual_encoding=DEFAULT_OUTPUT_ENCODING,
    660:                formatter="minimal"):
    661:         """Returns a string or Unicode representation of the parse tree
    662:             as an HTML or XML document.
    663: 
    664:         :param pretty_print: If this is True, indentation will be used to
    665:             make the document more readable.
    666:         :param eventual_encoding: The encoding of the final document.
    667:             If this is None, the document will be a Unicode string.
    668:         """
    669:         if self.is_xml:
    670:             # Print the XML declaration
    671:             encoding_part = ''
    672:             if eventual_encoding != None:
    673:                 encoding_part = ' encoding="%s"' % eventual_encoding
    674:             prefix = '<?xml version="1.0"%s?>\n' % encoding_part
    675:         else:
    676:             prefix = ''
    677:         if not pretty_print:
    678:             indent_level = None
    679:         else:
    680:             indent_level = 0
    681:         return prefix + super(BeautifulSoup, self).decode(
    682:             indent_level, eventual_encoding, formatter)

    As you can see, the subclass's method completely overrides a superclass's one But in the end it properly calls super() with right parameters. How to teach mypy to properly type-check such a case?

    Personally I'm not fan this kind of overrides. But, I can't just patch installed library code.
    Anthony
    @tribals

    Another question:

    There is a method which yields a tuple of arbitrary length with two alternating types: Tuple[Node, List[Node], Node, List[Node], ...]. Unfortunately, at this moment such a type can't be expressed. Any ideas?

    Thomas Grainger
    @graingert
    how can I type a generator that works like a coroutine? https://mypy-play.net/?mypy=latest&python=3.8&gist=859ae9484af82c6690806b9e5f0d35bd
    Thomas Grainger
    @graingert
    god damn it's moved - I fell for it again
    Omry Yadan
    @omry
    can anyone help with something? I got this: https://mypy-play.net/?mypy=latest&python=3.8&gist=fa9bec1407a0eadb3f1a8b84d778a0cf
    basically, I have an existing decorator, and I would like to add a passthrough to the underlying function. the code works but I can't quiet figure out how to make mypy happy (I want it strictly happy :) )
    Alexander Ivanov
    @alehander92
    is the right channel!
    Omry Yadan
    @omry
    @alehander92 , oh - didn't realize I was in the wrong one. thanks.