Python 3.3 PEP 418 example gives 'namespace' object is not iterable error
-
20-06-2021 - |
Pregunta
The beta of Python 3.3 is out and wonderful.
The newly reworked time module has the get_clock_info method to get information about the platform's many logical clocks. PEP 418 describes the new time module.
When I try and run one of the example programs referenced in PEP 418, clock_resolution.py, I get TypeError: 'namespace' object is not iterable
on line 54 below:
46 clocks = ['clock', 'perf_counter', 'process_time']
47 if hasattr(time, 'monotonic'):
48 clocks.append('monotonic')
49 clocks.append('time')
50 for name in clocks:
51 func = getattr(time, name)
52 test_clock("%s()" % name, func)
53 info = time.get_clock_info(name)
54 if 'precision' in info:
55 print("- announced precision: %s" % format_duration(info['precision']))
56 print("- implementation: %s" % info['implementation'])
57 print("- resolution: %s" % format_duration(info['resolution']))
'info' on line 53 contains:
>>> info
namespace(adjustable=True, implementation='gettimeofday()', monotonic=False, resolution=1e-06)
So how does one iterate over a namespace object?
Solución
You don't want to iterate the object; you just want to test for presence of an attribute. Two ways:
# "easier to get forgiveness than permission" approach
try:
print(info.precision)
except AttributeError:
pass
# "look before you leap" approach
if hasattr(info, "precision"):
print(info.precision)
The in
test is used to check if something is in a dictionary, a list, a tuple, or some other sequence. In the general case, in
will try to iterate something to find the value (dict
and set
are exceptions; Python special-cases them for efficiency). But info
is an instance of a class that doesn't support iteration.
You could, if you wished, do this:
# alternate "look before you leap"
if "precision" in info.__dict__:
print(info.precision)
Attributes actually are stored in a dict
instance member variable named .__dict__
.
EDIT: @DSM wrote a comment that showed an alternative to the above. The built-in function vars()
will return the .__dict__
member variable, so this is equivalent to the above:
# nicer alternate "look before you leap"
if "precision" in vars(info):
print(info.precision)