Here is an example class:
from datetime import datetime
class Article:
published = datetime.now()
for propname in "year month day hour minute second".split():
exec "%s = property(lambda self: self.published.%s)"%(propname, propname)
del propname
As you can see, I’m using exec to optimize the creation of multiple property() objects. I often read that using exec is bad and that it is a security hole in your program. In this case, is it?
In this case, it’s not really a security threat, since the security threat arises when the executed string is something the user has any kind of access to. In this case, it is a split string literal.
However, even if it’s not a security risk,
execis almost always a poor choice. Why not usegetattrandsetattrinstead?One flaw is that this has to be done in the
__init__method, so it depends whether you have a good reason not to include it there.