question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is it possible to use typing_inspect to achieve the following?

from typing import Any, List, TypeVar

import typing_inspect


class C:
    x: int

    def __init__(self, x: int) -> None:
        self.x = x


T = TypeVar("T")


class L(List[T]):
    def append_new(self, *args: Any, **kw: Any) -> T:
        item_class = ???(T)
        self.append(item_class(*args, **kw))
        return self[-1]


l = L[C]()
print(l.append_new(42).x)

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:11 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
Peilonrayzcommented, May 9, 2019

This is as the arguments are on the base class. Using get_generic_bases works fine.

from typing import List, TypeVar

import typing_inspect

T = TypeVar("T")


class L(List[T]):
    def f(self) -> None:
        types = typing_inspect.get_args(typing_inspect.get_generic_type(self))
        if not types:
            types = typing_inspect.get_args(typing_inspect.get_generic_bases(self)[0])
        print(types)


class L2(L[int]):
    pass


L().f()
L[int]().f()
L2().f()

It should be noted that this is hacky solution, and may give unexpected results if the class is class C(Mapping[int, T], Sequence[str]). The behavior can be seen in one of typing_inspect_lib.get_mro_orig tests. This function isn’t available until #31 has been completed.

Using this should be fairly simple when it does come out: (Note: untested and subject to change)

for type_info in get_mro_orig(L2()):
    if type_info.typing is L:
        print(get_args(type_info.orig))

It should be noted that this won’t return (int, T, str) if used on C, in an equivalent way. It however is rather simple to change it to return this, return a combination of Mapping and Sequence.

2reactions
Peilonrayzcommented, May 2, 2019

It doesn’t look like this is at all possible to do in the constructor, in Python 3.7.2 at least.

This is as typing_inspect.get_generic_type(self) returns <class '__main__.L'> not __main__.L[int, str].

Otherwise it looks rather simple:

from typing import List, Tuple, TypeVar

import typing_inspect

U = TypeVar("U")
V = TypeVar("V")
W = TypeVar("W")
Z = 1


def get_type_argument(instance, type_var):
    generic = typing_inspect.get_generic_type(instance)
    origin = typing_inspect.get_origin(generic)
    params = typing_inspect.get_parameters(origin)
    index = params.index(type_var)
    return typing_inspect.get_args(generic)[index]


class L(List[Tuple[U, V]]):
    pass


l = L[int, str]()
print(get_type_argument(l, U))
print(get_type_argument(l, V))
try:
    print(get_type_argument(l, W))
except ValueError as e:
    print(e)
try:
    print(get_type_argument(l, Z))
except ValueError as e:
    print(e)
Read more comments on GitHub >

github_iconTop Results From Across the Web

getArgs - Hoogle - Haskell.org
Computation getArgs returns a list of the program's command line arguments (not including the program name), as ByteStrings. Unlike getArgs, this function ...
Read more >
How does getArgs work? - haskell - Stack Overflow
getArgs gives you the arguments you supplied at the command line when you ran the program. If you don't supply any arguments at...
Read more >
Haskell : getArgs - ZVON.org
Computation getArgs returns a list of the program's command line arguments (not including the program name). Related: getProgName. Example 1. Program: import ...
Read more >
getArgs() - IBM
The getArgs() method returns a table that contains one row for each argument that will be accepted by the UDX. In the database,...
Read more >
getargs - Rust - Docs.rs
getargs is a low-level, efficient and versatile argument parser that works similarly to getopts . It works by producing a stream of options,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found