Is it a bad habit to use eval in Python?

Asked 2 years ago, Updated 2 years ago, 38 views

In order to easily store the information of the song, we have created and used the following classes.

class Song:
    """The class to store the details of each song"""
    attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
    def __init__(self):
        for att in self.attsToStore:
            exec 'self.%s=None'%(att.lower()) in locals()
    def setDetail(self, key, val):
        if key in self.attsToStore:
            exec 'self.%s=val'%(key.lower()) in locals()

It seems to me that the above method is much more scalable than the if/else syntax, but the way you use eval is not good and it is known as a less secure method. Please tell me why and how to define the above class in a better way.

python eval

2022-09-21 18:38

1 Answers

First of all, eval is a bad programming habit as you said. To give you a couple of reasons:

For the above class, setattr can be used instead:

class Song:
    """The class to store the details of each song"""
    attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
    def __init__(self):
        for att in self.attsToStore:
            setattr(self, att.lower(), None)
    def setDetail(self, key, val):
        if key in self.attsToStore:
            setattr(self, key.lower(), val)

Of course, there are cases where you have to use eval or exec, but those cases are very rare. It's definitely not a good habit to use eval in this case. The reason why we keep emphasizing that it's such a bad habit is that eval and exec are often used in the wrong way.


2022-09-21 18:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.