1

I came across this python code base where there is a custom ORM code that maps to MongoDb. I was asked to write new Entities following the existing pattern of code. I have only been writing python code for a week now. But, i find this mix of getter style method name marked as property etc confusing. I know I am not giving a lot of context here. But, I want to discuss how this api looks from a good python programming api pov.

Its python 2.7.

class Entity(object):
    def save(self): 
    ...

class Person(Entity):
  ...
  @property
  def get_config(self):
    return getattr(self, 'config', None)

  def set_config(self, config):
    self.set('config', config)
  ...
smartnut007
  • 6,324
  • 6
  • 45
  • 52

1 Answers1

3

It doesn't look that good. There is no reason to use getters/setters in Python just to get and set static values. See this question. You should only use them if you actually need to programmatically compute the attribute value on every access.

Also, instead of using getattr to return None if the attribute is undefined, you should just initialize it to None. Then you can later read its value unconditionally.

So:

class Person(Entity):
    def __init__(self):
        # initialize config to None
        self.config = None

Later, if other code needs to read the config attribute of a Person instance called somePerson, just do:

somePerson.config

If you need to set it, just do:

somePerson.config = newConfig
Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • 1
    Agreed; if the pattern *does* demand computation on read/write it should make complete use of the getter/setter **decorator** pattern which uses a `@config.setter` decorator invocation as well as a getter. – BlackVegetable May 06 '13 at 18:45