How to create a factory function that preserves generic type information in Python?

I have the following function that returns a class with a generic type parameter:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>T = TypeVar('T')
def create_property(event_bus: EventBus):
class Property(Generic[T]):
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
event_bus.publish()
return Property
</code>
<code>T = TypeVar('T') def create_property(event_bus: EventBus): class Property(Generic[T]): def __init__(self, validator: Callable[[T], bool]): self._validator = validator def __set_name__(self, obj: Any, name: str): self.name = name def __get__(self, obj: Any, type: Any) -> T: return obj.__dict__.get(self.name) def __set__(self, obj: Any, value: T): if not self._validator(value): raise ValueError("Invalid value") obj.__dict__[self.name] = value event_bus.publish() return Property </code>
T = TypeVar('T')

def create_property(event_bus: EventBus):
    class Property(Generic[T]):
        def __init__(self, validator: Callable[[T], bool]):
            self._validator = validator

        def __set_name__(self, obj: Any, name: str):
            self.name = name

        def __get__(self, obj: Any, type: Any) -> T:
            return obj.__dict__.get(self.name)

        def __set__(self, obj: Any, value: T):
            if not self._validator(value):
                raise ValueError("Invalid value")
            obj.__dict__[self.name] = value
            event_bus.publish()

    return Property

What I’m trying to do here is to create a class that has an EventBus bound to it so that I don’t have to pass it as a constructor parameter.

My problem with the above code is that this will resolve to Property[Any] instead of Property[T] so the generic is lost somewhere along the way. How can I fix this function to preserve the generic?

Your function create_property needs a typed argument to deduce return value type. To make validations, you will probably need T‘s type in Property class. Also, I added event_bus as class variable.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from typing import Any, Callable
class EventBus:
def publish(self):
...
class Property[T]:
event_bus: EventBus
type: type[T]
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
self.event_bus.publish()
def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]:
class P[T](Property[T]):
...
P.event_bus = event_bus
P.type = typ
return P
Prop = create_property(int, event_bus=EventBus())
</code>
<code>from typing import Any, Callable class EventBus: def publish(self): ... class Property[T]: event_bus: EventBus type: type[T] def __init__(self, validator: Callable[[T], bool]): self._validator = validator def __set_name__(self, obj: Any, name: str): self.name = name def __get__(self, obj: Any, type: Any) -> T: return obj.__dict__.get(self.name) def __set__(self, obj: Any, value: T): if not self._validator(value): raise ValueError("Invalid value") obj.__dict__[self.name] = value self.event_bus.publish() def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]: class P[T](Property[T]): ... P.event_bus = event_bus P.type = typ return P Prop = create_property(int, event_bus=EventBus()) </code>
from typing import Any, Callable

class EventBus:
    def publish(self):
        ...

class Property[T]:
    event_bus: EventBus
    type: type[T]

    def __init__(self, validator: Callable[[T], bool]):
        self._validator = validator

    def __set_name__(self, obj: Any, name: str):
        self.name = name

    def __get__(self, obj: Any, type: Any) -> T:
        return obj.__dict__.get(self.name)

    def __set__(self, obj: Any, value: T):
        if not self._validator(value):
            raise ValueError("Invalid value")
        obj.__dict__[self.name] = value
        self.event_bus.publish()

def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]:
    class P[T](Property[T]):
        ...
    P.event_bus = event_bus
    P.type = typ
    return P

Prop = create_property(int, event_bus=EventBus())

New contributor

makukha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to create a factory function that preserves generic type information in Python?

I have the following function that returns a class with a generic type parameter:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>T = TypeVar('T')
def create_property(event_bus: EventBus):
class Property(Generic[T]):
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
event_bus.publish()
return Property
</code>
<code>T = TypeVar('T') def create_property(event_bus: EventBus): class Property(Generic[T]): def __init__(self, validator: Callable[[T], bool]): self._validator = validator def __set_name__(self, obj: Any, name: str): self.name = name def __get__(self, obj: Any, type: Any) -> T: return obj.__dict__.get(self.name) def __set__(self, obj: Any, value: T): if not self._validator(value): raise ValueError("Invalid value") obj.__dict__[self.name] = value event_bus.publish() return Property </code>
T = TypeVar('T')

def create_property(event_bus: EventBus):
    class Property(Generic[T]):
        def __init__(self, validator: Callable[[T], bool]):
            self._validator = validator

        def __set_name__(self, obj: Any, name: str):
            self.name = name

        def __get__(self, obj: Any, type: Any) -> T:
            return obj.__dict__.get(self.name)

        def __set__(self, obj: Any, value: T):
            if not self._validator(value):
                raise ValueError("Invalid value")
            obj.__dict__[self.name] = value
            event_bus.publish()

    return Property

What I’m trying to do here is to create a class that has an EventBus bound to it so that I don’t have to pass it as a constructor parameter.

My problem with the above code is that this will resolve to Property[Any] instead of Property[T] so the generic is lost somewhere along the way. How can I fix this function to preserve the generic?

Your function create_property needs a typed argument to deduce return value type. To make validations, you will probably need T‘s type in Property class. Also, I added event_bus as class variable.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from typing import Any, Callable
class EventBus:
def publish(self):
...
class Property[T]:
event_bus: EventBus
type: type[T]
def __init__(self, validator: Callable[[T], bool]):
self._validator = validator
def __set_name__(self, obj: Any, name: str):
self.name = name
def __get__(self, obj: Any, type: Any) -> T:
return obj.__dict__.get(self.name)
def __set__(self, obj: Any, value: T):
if not self._validator(value):
raise ValueError("Invalid value")
obj.__dict__[self.name] = value
self.event_bus.publish()
def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]:
class P[T](Property[T]):
...
P.event_bus = event_bus
P.type = typ
return P
Prop = create_property(int, event_bus=EventBus())
</code>
<code>from typing import Any, Callable class EventBus: def publish(self): ... class Property[T]: event_bus: EventBus type: type[T] def __init__(self, validator: Callable[[T], bool]): self._validator = validator def __set_name__(self, obj: Any, name: str): self.name = name def __get__(self, obj: Any, type: Any) -> T: return obj.__dict__.get(self.name) def __set__(self, obj: Any, value: T): if not self._validator(value): raise ValueError("Invalid value") obj.__dict__[self.name] = value self.event_bus.publish() def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]: class P[T](Property[T]): ... P.event_bus = event_bus P.type = typ return P Prop = create_property(int, event_bus=EventBus()) </code>
from typing import Any, Callable

class EventBus:
    def publish(self):
        ...

class Property[T]:
    event_bus: EventBus
    type: type[T]

    def __init__(self, validator: Callable[[T], bool]):
        self._validator = validator

    def __set_name__(self, obj: Any, name: str):
        self.name = name

    def __get__(self, obj: Any, type: Any) -> T:
        return obj.__dict__.get(self.name)

    def __set__(self, obj: Any, value: T):
        if not self._validator(value):
            raise ValueError("Invalid value")
        obj.__dict__[self.name] = value
        self.event_bus.publish()

def create_property[T](typ: type[T], event_bus: EventBus) -> type[Property[T]]:
    class P[T](Property[T]):
        ...
    P.event_bus = event_bus
    P.type = typ
    return P

Prop = create_property(int, event_bus=EventBus())

New contributor

makukha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật