Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic function typing in Python

I am running under Python 3.7 on Linux Ubuntu 18.04 under Eclipse 4.8 and Pydev.

The declaration:

args:Dict[str: Optional[Any]] = {}

is in a module that is imported from my testing code. and it is flagged with the following error message from typing.py:

TypeError: Parameters to generic types must be types. Got slice(<class 'str'>, typing.Union[typing.Any, NoneType], None). The stack trace follows: Finding files... done. Importing test modules ... Traceback (most recent call last):   File "/Data/WiseOldBird/Eclipse/pool/plugins/org.python.pydev.core_7.0.3.201811082356/pysrc/_pydev_runfiles/pydev_runfiles.py", line 468, in __get_module_from_str
    mod = __import__(modname)   File "/Data/WiseOldBird/Workspaces/WikimediaAccess/WikimediaLoader/Tests/wiseoldbird/loaders/TestWikimediaLoader.py", line 10, in <module>
    from wiseoldbird.application_controller import main   File "/Data/WiseOldBird/Workspaces/WikimediaAccess/WikimediaLoader/src/wiseoldbird/application_controller.py", line 36, in <module>
    args:Dict[str: Optional[Any]] = {}   File "/usr/local/lib/python3.7/typing.py", line 251, in inner
    return func(*args, **kwds)   File "/usr/local/lib/python3.7/typing.py", line 626, in __getitem__
    params = tuple(_type_check(p, msg) for p in params)   File "/usr/local/lib/python3.7/typing.py", line 626, in <genexpr>
    params = tuple(_type_check(p, msg) for p in params)   File "/usr/local/lib/python3.7/typing.py", line 139, in _type_check
    raise TypeError(f"{msg} Got {arg!r:.100}.") TypeError: Parameters 

This prevents my testing module from being imported. What am I doing wrong?

like image 596
Jonathan Avatar asked Dec 15 '18 17:12

Jonathan


People also ask

What is generic in typing Python?

Generics are not just used for function and method parameters. They can also be used to define classes that can contain, or work with, multiple types. These “generic types” allow us to state what type, or types, we want to work with for each instance when we instantiate the class.

What is type () in Python?

The type() function is used to get the type of an object. Python type() function syntax is: type(object) type(name, bases, dict)

Is generic data type supported in Python?

In Python 3.6 indexing generic types or type aliases results in actual type objects. This means that generic types in type annotations can have a significant runtime cost. This was changed in Python 3.7, and indexing generic types became a cheap operation.


1 Answers

The proper syntax for a dict's type is

Dict[str, Optional[Any]]

When you write [a: b], Python interprets this as a slice, i.e. the thing that makes taking parts of arrays work, like a[1:10]. You can see this in the error message: Got slice(<class 'str'>, typing.Union[typing.Any, NoneType], None).

like image 168
Norrius Avatar answered Sep 24 '22 06:09

Norrius