DEV Community

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

Posted on

1

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay