1

So I'm currently converting my non-object oriented python code to an object oriented design. This is an example of what my file looks like.

[object1] # this only has keys 1, 2 and 3
key1: "value 1"
key2: "value 2"
key3: "value 3"

[object2] # this only has keys 1, 2 and 4
key1: "different value 1"
key2: "different value 2"
key4: "value 4"

[object3] # this has all possible keys 1, 2, 3, 4, 5
key1: "another different value 1"
key2: "another different value 2"
key3: "different value 3"
key4: "different value 4"
key5: "value 5"

I parse this to create key:value pairs in a dictionary for each (non-created at this point) object. So my list of all possible keys, and lists of dictionary keys would look like this, for these three objects: (pseudo-code)

possibleKeyList = ['key1', 'key2', 'key3', 'key4', 'key5']
dictionary1 keyList = ['key1', 'key2', 'key3'] # has keys 1, 2, 3
dictionary2 keyList = ['key1', 'key2', 'key4'] # has keys 1, 2, 4
dictionary3 keyList = ['key1', 'key2', 'key3', 'key4', 'key5'] # has all possible keys

As you can see, each dictionary may have all possible keys, or only a few, etc (but the values are still different). When I create a new class Object, I pass in the specific dictionary. I want to initialize the keys found in that dictionary to their respective values...and if the key ISN'T in the dictionary (like how dictionary2 does not have 'key3' or 'key5'), then that attribute isn't created. This is what I am figuring out how to do here:

Class MyClass( object ):
    def __init__(self, **kwargs):
    possibleKeys = ['key1', 'key2', 'key3', 'key4', 'key5']
    for key in kwargs.keys():
        if key in possibleKeys:
            # create attribute for this instance using the key:value pair
        else:
            # don't create the attribute, but also don't have a default blank value

dictionary = {'key1': 'different value 1', 'key2': 'different value 2', 'key4': 'value 4'}
newObject = MyClass(**dictionary)

I tried avoiding an AttributeError by setting ALL possible attributes to default values ( "", [], or False), then only replacing these defaults if the key is present in the dictionary. This gives me what I want...but for some objects, I only have one or two attributes, and the rest are just empty/default and I don't want a bunch of place holders that don't need to be there taking up space in this object

Is this the best way to go about this? I have also looked at things like setattr but I am not sure how everything ties in (init, setting attributes if they are present in **kwargs etc.

Thanks everyone. I hope I was clear enough.

EDIT I used this and it seems to work, but I will have to test it and make sure it is doing what I need.

class MyClass( object ):
def __init__(self, **kwargs):
    self.__dict__.update(kwargs)


# method to produce dictionary for specified term/object

newObject = MyClass(**dictionary)
print newObject.<key>
bburc
  • 169
  • 1
  • 2
  • 13
  • 1
    `self.__dict__.update(kwargs)` should work fine for you. just an idea: have you thought about directly storing the dictionary as an attribute and overloading `__getitem__` and `__setitem__`? then you could access like this: `newObject[]`. – Rick Oct 14 '15 at 17:42
  • 1
    more on treating your object like a dict here: http://stackoverflow.com/questions/3387691/python-how-to-perfectly-override-a-dict – Rick Oct 14 '15 at 17:48
  • I have not looked into that yet. What is the advantage aside from syntax when accessing the keys/values? – bburc Oct 14 '15 at 18:32
  • 2
    For further fine grained control I recommend the excellent talk of David Beazley on Python metaprogramming: https://www.youtube.com/watch?v=sPiWg5jSoZI – Sebastian Wozny Oct 14 '15 at 19:05
  • 1
    some advantages: you can do everything with your custom object that you can do with a vanilla dict, such as iterate through the keys, `update`, things like that. – Rick Oct 14 '15 at 19:15
  • excellent thank you both very much! – bburc Oct 14 '15 at 19:17
  • i second the Beazley talk linked by @SebastianWozny. it's gold, jerry, gold. – Rick Oct 14 '15 at 19:17

0 Answers0