DEV Community

Cover image for Don't mess with default Python scoping
MoRoth
MoRoth

Posted on

Don't mess with default Python scoping

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,

https://github.com/aws-samples/aws-concurrent-data-orchestration-pipeline-emr-livy/blob/master/dags/airflowlib/emr_lib.py


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...
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
rhymes profile image
rhymes • Edited

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