DEV Community

Cover image for Don't mess with default Python scoping

Don't mess with default Python scoping

mzsrtgzr2 profile image Moshe Roth ・1 min read

Using the global and nonlocal keywords shouldn't happen too often imho. I think it's hard to debug and read. Newcomers may not see the big picture as the original writer of a piece of code. So, when those are used - keep very tight set of tests to make sure it won't be broken in the future and also - more understandable. I tend to read tests to understand how to use.
Why not use them? - I think it makes code less modular. So Use it only in the very same Unit of code.

For example,

def client(region_name):
    global emr  # <-- (1)
    emr = boto3.client ('emr', region_name=region_name)

... other functions...

def get_cluster_dns(cluster_id):
    response = emr.describe_cluster(ClusterId=cluster_id)
    return response['Cluster']['MasterPublicDnsName']

... other functions...

I won't call this a "good" example (I would rather gather those functions to a Class with an emr property) - but at least it's "understandable". The writer intended for the "client" method to be called first for initialization before any other function in this file.

If you can think of other examples to when it's right to use global and nonlocal, please comment in the discussion.


Editor guide
rhymes profile image

It's pretty rare indeed to use global or nonlocal in day to day programming

The few times it happened to me was kinda the result of improper design in the interface of the code. Over the years I switched to a mostly functional style of programming in Python so no globals as much as possible