I wanted to share an idea that came up while working on some dynamic code and plugin setups. It’s about making Python’s global
keyword a little more expressive and compact.
Right now, if you’re inside a function and want to import something and make it global, you have to do this:
def func():
global requests
import requests
Same goes for assigning global variables:
def setup():
global config
config = load_config()
This works fine, but it feels a bit verbose when the intent is pretty clear: declare something global and define it.
The idea
Would it make sense to support syntax like:
def func():
global import requests
Or:
def setup():
global config = load_config()
And for functions:
global def handler():
...
Or even:
def outer():
global def conditional_logic():
...
The idea behind global def
is that the function would automatically be placed in the global scope — not captured by the parent scope. This could make defining conditional or dynamic functions easier without needing to do a globals()['func_name'] = ...
manually.
Why this might be useful
- It removes boilerplate when declaring globals
- Makes intent clearer at the point of declaration
- Could simplify patterns in dynamic or embedded code
- Useful for conditional function declarations that need to be globally visible
Why I’m not sure
I’m not familiar with how Python’s parser handles global
, so this might be more complex than it seems. I’m assuming this would require grammar changes, and I know that’s not trivial.
Also not sure if this would go against Python’s design philosophy or encourage bad practices around global usage — though I think there are valid use cases where it could be helpful.
Some open questions
- Would this kind of syntax even be possible in Python’s current parser model?
- Should it be limited to certain scopes (like top-level functions)?
- Are there obvious edge cases I’m missing?
- Has anything like this already been proposed?
Would love to hear thoughts — especially from anyone familiar with how this might work under the hood or if there’s prior art for this. Totally open to it not being practical, but figured it was worth floating.
Thanks!