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.
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
nonlocal, please comment in the discussion.