0

So, I've create global objects that can be accessed by any method. Now I have to return the objects by a method like this.

def get_my_obj  (obj_name):  
    if   obj_name == "abc":  return  abc
    elif obj_name == "xyz":  return  xyz
    elif obj_name == "def":  return  def

Is there a simpler way to achieve this? I have hundreds of these objects.

elroyalva
  • 107
  • 1
  • 9
  • 1
    is obj_name necessarily a string? – Jonas Jul 25 '16 at 20:06
  • 2
    Possible duplicate of [How do I create a variable number of variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables-in-python) – Morgan Thrapp Jul 25 '16 at 20:07
  • 1
    could you share a little more of why would you do this? I'm sure you know the global objects are generally not a good idea. – fodma1 Jul 25 '16 at 20:07
  • 4
    Use a `dict` with the objects as values. But first tell us, why you are doing this? What is the problem you are really trying to solve? –  Jul 25 '16 at 20:08
  • Agreed with the rest of the comments. There's no simple way to do this because this is a Thing That Should Not Be Done. If you have to do it, either kludge it like you're doing or find a better way to implement that functionality. – Adam Smith Jul 25 '16 at 20:08
  • 4
    `globals()[obj_name]` is the literal answer. Don't do this is the rest of the answer. – dawg Jul 25 '16 at 20:11
  • 1
    This reeks of being an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is the actual problem you are trying to solve (what is your script/app supposed to be doing)? – kylieCatt Jul 25 '16 at 20:15
  • Unfortunately I have to do this. Mostly improving on already built code. I looked up dict() and that seems to be the best way to do this. – elroyalva Jul 25 '16 at 20:26
  • There are hundreds of already written objects, they are to be accessed by many methods. I don't even know how many are using it. I know there is a simpler way than me writing 586 return statements. I don't really like the method I was using. But I'm pretty sure that I got my answer above! – elroyalva Jul 25 '16 at 20:30

1 Answers1

3

Through the use of globals() in the appropriate file, it is entirely possible for achieve such an evil act.

# file1.py

abc = 'foo'
xyz = 'bar'
dfe = 'baz'


def get_my_obj(obj_name):
    return globals()[obj_name]


# file2.py

from file1 import get_my_obj

print(get_my_obj('abc'))  # 'foo'

globals() retrieves variables within the current module. In this case, it may be the file where it is executed.

Can you do it? Yes. Would I do it? No. Is it my business to decide if you should do it anyway? No.

Brian
  • 7,394
  • 3
  • 25
  • 46
  • I guess this would by my approach, or I may use dict() to get it done. As vile as my approach may be, I think I'd prefer it over correcting the many methods that already use these globals. Thanks again Brian! – elroyalva Jul 25 '16 at 20:33