qkhhly
qkhhly

Reputation: 1220

how to prevent python function to read outer scope variable?

When defining a python function, I find it hard to debug if I had a typo in a variable name and that variable already exists in the outer scope. I usually use similar names for variables of the same type of data structure, so if that happens, the function still runs fine but just returns a wrong result. So is there a way to prevent python functions to read outer scope variables?

Upvotes: 5

Views: 1805

Answers (3)

Quentin
Quentin

Reputation: 6378

A python function can only see the global scope of the module it is defined in. As an example, if you run the code:

def accidentalresolveglobal():  
    try:
        return x
    except NameError: 
        print("variable x does not exist")
        
x=1     
print(accidentalresolveglobal())

The function will resolve x from the outer global scope.

But if you place the function definition into a separate module myfuncs.py and then restart your python session and import that module:

import myfuncs
x=1
print(myfuncs.accidentalresolveglobal())

then the function will not be able to resolve x, and you get a NameError exception as you would like.

The key point (as I understand it), is that a function can only see global objects that exist in its own module. So if you place your function definitions into their own module, and import them into your main module, then you won't have a problem where global objects from your main module are accidentally resolved by a function. I'm just learning python, but it seems like placing function definitions into a separate module provides an important degree of encapsulation in order to avoid accidental name collisions.

I recognize this question is 8 years old. I don't know if the implementation of module global scope has changed across python versions.

Upvotes: 0

Meghdeep Ray
Meghdeep Ray

Reputation: 5537

You're going against the point of having Scopes at all. We have local and global scopes for a reason. You can't prevent Python from seeing outer scope variables. Some other languages allow scope priority but Python's design principles enforce strong scoping. This was a language design choice and hence Python is the wrong language to try to prevent outer scope variable reading.

Just use better naming methodologies to ensure no confusion, you change up variable names by using the Find-Replace function that most text editors provide.

Upvotes: 3

wanderlust
wanderlust

Reputation: 1936

They say you should avoid usage of global variables if possible. Also, keep in mind, that python has rules on searching variables in the specific order.

So you can avoid checking global variables only if you will delete them, but it makes usage of global variables useless.

Upvotes: 0

Related Questions