Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 878
Xiaowen Zhang Avatar asked Dec 31 '22 17:12

Xiaowen Zhang


1 Answers

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.

like image 85
Chris Avatar answered Jan 02 '23 06:01

Chris