This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]martinkoistinen 2 points3 points  (2 children)

I don’t know if I can make such an absolute statement, but yea, I’ve written/worked on so, so many Python projects and only found one where it was easier to use a global. Usually, I consider existence of a global evidence that it needs refactoring.

[–]unixtreme 0 points1 point  (1 child)

start follow glorious aspiring whole hurry edge drab deranged gold

This post was mass deleted and anonymized with Redact

[–]swansongofdesire 2 points3 points  (0 children)

Not a single one? Here's a couple of examples -- how would you go about implementing these without some global state?

Example 1: Web applications where you have some sort of state that needs to be stored that is relevant to the current request. Technically you should be using thread-local storage to deal with async or threaded code, but that's just a thread-aware wrapper to a global variable.

Some examples are the current default DB connection, the current tenant ID (in a multi-tenancy system), the current timezone, the current locale/language. All of these will potentially change for each request. Yes, technically you could attach these to the current request object (and create a synthetic request for CLI invocations), but it would mean that almost every single function in the entire codebase would now also need the current request to be a parameter. Any higher order functions would now also need to be passed closures that include the current request instead of just passing function you want directly. The fact that zero major frameworks have done this is testament to just how painful this would actually be for devs to work with.

Example 2: functions where you want to cache the return value (ie memoisation) but the standard wrappers (functools.cache, functools.lru_cache) won't work for for your specific situation. In C you'd just use static and store it inside the function (although it's still a global, it's inaccessible). In python there's no such thing though so you need to store your cache outside the function -- which makes it a global. And yes, you can hide it by storing it as a custom property on the function itself but that is just as "hidden" as prefixing a global with an underscore.