Skip to content

How to use an implicit-optional library in a no_implicit_optional codebase #9208

@PeterJCLaw

Description

@PeterJCLaw

Given a library which uses no_implicit_optional = False (the default) and thus defines functions like:

def foo(bar: str = None): ...

(where bar is implicitly Optional[str])

I'm trying to work out how to call such a function in a project where I want to have set no_implicit_optional = True.

def myfunc(bar: Optional[str] = None):
    # Argument 1 to "foo" has incompatible type "Optional[str]"; expected "str"
    that_library.foo(bar)

My current workaround is to cast the value of bar to the non-optional type before passing it on, however this doesn't feel like a good solution.

I've also tried configuring mypy with a different setting for the library, via the following in my setup.cfg:

[mypy]
no_implicit_optional = True

[mypy-that_library]
no_implicit_optional = False

What is the recommended approach for this?

It's worth noting that the signature reported by reveal_type also changes in response to the local value of this setting.
Is it intentional that such library APIs change their signature based on the local value of no_implicit_optional?


I'm using mypy 0.782 on Python 3.6.

In case it's useful, the actual place I'm hitting this is in using httpx: https://github.com/PeterJCLaw/code-submitter/blob/79d5cc7539d47f7effd27e7d8c630badf75d9e0d/code_submitter/auth.py#L94-L106

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions