#๐Ÿ”’ Clearer and more readable type hinting

9 messages ยท Page 1 of 1 (latest)

sleek sluice
#

I have the following code for a function definition that I wrote, there's nothing wrong with it functionality wise however I'm starting to see the potential flaws in readability, especially with the return values. I was wondering if there was anything that anyone can suggest would be a better way of type hinting a function like this?

Here's the code:

    def get_artist_discography(
        self, artist_name: str
    ) -> list[dict[str : Union[str, List[dict[str:str]]]]]:
azure pierBOT
#

@sleek sluice

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.

fathom path
#

it should be dict[str, str], not dict[str:str]

you probably should use custom classes instead of dictionaries for holding the data, you can use dataclasses or something like pydantic to make defining them less of a hassle

sleek sluice
#

Oh thanks for the tip

#

After a bit more googling, I found out about TypedDicts and it seems to work as a good solution

#

I broke it into two separate files as a personal choice but I'm leaving what I did just in case anyone is curious

utils.types file:

from typing import TypedDict, List


class Song(TypedDict):
    title: str
    link: str


class Album(TypedDict):
    title: str
    songs: List[Song]

other file:

from utils.types import Album, List # moved it into another file

def get_artist_discography(self, artist_name: str) -> List[Album]:
sleek sluice
#

!close

azure pierBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, 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.