Skip to content

Unexpected behavior of __class__ attribute for annotated python arguments #3954

Closed

Description

@UltimateLobster

Hello, I'm kinda new to Cython so hopefully I didn't miss anything obvious, but I think I've found a weird behavior of annotated function arguments.
Seems like the __class__ attribute acts unexpectedly when the arguments are annotated with pythonic

def func(dict my_dict):
    # The following prints "<class 'dict'>" as expected
    print(my_dict.__class__)

    # I would expect the following to print "{}" since this is the equivalent of dict()
    # Instead, it once again prints "<class 'dict'>
    print(my_dict.__class__())

    # Calling the class twice would create an empty dict and print "{}"
    print(my_dict.__class__()())

Removing the "dict" annotation from "my_dict" would make this function work as expected
(printing "<class 'dict'> followed by "{}" followed by an exception for calling a 'dict' object)

This behavior also occurs with other python types such as strings, lists and sets.
However, when using ints, it behaved has expected.

I'm using Cython 0.29.21 with Python 3.9.1 on Windows.

Activity

  1. scoder commented on Mar 21, 2021

    @scoder
    Contributor

    Agreed that this is a bug, but is there any use case for such code? I can't think of a case where [some builtin object].__class__ isn't just the builtin type itself.

  2. da-woods commented on Mar 21, 2021

    @da-woods
    Collaborator

    Agreed that this is a bug, but is there any use case for such code? I can't think of a case where [some builtin object].__class__ isn't just the builtin type itself.

    This is very artificial, but you can come up with cases where the user hasn't actually typed a variable, but Cython has successfully inferred it:

    def f(x: list):
        y = x*2   # hmmmm - what type is this going to be?
        return y.__class__()
    

    Here Cython works out that y is going to be a list but it isn't necessarily obvious to the user. I haven't really convinced myself that this is a use-case, but you could invent more complicated examples: maybe y was created from a cdef function with a specified return type?

  3. added this to the 3.0 milestone on May 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions