Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support parameter type typing.Dict[str, typing.Any] #130

Open
tekumara opened this issue Jun 28, 2020 · 2 comments
Open

Support parameter type typing.Dict[str, typing.Any] #130

tekumara opened this issue Jun 28, 2020 · 2 comments
Labels
feature New feature, enhancement or request investigate

Comments

@tekumara
Copy link

My CLI app can use a profile key, which is used to load the appropriate config:

def load_profile(profile: str) -> Dict[str, Any]:
    ...

@app.command()
def describe(
    config: Dict[str, Any] = typer.Option(None, "--profile", help="Profile in the config file to use", callback=load_profile),
) -> List[Dict[str, Any]]:

However, this errors with:

RuntimeError: Type not yet supported: typing.Dict[str, typing.Any]

The solution you would like

The ability to support Dict as a type, when returned from a callback function.

@tekumara tekumara added the feature New feature, enhancement or request label Jun 28, 2020
@tekumara
Copy link
Author

The workaround, for now, is to remove the type hint from the config param (which also disables type checking).

@pavan-uppari
Copy link

pavan-uppari commented Sep 9, 2024

Handling Dict type.

Issue - If we pass dict directly from terminal, it will be coming as string to us.

Fix: We can use pydantic Json with given dict type and use pydantic TypeAdapter to validate data and get the actual value

Usage

import json
from pydantic import TypeAdapter
from pydantic.types import Json

dict_type = dict[str, int]  #type from method annotations
data = '{"key": 1, "key2": 2}'  #input from terminal - json data

type_adapter = TypeAdapter(Json[dict_type])
t2 = type_adapter.validate_python(data, strict=True)
print(t2) #pass this value to function

Usage with typer

def main(data: dict[str, int]):
    print(f"data is {data}")
$ typer main.py run {"key": 1, "key2": 2}
data is {"key": 1, "key2": 2}

NOTE: User should provide json data as input

@tiangolo If this is ok, we can follow the same for classes as types, let user provide data as dict and pydantic will handle the validation

Inspired from pydantic/pydantic#8446 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature, enhancement or request investigate
Projects
None yet
Development

No branches or pull requests

3 participants