Incompatible types in assignment (expression has type List[nothing], variable has type (...)

2024/10/14 15:30:54

Consider the following self-contained example:

from typing import List, UnionT_BENCODED_LIST = Union[List[bytes], List[List[bytes]]]
ret: T_BENCODED_LIST = []

When I test it with mypy, I get the following error:

example.py:4: error: Incompatible types in assignment (expression has type "List[<nothing>]", variable has type "Union[List[bytes], List[List[bytes]]]")

What is the problem here and how can I properly annotate this example?

Answer

This is related to the following mypy bugs:

  • https://github.com/python/mypy/issues/2164
  • https://github.com/python/mypy/issues/6463

The issue relates to the use of Union with an empty list.

There are two ways to deal with this:

  1. Get mypy to ignore the empty list assignment (not ideal, but probably the simplest approach)
  2. Use a type-hinted function to perform the empty list assignment

Approach 1 - Get mypy to ignore the empty list assignment

from typing import List, Union# Define the variable with type hint
T_BENCODED_LIST: Union[List[bytes], List[List[bytes]]]# Set the value to empty list and tell mypy to look the other way.
T_BENCODED_LIST = []  # type: ignore

This feels like a reasonable approach, because it allows mypy to continue to assume that the type is correctly defined.

Approach 2 - Use a type-hinted function for empty list assignment

Using a type-hinted function avoids the issue with Union and empty lists. This approach means adding code that is only necessary for working around the typing issue, so isn't my preferred approach.

from typing import List, Union# Define the variable with type hint
T_BENCODED_LIST: Union[List[bytes], List[List[bytes]]]# Create a type-hinted function that can be used
# for assignment.
def get_empty_list_bytes() -> List[bytes]:return []# Set the value to empty list using the function.
# Mypy will assume the type based on the functions type hint.
T_BENCODED_LIST = get_empty_list_bytes()
https://en.xdnf.cn/q/69396.html

Related Q&A

How to convert XComArg to string values in Airflow 2.x?

Code: from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults from airflow.providers.google.cloud.hooks.gcs import GCSHookclass GCSUploadOperator(BaseOperator):@appl…

Python dryscrape scrape page with cookies

I wanna get some data from site, which requires loggin in. I log in by requestsurl = "http://example.com" response = requests.get(url, {"email":"[email protected]", "…

Python retry using the tenacity module

Im having having difficulty getting the tenacity library to work as expected. The retry in the following test doesnt trigger at all. I would expect a retry every 5 seconds and for the log file to refle…

How to write own logging methods for own logging levels

Hi I would like to extend my logger (taken by logging.getLogger("rrcheck")) with my own methods like: def warnpfx(...):How to do it best? My original wish is to have a root logger writing …

How to use pandas tz_convert to convert to multiple different time zones

I have some data as shown below with hour in UTC. I want to create a new column named local_hour based on time_zone. How can I do that? It seems like pandas tz_convert does not allow a column or panda…

virtualenv, python and subversion

Im trying to use the python subversion SWIG libraries in a virtualenv --no-site-packages environment. How can I make this work?

Float to Fraction conversion in Python

While doing exercise on the topic of float type to Fraction type conversion in Python 3.52, I found the difference between the two different ways of conversion.The first method is:>>> from fra…

How to update an SVM model with new data

I have two data set with different size.1) Data set 1 is with high dimensions 4500 samples (sketches).2) Data set 2 is with low dimension 1000 samples (real data). I suppose that "both data set ha…

Expanding NumPy array over extra dimension

What is the easiest way to expand a given NumPy array over an extra dimension?For example, suppose I have>>> np.arange(4) array([0, 1, 2, 3]) >>> _.shape (4,) >>> expand(np.…

Django-Haystack giving attribute error?

I am trying to use Haystack and Whoosh with my Django app. I followed the steps on Haystack docs, but i am getting this error when i do a searchAttributeError at /search/ module object has no attribute…