0

I have a class called House()

To make a new instance of House I can pass data like house = House(roof = roof)

To standardize how Houses get created (and make use of type annotations) House has a .new() static method that looks like:

class House():

  @staticmethod
  def new(roof: Roof):
    house = House(roof = roof)
    # do other stuff for new method, ie may add to session, etc.
    return house

However, this is kind of annoying because if house has say 10 attributes, it means there's a lot of copy and paste. For example here, to use keyword args (which is preferred), 'roof' is repeated 3 times.

Docs states that __init__ is not called when recreating, but I feel a bit strange over riding it for a .new() method or is this correct?

Also I feel like __init__ doesn't really solve the generic concern. I'm looking for the best of both worlds, where the existing defined properties are available on init, but I can also define logic that's different for each class.

Thinking along the lines of attributes from kwargs maybe but not exactly it?

An assumption is that there will always be some attributes that are not needed. Part of this is enforcing that say a house always needs a roof, but an attribute like owner doesn't need to be populated when it's first created. But if a new developer joins the team and calls House.new() they should be able to see that definition of what attributes are needed.

For example I can pass roof = Column(..., default = 1) is there a way in Column or similar to say something like required?

oooiiiii
  • 302
  • 2
  • 11
  • "Docs states that __init__ is not called when recreating, but I feel a bit strange over riding it for a .new() method or is this correct?" is correct, but I don't think there'd be any point anyway because you're using `@staticmethod` so you're not passing any particular instance when calling `new()` – roganjosh Dec 09 '19 at 23:37
  • I was trying to think of a way to use the built-in init method instead of .new() altogether. For example it seems like if the IDE is configured right the default does actually support type annotations (which makes sense, It is already defined!) https://stackoverflow.com/questions/49095677/type-hinting-for-the-init-function-from-class-meta-information-in-python – oooiiiii Dec 09 '19 at 23:42
  • I _think_ you're asking different things. Firstly, you can use [type annotations with defaults in function declarations](https://stackoverflow.com/a/38727786/4799172). Secondly, as you show in your link, you [could use `orm.reconstructor` to make use of `__init__`](https://docs.sqlalchemy.org/en/13/orm/constructors.html#sqlalchemy.orm.reconstructor). IIUC, though, your issue is that you want to just pass a dict to `__init__` and have it figure out how to replace the defaults. I can sorta think of a way of doing it, but I don't like it and I don't think it saves much typing – roganjosh Dec 09 '19 at 23:58

0 Answers0