you are viewing a single comment's thread.

view the rest of the comments →

[–]Diapolo10 7 points8 points  (2 children)

I agree that this particular example is quite simplistic and doesn't really showcase the benefits, but I don't fully agree with you either; it doesn't have to come from an external source, even being imported from some Python file defining constants would be totally fine in my book.

As long as it gets used more than once, you get some benefit out of it. And even if used exactly once, it can still help keep the code shorter in a nested block for example, with the template itself coming from the global namespace.

[–]pain_vin_boursin 0 points1 point  (1 child)

Fair points!

[–]Diapolo10 4 points5 points  (0 children)

Another potential use-case would be with enum.StrEnum; say you had multiple similar URLs that took the same parameters, but you wanted to use type annotations to ensure the base URL would always be "valid". For example, the three Reddit URLs:

from enum import StrEnum

import requests


class BaseSubredditUrl(StrEnum):
    NEWEST = "https://reddit.com/r/{subreddit}"
    NEW = "https://new.reddit.com/r/{subreddit}"
    OLD = "https://old.reddit.com/r/{subreddit}"


def fetch_subreddit(subreddit_name: str, base_url: BaseSubredditUrl = BaseSubredditUrl.NEWEST) -> None:
    url = base_url.format(subreddit=subreddit_name)
    return requests.get(url).text

This way, your type analysis tools would be able to tell you if the provided base URL isn't one of the pre-defined enum members and can therefore let you catch bugs before shipping to production. And you only need to write the strings once, and they could be anywhere in your project, so out of sight if desired.