Does “exec” use a security risk under controlled conditions?

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 use execto optimize the creation of several objects property(). I often read that use is execbad and that this is a hole in your program. In this case, this?

+5
source share
2 answers

In this case, this is not a security risk, since a security risk occurs when the executable line is what the user has access to. In this case, it is a string literal.

However, even if this is not a security risk, it is execalmost always a bad choice. Why not use getattrand setattrinstead?

from datetime import datetime
class Article:
    published = datetime.now()

    def __init__(self):
        for propname in "year month day hour minute second".split():
            setattr(self, propname, getattr(self.published, propname))

, __init__, , .

+6

exec ; script.

0

All Articles