Skip to content

Strange case with deepcopy() and Literal[True] #12001

Closed

Description

@jolaf

The following code:

from copy import deepcopy
from typing import Literal, Union

def f(a: str, b: bool) -> Union[Literal[True], str]:
    return b or deepcopy(a)

print(f("abc", False))
print(f("abc", True))

produces the following output:

$ python3 test.py
abc
True

$ mypy test.py
test.py: note: In function "f":
test.py:5:12: error: Incompatible return value type (got "bool", expected "Union[Literal[True], str]")  [return-value]
        return b or deepcopy(a)
               ^
test.py:5:26: error: Argument 1 to "deepcopy" has incompatible type "str"; expected "bool"  [arg-type]
        return b or deepcopy(a)
                             ^
Found 2 errors in 1 file (checked 1 source file)

$ python3 --version
Python 3.8.10

$ mypy --version
mypy 0.931

$ cat /etc/issue
Ubuntu 20.04.3 LTS \n \l

$ uname -a
Linux ubuntu 5.4.0-94-generic #106-Ubuntu SMP Thu Jan 6 23:58:14 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

If deepcopy() call is removed, warnings go away.

In some similar cases only the second warning appears, which looks even weirder.

Activity

  1. changed the title [-]Strange case with deepcopy()[/-] [+]Strange case with deepcopy() and Literal[True][/+] on Jan 17, 2022
  2. brianschubert commented on Dec 8, 2024

    @brianschubert
    Collaborator

    Related / duplicate of #10696, just using or instead of and. Both issues have to do with bidirectional inference going awry when analyzing the right operand using the type of the left operand as the type context.

  3. added 2 commits that reference this issue on Jun 11, 2025
  4. added a commit that references this issue on Jun 13, 2025
    2ba79cb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions