reading-notes

reading notes for code fellows


Project maintained by dLeigh01 Hosted on GitHub Pages — Theme by mattgraham

Pythonisms

Dunder methods are something we’ve been using a bit so far with things like __iter__, and it should be very helpful to add some of the other possibilities to our repertiore.

Dunder Methods

Duner methods are a set of predefined methods you can use to enrich you classes by emulating the behavior of built in types. Some helpful ones are:

Iterators

If an object supports __iter__ and __next__ it will automatically work with for loops. A for loop is really a while loop behind the scenes that runs until it can no longer move to the next property of whatever it is iterating through. If you run all the way through an iterator, then it will raise a StopIteration exception. When you want to use these in a class, you will need both methods, one to call on itself, and the other to act as a next that can move between values and know when to stop.

Generators

A generator looks like a normal function, but is actually an object that can do something for as long as necessary. Within a generator, you can use yield to pass back control to the caller, but differently from return in a function, yield is only temporary, and retains its local state. You can use them to either iterate at a one by one rate, or leave them to run on their own depending on how you decide to call them, and they’re completely configurable, as you have to write it yourself.

Discussion

It will be nice to be able to add iterators to data structures we have so they can be iterated through rather than needing to write up a function for it every time. I can see a lot of uses for generators and I’ll be interested to see how we plan to go about working with them.

[< table of contents]

[< home]