[Tutor] Playing with generators

Leam Hall leamhall at gmail.com
Wed Aug 10 17:00:15 EDT 2022


On 8/10/22 12:12, Mats Wichmann wrote:
> On 8/10/22 05:32, Leam Hall wrote:

>> class Person():
>>      def __init__(self, data = {}):
> 
> don't do this: don't use a mutable default argument

Hey Mats, can you explain why that's an issue? In this case, data is the dict of key word arguments, when the number of kwargs will be long.

> def make_person(data):
>      """ Creates Person instances, yielding a lookup key and the instance."""
>      for d in data:
>          p =  Person(**d)
>          yield p.fname, p

The issue with the Person(**d) is that all arguments must be present, in some form or other. For example:

class Person():
     def __init__(self, fname, lname, nname = ''):
	""" first name, last name, optional nickname, defaults to 'fred' """
         self.fname = fname
         self.lname = lname
         self.nname = nname or "fred"

After a few more initialization variables, the __init__ line will get pretty long. That's why I tend to use a data dict; I can keep the init line short, and deal with any missing variables in a way that best fits that variable.

I'm not using a dataclass, the goal is to learn generators. Things like dataclasses come later, when I know more of what the goal is.

Thanks!

Leam

-- 
Automation Engineer        (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)


More information about the Tutor mailing list