#๐Ÿ”’ How to correctly convert/ provide dict type hint?

8 messages ยท Page 1 of 1 (latest)

waxen frost
#

I tried reading ultralytics python lib's function as below, but the vscode highlights with the error Type "dict[Unknown | Any, Unknown | Any | None] | Any" is not assignable to return type "dict[int, str]". I am sure the content I want to read is a dict[int, str] (The link is https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/datasets/coco.yaml#L18). But I am not sure how to correctly convert that unknown/ any/ none type to int and str types correctly. I appreciate any advice. Thanks.

def load_file() -> dict[int, str]:
    path = check_yaml("coco.yaml")
    return YAML.load(path) # this line is highlighted with Type "dict[Unknown | Any, Unknown | Any | None] | Any" is not assignable to return type "dict[int, str]"
data = load_file()
data.get("names)
pulsar emberBOT
#

@waxen frost

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

#

ultralytics/cfg/datasets/coco.yaml line 18

names:```
waxen frost
#

ok. I just find the answer. use cast(dict[int, str], YAML.load(...))

clever dune
#

If you are sure it returns a dict[int, str] you can use type casting

from typing import cast
...

content = YAML.load(path)
return cast(dict[int, str], content)
pulsar emberBOT
#

Hey @clever dune!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
pulsar emberBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.