2

Is it possible to use the name of an input, eg a yaml/dict key, on self while not knowing that key literally?

Meaning, if there were some data like:

entries = [ {'foo': 'foo 1', 'bar': 'bar 1'}, {'foo': 'foo 2', 'bar': 'bar 2'}, ] 

How could we do the below without explicitly preprogramming 'foo' and 'bar' to name the self variables?

class entry(object): def __init__(self): self.foo = entries[0]['foo'] self.bar = entries[0]['bar'] 

And I suppose those self assignments would not have to be named foo and bar, but at least be able to reference them as such.

2
  • 2
    You can use setattr function. for example setattr(self, 'foo', 'entries[0]['foo']') is equivalent to self.foo = entries[0]['foo'] Commented Aug 26, 2019 at 3:16
  • I believe I understand what you want to do, but that's not a good design. Classes, by definition, should serve as a "contract" - it should have attributes such that whomever calls those classes/instantiate objects know what to expect. A class that has totally unpredictable attributes is useless - how will anyone know what object to use? If you want a dynamic data structure that is mutable, and that holds different "attributes" at different points in time, you need exactly a dict. Instead of using obj.foo, you'd call my_dict['foo'] - so I'd just stick to your entries dictionaries Commented Aug 26, 2019 at 3:19

1 Answer 1

5

You can use the built-in function setattr to add/set an attribute on an object in Python

def __init__(self): for k, v in entries[0].items(): setattr(self, k, v) 
Sign up to request clarification or add additional context in comments.

1 Comment

This helped me a ton. I have also used if hasattr(self, k): prior to using setattr() as well to catch instances (in the else clause) where an invalid key may be passed through to the class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.