jsonmodels icon indicating copy to clipboard operation
jsonmodels copied to clipboard

Refactor some code for understandability

Open micahjsmith opened this issue 7 years ago • 2 comments

Hello, I spent a fair amount of time reading through the code of jsonmodels to understand how it worked. It employs a fair amount of interesting python constructs, like __get__ and __set__ methods of BaseField and a healthy use of metaclasses and class methods.

To help myself understand what was going on, I found myself making small changes to the code for readability and interpretability. This includes

  • consistently use if/else to make control flow explicit
  • fix typo of structure_name (still leaving structue_name for backwards compatibility)
  • use more explicit names for iteration over class attributes
# original
for attr in dir(cls):
    clsattr = getattr(cls, attr)

# new
for attr_name in dir(cls):
    field = getattr(cls, attr_name)
  • try to simplify logic of field initialization by adding an _initialized attribute to BaseField and guarding against re-initialization
  • make Base.get_field a classmethod, which avoids a linear search through the entire set of fields on each access

I thought other people might benefit from these small changes. Hope this is helpful, let me know what you think!

micahjsmith avatar Dec 17 '18 19:12 micahjsmith

Hi @beregond , any thoughts on this PR?

micahjsmith avatar Jan 14 '19 09:01 micahjsmith

Hi @beregond any thoughts on this PR?

micahjsmith avatar Mar 21 '19 17:03 micahjsmith