0

I have a list of objects. I have a user inputted string. I need to check and see if the string is in the list of objects.

For example:

string = "book"
object_list = [book, paper, pencil]
if eval(string) in object_list:
  #do this, etc

This works as long as the string is in the list. If the string is something else, like: string = 'ruler'

Then the if eval(string)... statement gives an error: NameError: 'ruler' is undefined.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 1
    Ouch, I mistakenly flagged it as duplicate, please ignore. Well, anyway: See possible duplicate of [Is Using eval In Python A Bad Practice?](http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice) –  Mar 28 '13 at 02:45
  • What are you **really** trying to do? What *is* `book`, etc.? Suppose you find the item in the `object_list`; then what? Why should the person who is running your program have any idea what your variables are named? – Karl Knechtel Mar 28 '13 at 04:01

2 Answers2

2

Don't use eval - just umm, either create a dict mapping eg:

dispatch = {'book': book, ...}

Then use that and let a traceback happen - much more controlled....

or at worst use globals():

if globals()[string] in object_list:
    # do something...
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • I'm new to programming. Would you mind explaining a bit more? I've read about the globals function but I don't understand it. And how would I go about making the dictionary contain the object book in the value position. – user2218093 Mar 28 '13 at 03:12
  • Sure - the best thing you can do is look up `globals()` in the manual, or look up how a `dict` works... – Jon Clements Mar 28 '13 at 03:15
  • I've done both. 'Globals: Return a dictionary representing the current global symbol table.' That is greek to me. I've used dictionaries a bit but I wouldn't know how to take a string and convert it to a dictionary containing string keys and object values. – user2218093 Mar 28 '13 at 03:28
1

if you need to check if the string is in the list, why dont u just use,

if string in object_list:
    #code
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69