4 ms·
The namedtuple example is wrong. The constructor requires all of the parameters, and an attribute cannot be set: >>> from collections import namedtuple
by dalke 12y ago
The namedtuple example is wrong. The constructor requires all of the parameters, and an attribute cannot be set:
>>> from collections import namedtuple
>>> LightObject = namedtuple('LightObject', ['shortname', 'otherprop'])
>>> m = LightObject()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 3 arguments (1 given)
>>> m = LightObject("first", "second")
>>> m.shortname
'first'
>>> m.shortname = 'athing'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
Also, bare try/excepts as in:
try:
# get API data
data = db.find(id='foo') # may raise exception
except:
# log the failure and bail out
log.warn("Could not retrieve FOO")
return
are really bad. The failure might be caused by a ^C or MemoryError, or even a SystemExit, should db.find() desire to do that.
Instead, qualify it by catching Exception:
try:
# get API data
data = db.find(id='foo') # may raise exception
except Exception:
# log the failure and bail out
log.warn("Could not retrieve FOO")
return
It's also poor form to "return True" in the exit method of the context manager. If there is no exception then that's not needed at all, and if there is an exception ... well, that code will swallow AttributeError and NameError and ZeroDivisionError, and leave people confused as to the source of the error.
- ryan_sb 12y agoThanks for correcting me, I'll get those updated ASAP.
- pdonis 12y agoA good rule of thumb: if you show actual code, run it before you post it!
- mkesper 12y agoShouldn't you qualify the exception class as properly as you can? If you can't I'd expect to check for certain error classes you can handle and else reraise the Exception.
- dalke 12y agoYes, I would do that in nearly every case. However, I don't know the larger context. If this were at the top-level of a web services handler where a "return None" indicates a 400 - Internal Server Error, then logging the database failure and stopping is likely acceptable. Even then, I wouldn't call it good code. However, the goal of this essay seemed to be to give the minimal example, and a more complete example would have required introducing a fake database module with its own exception type. I believe that would have obscured the intent. I would have preferred real, working code. In this case, with sqlite3. That's fundamentally a pedagogical choice though.
- timdierks 12y agoI frequently want ad-hoc slots to create a structure of related values without the verbosity of a dict with static keys. What's the pythonic method? E.g. when I want to carry a foo, a bar, and a baz around, but namedtuple isn't right (e.g. I need mutation). I'd prefer config = Someclass() config.foo = 1 config.bar = "quux" config.baz = 3.3 and then using config.bar, etc. over: config = { 'foo': 1, 'bar': "quux", 'baz': 3.3 } and then using config['bar']