Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

Why directly use dir() in all(...) always return False in python?

I want to know if multiple modules are imported, and have tried the following 3 ways. But I found their result are different. I wonder why directly using dir() in all(...) leads to incorrect result?

import re, os

# Approach 1
all(k in dir() for k in ('re', 'os'))  # False


# Approach 2
're' in dir() and 'os' in dir()  # True


# Approach 3
list = dir()
all(k in list for k in ['re', 'os'])  # True

question from:https://stackoverflow.com/questions/65541566/why-directly-use-dir-in-all-always-return-false-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

dir() without arguments depends on the current scope:

Without arguments, return the list of names in the current local scope.

Inside the generator expression the scope changes:

>>> list(dir() for _ in ("re", "os"))
[['.0', '_'], ['.0', '_']]

This is also true for list, set, and dict comprehensions:

aside from the iterable expression in the leftmost for clause, the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don't "leak" into the enclosing scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...