Friday 15 January 2010

python - Why is using 'eval' a bad practice? -


I am using the following class to easily store your song data.

"class": "class" to store the description of each song "attsToStore = ('name', 'artist', 'album', 'style', 'location') Def __init __ (self): for att in self. AttsToStore: locals () def setDetail ('self' in the key, val) 'exec' itself.% S = None '% (att.lower ()): if self.attsToStore: exec' self.% S = val ' % Local people (key.lower ())

I think this is more expandable than writing a if / else block However, Eval is considered to be a bad practice and unsafe to use. If so, can someone explain to me and show me a better way of defining the class above?

Yes, using eval is a bad practice for some reasons:

  1. There is almost always a better way to do this
  2. Very dangerous and unsafe
  3. Debugging makes it difficult
  4. Slow

In your case you can use instead:

  class song: "" "class to store the details of each song" "AttsToStore = (' Name ',' artist ',' album ',' style ',' location ') def __init __ (self): For the att .stostor: setetter (self, et.) Def setDetail (self, key, val): If there is a key in itself.Testor: setattr (self, key.color, wal)  < / Pre> 

Edit:

There are some cases where you have to use an acoust or an app. But they are rare. Using Aval in your case is definitely bad behavior. I emphasize bad behavior because eval and exec are often used in the wrong place.

Edit 2:

It seems that some disagree that eval is 'very dangerous and unsafe' in OP case. This can be true for this specific case but in general no question was normal and whatever I have listed is also true for the general case.

Edit 3: Reorder Point 1 and 4


No comments:

Post a Comment