Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name variable correctly to avoid warning like "Shadows name from outer scope" in Python

Tags:

I use PyCharm for my python program, and I wrote codes below:

def get_files_name():
    root_dir = "/Volumes/NO NAME/"
    for root, ds, fs in os.walk(root_dir):
        for f in fs:
            print(os.path.join(root_dir, f))


get_files_name()
for root, ds, fs in os.walk(other_dir):
    pass

So I get a Warning text like "Shadows name 'ds' from outer scope". I know the effect of scope, but I still want to use the same code format like "for root, ds, fs in ...." at inner or outer of scope.

I have searched PEP8, however, I still don't know how to name variable in function normatively.

Could you give me some suggestion?

like image 272
GoldenMan Avatar asked Mar 04 '18 09:03

GoldenMan


2 Answers

In general: just ignore the warning. It's just a warning, not an error. You have use for both global and local names that happen to match.

However, I'd not put an os.walk() call at global scope anyway. I'd rather put that into a function too, which has the happy side-effect of the names you used no longer being globals.

For example, you could use a main() function:

def main():
    get_files_name()
    for root, ds, fs in os.walk(other_dir):
        pass

if __name__ == '__main__':
    main()

Generally speaking, you don't want to leave loop names like root, ds, fs as globals in your module anyway. Those are implementation details, and should not become part of the public API of a module. If you have to use a for loop like that at the global scope, use _ single-underscore prefixes on the names and consider deleting them after the loop with del:

for _root, _ds, _fs in os.walk(other_dir):
    # do something with the files or directories

# clean variables for the loop that are not part of the API
del _root, _ds, _fs
like image 83
Martijn Pieters Avatar answered Sep 22 '22 13:09

Martijn Pieters


If your names repeats use "_" to avoid such warnings.It's a common practice.

def get_files_name():
    root_dir = "/Volumes/NO NAME/"
    for root, _ds, fs in os.walk(root_dir):
        for f in fs:
            print(os.path.join(root_dir, f))

get_files_name()
for root, _ds, fs in os.walk(other_dir):
    pass
like image 23
Alex Delarge Avatar answered Sep 19 '22 13:09

Alex Delarge