Jonathan
Jonathan

Reputation: 2845

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?

Upvotes: 9

Views: 11064

Answers (1)

Norrius
Norrius

Reputation: 7920

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).

Upvotes: 25

Related Questions