Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Globals are not commonly used except in retrofit cases of legacy code or in beginner code.

I haven’t seen or used a global more than once in my 20 years of writing Python.





Flask's request context is a global object. And since this is specifically about web services, flask seems highly relevant to the conversation.

That's correct. Flask has a global request context object, so by design it can only safely handle a single request at a time per Python interpreter. If you want to parallelize multiple Flask servers, you spin up multiple interpreters.

Web services in Python that want to handle multiple comcurrent requests in the same interpreter should be using a web framework that is designed around that expectation and don't use a global request context object, such as FastAPI.


No, Flask has global objects wrapping state objects in contextvars.

This is even more funny, because now you need to switch the global reference according to the context. With GIL, it is easy; without it,...

You misunderstand. The "request" or "g" objects in Flask are proxies which access the actual objects through contextvars, which are effectively thread-local storage with some extra sugar. The context stack of a contextvar is already within the TLS and therefore always bound to a specific thread.

I've nearly seen the opposite - tons of libraries and tons of user code that uses globals either directly or transitively.

I have not been seeing good Python code, for sure. Hopefully it's not a majority. But it's very far from non-existent.


You can modify the posted script to eliminate global variables:

  def f():
      l = [0]
      for i in range(100000000):
          l += [2]
      return l

  x = f()
  print(x[0])
Timings:

  3.9:                    8.6s

  3.14:                   8.7s

  3.14 (free-threading): 11.6s
3.14 is not faster than 3.9 and the free-threading build is 33% slower.

I get:

3.9: 2.78

3.14: 3.86

3.14t: 3.91

This is a silly benchmark though. Look at pyperformance if you want something that might represent real script/application performance. Generally 3.14t is about 0.9x the performance of the default build. That depends on a lot of things though.


Pyperformance is a bloated, over-engineered test suite that does not catch anything. Due to the bloat it is hard to see what is even measured.

This benchmark demonstrates that global variables are not needed to find severe regressions.


What is this $hi+? You're creating a list that looks like this: [0, 2, …, 2]. It's also common / Pythonic to use uppercase L for lists.

If you don't want to use global variables just add the result of f to x and stop using the global variable, i.e.

   x += f()

Not even wrong.



Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: