How to use constructor of Generic type

TheHeadlessSourceMan

How do I use the constructor of a python Generic typed class?

T = typing.TypeVar('T')

class MyClass(typing.Generic[T]):
    def __init__(self, initialValue: typing.Iterable):
        self.values: T = T(initialValue)

test = MyClass[tuple[int]]([1, 2, 3])

In this case I am expecting T(initialValue) to be equivalent to tuple(initialValue) but instead I get an error. "Exception has occurred: TypeError 'TypeVar' object is not callable"

I guess that's not too surprising since that's not what typing was built for, but is there a workaround to accomplish this?

Silvio Mayolo

You'll need to take an explicit factory method. Type annotations only exist for compile-time purposes, and at runtime that T is just a TypeVar. Consider

class MyClass(Generic[T]):
    def __init__(self, initialValue: Iterable[int], factory: Callable[[Iterable[int]], T]):
        self.values: T = factory(initialValue)

Then call it as

test = MyClass([1, 2, 3], lambda x: tuple(x))

Note: It would be nice to just pass tuple as the second argument, but mypy seems to choke when converting that typename to a Callable. Other type checkers may be able to handle it; your mileage may vary.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Use generic type in class constructor

How to know a generic type T if it has an appropriate constructor for use?

Is it possible to use constructor injection with a generic type?

Pass Type as a Constructor and use it as a generic for provider package

How to use a generic type?

How to work with generic type array and generic type class as parameter in constructor?

How to pass a generic type object to a class constructor

How to use reflection in order to execute a generic constructor

Generic constructor for generic type in Rust

How to build a class and constructor generic to use generic methods?

Calling constructor of generic type?

Calling constructor of a generic type

Generic type as a constructor parameter

How to use a type alias to define a type constructor

How to use a helper generic of type class of type

Explicit type annotation for generic constructor of a generic type

How to add a primary constructor to a generic class with type constraints?

how to extend 2 classes with generic type and different constructor?

How to register/resolve a type with one generic constructor parameter

How to pass a type parameter to a generic class constructor reference?

How to define a parameter of type generic list with constructor constraint?

how to pass generic list of unknown type to class constructor

How to use type constructor in infix form

How to use generic type for interface - TypeScript?

How to use generic protocol as a variable type

How to use generic type parameter in a method of an interface

flutter: how to use type or generic to Map?

How to use generic type in a value tuple?

How to provide a proper type for use of generic impl?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive