0

Trying to figure out how I can do the following. Suppose I have some function which has an attribute that I want to set. generically let's call it: func.attrib = ['list']. the challenge is that 'func' can vary according to the result of some look up (say, based on a key within a dictionary).

so, I might want to say:

func.attrib = ['list']
OR
func1.attrib = ['list']
OR 
func2.attrib = ['list']

etc

where func, func1, func2 are the result of a look up in a dictionary.

Treating func as a string and appending ".attrib" will not work, so I'm guessing a more specific method of formatting is required.

any help appreciated!

ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
laszlopanaflex
  • 1,836
  • 3
  • 23
  • 34
  • How do you know if you should use func1, func2, func3 etc? – Amit Gold Mar 07 '16 at 18:46
  • that is based on a look-up in a dictionary, based on a key. i did not bother to include it in the original question – laszlopanaflex Mar 07 '16 at 18:50
  • I mean, where is the result of the look up stored? Is the result the function? Or is it a string indicating the function? – Amit Gold Mar 07 '16 at 18:50
  • the result is a string indicating the function. i.e. the entry in the dictionary would be "func", "func1", or "func2" – laszlopanaflex Mar 07 '16 at 18:51
  • If you don't have a lot of functions, you could build a dictionary of them where the key is that string and the value is the function. Otherwise, you could use the `globals` variable (I think, not sure), you could search the documentation about that. – Amit Gold Mar 07 '16 at 18:53

2 Answers2

0

Have you considered using an if statement? Coz for say, if the look up is "Big Melons" and for that you have to use func1.attrib then you could use if or elif statement.

if look_up = "Big Melons":
    func1.attrib = ["Lists"]
elif look_up = "Small Melons":
    func2.attrib = ["list"]
Imtiaz Raqib
  • 315
  • 2
  • 20
  • this is suboptimal because there could potentially be many functions, and this type of variable usage is needed in a few ways down the road. the question really is is there a way to append a string to an attribute call. – laszlopanaflex Mar 07 '16 at 18:59
0

If you're trying to set an attribute on a function stored as a value in a dict, just do the lookup and set the attribute, e.g.

mydict = {'foo': func, 'bar': func1, 'baz': func2}

key = ... get a key that is either 'foo', 'bar' or 'baz' ...

mydict[key].attrib = ['list']

If no such dict exists, you but all the function in question are defined in the global namespace of the module, and you want to assign the attribute based on the function name itself ('func', 'func1', etc.), then you could use globals to get the current module's global dict:

# key is 'func', 'func1', or 'func2'
globals()[key].attrib = ['list']

If the functions are in some other module, you'd use getattr:

# All the modules are in module spam
import spam

getattr(spam, key).attrib = ['list']
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271