Skip to content

Typing for props callbacks #361

@Andrej730

Description

@Andrej730

Currently there is a problem passing callback-arguments to bpy.props functions - there seems to be no way to do it right without producing errors.

Callable arguments are defined as collections.abc.Callable[[bpy.types.bpy_struct, bpy.types.Context], None].

Callable arguments are acting contravariantly (https://peps.python.org/pep-0483/#covariance-and-contravariance).
Therefore, the first argument allowed to be either bpy.types.bpy_struct or any of it's supertypes.
So bpy.types.PropertyGroup or any of it's subtypes is not allowed and passing a callable with bpy.types.PropertyGroup argument (or MyCustomProperties) inevitably leads to typing errors.

Any ideas how we can work around this to allow correct callbacks to be passed?

import bpy


def my_update_callback(self: "MyCustomProperties", context: bpy.types.Context) -> None:
    print(self.my_float)


# Argument of type "(self: MyCustomProperties, context: Context) -> None" cannot be assigned to parameter "update" of type "((bpy_struct[Unknown], Context) -> None) | None" in function "FloatProperty"
#   Type "(self: MyCustomProperties, context: Context) -> None" is not assignable to type "((bpy_struct[Unknown], Context) -> None) | None"
#     Type "(self: MyCustomProperties, context: Context) -> None" is not assignable to type "(bpy_struct[Unknown], Context) -> None"
#       Parameter 1: type "bpy_struct[Unknown]" is incompatible with type "MyCustomProperties"
#         "bpy_struct[Unknown]" is not assignable to "MyCustomProperties"
#     "function" is not assignable to "None"
# PylancereportArgumentType


class MyCustomProperties(bpy.types.PropertyGroup):
    my_float: bpy.props.FloatProperty(
        name="My Float",
        description="A float property with update callback",
        default=1.0,
        update=my_update_callback,
    )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions