How to Define Type Aliases Using `list` in Python 3.8

Asked 2 years ago, Updated 2 years ago, 30 views

  • Python 3.8.6

Writing code running Python 3.8 and above.

I used typing.List until now when I gave the type hint.
However, Python 3.9 deprecated typing.List, so I ran from__future_import announcements to make the list available.

I would like to define a type alias using the list as shown in the following site.
https://docs.python.org/ja/3/library/typing.html#type-aliases

 from__future__import announcements

Vector=list [float]

def scale (scale:float, vector:Vector) - > Vector:
    return [scalar*num for numinvector]

# typechecks; a list of flows qualifications as a Vector.
new_vector=scale (2.0, [1.0, -4.2, 5.4])

However, the following error occurred:

$python foo.py
Traceback (most recent call last):
  File "foo.py", line 5, in <module>
    Vector=list [float]
TypeError: 'type' object is not subscriptable

How do I define a type alias using the list in Python 3.8?

It works by using typing.List as shown below, but it's deprecated in Python 3.9, so I don't want to write it like this if possible.

from typing import list
Vector=List [float]

python python3

2022-09-29 22:23

1 Answers

If you want to use it as a type hint, you can specify it as follows, but

>>from__future__import announcements
>>>vct:list [float]

If you use it as a substitute (Vector=list[float]), it looks like Python 3.9 or later, so
If you really want to use it, do you want to do it like this?

 if sys.version_info [0:2]==(3,8):
    from typing import list as list

Vector=list [float]
# something else

if sys.version_info [0:2] == (3,8):
    del list# From now on, the normal list


2022-09-29 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.