2

I have seen two examples of people using Flask writing a function like

@property
def serialize(self):
    return { # object data in easily serializable format }

I understand property as a replacement for getters and setters, but who would be getting or setting a serialize function? Is there some native serialize method that we are attaching extra code to? Why isn't this just an instance method?

Community
  • 1
  • 1
Noumenon
  • 5,099
  • 4
  • 53
  • 73
  • I don't know if there's a better reason, but this will prevent overwriting it in the instance. – L3viathan Feb 01 '16 at 23:48
  • 4
    Technically, it is not exactly an instance method, since you'll be accessing it as `obj.serialize`, not `obj.serialize()` — there's a stylistic difference. Although I think that in the referenced example it should have stayed a method. If a property has a verb as a name, it's a bad sign. – fjarri Feb 01 '16 at 23:55
  • 5
    This seems like a grammar problem rather than a coding problem- I would expect `myclass.serialize` to be a callable function, it would be OK if it was instead called `myclass.serialized` to make it more obvious it was a property. – Marius Feb 01 '16 at 23:56
  • Oh, shoot, I didn't realize I was looking at the exact syntax used in my example of how to define a property on a member attribute. It was the verbiness of the function name that threw me off and made me think it was a function. Thank you. – Noumenon Feb 01 '16 at 23:58
  • 2
    Naming things is hard... https://blog.stackoverflow.com/2009/03/it-stack-overflow-update-naming-is-hard/ – reptilicus Feb 02 '16 at 00:02
  • Using properties makes refactoring easier, you can change a static attribute into a dynamic function call or back without having to change code elsewhere that interacts with the class. I'm not sure why it makes sense in your linked example, though. Maybe it's specific to `jsonify`, which is a module I don't know? – Håken Lid Feb 02 '16 at 00:22

0 Answers0