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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With