Python refactoring question and create dynamic attributes

DL Neil PythonList at DancesWithMice.info
Sun Jun 23 15:59:09 EDT 2019


On 23/06/19 7:56 PM, Arup Rakshit wrote:
> In the below code:
> 
>      @classmethod
>      def find(self, id):
>          if isinstance(id, list):
>              rows = self.__table__().get_all(*id).run(self.__db__().conn)
>              result = []
>              for row in rows:
>                  acategory = Category()
>                  acategory.__dict__.update(row)
>                  result.append(acategory)
>              return result
>          else:
>              adict = self.__table__().get(id).run(self.__db__().conn)
>              acategory = Category()
>              acategory.__dict__.update(adict)
>              return acategory
> 
> I have 2 questions:
> 
> 1. Is there any better way to create attributes in an object without using __dict__().update() or this is a correct approach?
> 2. Can we get the same result what for row in rows: block is producing without killing the readability ?


Examining the readability concern(s):-

1
If it seems complex, first write a comment (in plain English).

2
Is the most basic refactoring improvement is any possible improvement in 
attribute/variable names?


A mid-point between these two: if you find the intricate coding of 
specific concepts awkward to read/explain, eg

__table__().get_all(*id).run(self.__db__().conn)
or __dict__.update(row)

then might you consider a short 'helper function' - whose name will 
explain-all and whose body will 'hide' or abstract the complex detail?

eg absorb_attributes( acategory, row )

(and yes, someone, somewhere, is absolutely itching to throw-in a Star 
Trek reference!)
-- 
Regards =dn



More information about the Python-list mailing list