diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..64968e9a
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,32 @@
+# General
+.DS_Store
+.AppleDouble
+.LSOverride
+
+# Icon must end with two \r
+Icon
+
+# Thumbnails
+._*
+
+# Files that might appear in the root of a volume
+.DocumentRevisions-V100
+.fseventsd
+.Spotlight-V100
+.TemporaryItems
+.Trashes
+.VolumeIcon.icns
+.com.apple.timemachine.donotpresent
+
+# Directories potentially created on remote AFP share
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+
+# Jupyter Checkpoints
+.ipynb_checkpoints
+
+.idea
+__pycache__
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/Part 1/Section 02 - A Quick Refresher/04 - The While Loop.ipynb b/Part 1/Section 02 - A Quick Refresher/04 - The While Loop.ipynb
index c68c2e56..13a189ef 100644
--- a/Part 1/Section 02 - A Quick Refresher/04 - The While Loop.ipynb
+++ b/Part 1/Section 02 - A Quick Refresher/04 - The While Loop.ipynb
@@ -11,7 +11,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The **while** loop is a way to repeatg a block of code as long as a specified condition is met."
+ "The **while** loop is a way to repeat a block of code as long as a specified condition is met."
]
},
{
@@ -366,7 +366,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -380,7 +380,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.6.1"
+ "version": "3.9.10"
}
},
"nbformat": 4,
diff --git a/Part 1/Section 02 - A Quick Refresher/07 - Classes.ipynb b/Part 1/Section 02 - A Quick Refresher/07 - Classes.ipynb
index 5e46359d..6d9ae065 100644
--- a/Part 1/Section 02 - A Quick Refresher/07 - Classes.ipynb
+++ b/Part 1/Section 02 - A Quick Refresher/07 - Classes.ipynb
@@ -24,9 +24,7 @@
{
"cell_type": "code",
"execution_count": 1,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -41,7 +39,7 @@
"source": [
"We create **instances** of the `Rectangle` class by calling it with arguments that are passed to the `__init__` method as the second and third arguments. The first argument (`self`) is automatically filled in by Python and contains the object being created.\n",
"\n",
- "Note that using `self` is just a convention (although a good one, and you shgoudl use it to make your code more understandable by others), you could really call it whatever (valid) name you choose.\n",
+ "Note that using `self` is just a convention (although a good one, and you should use it to make your code more understandable by others), you could really call it whatever (valid) name you choose.\n",
"\n",
"But just because you can does not mean you should!"
]
@@ -49,9 +47,7 @@
{
"cell_type": "code",
"execution_count": 2,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)\n",
@@ -126,9 +122,7 @@
{
"cell_type": "code",
"execution_count": 5,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -146,9 +140,7 @@
{
"cell_type": "code",
"execution_count": 6,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -218,9 +210,7 @@
{
"cell_type": "code",
"execution_count": 9,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -238,9 +228,7 @@
{
"cell_type": "code",
"execution_count": 10,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -299,7 +287,7 @@
{
"data": {
"text/plain": [
- "'<__main__.Rectangle object at 0x000002375E7006A0>'"
+ "'<__main__.Rectangle object at 0x103561af0>'"
]
},
"execution_count": 12,
@@ -323,9 +311,7 @@
{
"cell_type": "code",
"execution_count": 13,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -386,7 +372,7 @@
{
"data": {
"text/plain": [
- "'<__main__.Rectangle object at 0x000002375E708DA0>'"
+ "'<__main__.Rectangle object at 0x10356c5e0>'"
]
},
"execution_count": 15,
@@ -419,9 +405,7 @@
{
"cell_type": "code",
"execution_count": 16,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -442,9 +426,7 @@
{
"cell_type": "code",
"execution_count": 17,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -485,7 +467,7 @@
{
"data": {
"text/plain": [
- "<__main__.Rectangle at 0x2375e716ef0>"
+ "<__main__.Rectangle at 0x103570640>"
]
},
"execution_count": 19,
@@ -507,9 +489,7 @@
{
"cell_type": "code",
"execution_count": 20,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -533,9 +513,7 @@
{
"cell_type": "code",
"execution_count": 21,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -588,9 +566,7 @@
{
"cell_type": "code",
"execution_count": 24,
- "metadata": {
- "collapsed": true
- },
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)\n",
@@ -633,10 +609,8 @@
},
{
"cell_type": "code",
- "execution_count": 40,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 26,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -666,10 +640,8 @@
},
{
"cell_type": "code",
- "execution_count": 41,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 27,
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)\n",
@@ -678,7 +650,7 @@
},
{
"cell_type": "code",
- "execution_count": 42,
+ "execution_count": 28,
"metadata": {},
"outputs": [
{
@@ -687,7 +659,7 @@
"False"
]
},
- "execution_count": 42,
+ "execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
@@ -698,7 +670,7 @@
},
{
"cell_type": "code",
- "execution_count": 43,
+ "execution_count": 29,
"metadata": {},
"outputs": [
{
@@ -714,7 +686,7 @@
"True"
]
},
- "execution_count": 43,
+ "execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
@@ -725,10 +697,8 @@
},
{
"cell_type": "code",
- "execution_count": 44,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 30,
+ "metadata": {},
"outputs": [],
"source": [
"r3 = Rectangle(2, 3)"
@@ -736,7 +706,7 @@
},
{
"cell_type": "code",
- "execution_count": 45,
+ "execution_count": 31,
"metadata": {},
"outputs": [
{
@@ -752,7 +722,7 @@
"False"
]
},
- "execution_count": 45,
+ "execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
@@ -770,7 +740,7 @@
},
{
"cell_type": "code",
- "execution_count": 46,
+ "execution_count": 32,
"metadata": {},
"outputs": [
{
@@ -786,7 +756,7 @@
"False"
]
},
- "execution_count": 46,
+ "execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
@@ -804,10 +774,8 @@
},
{
"cell_type": "code",
- "execution_count": 47,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 33,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -847,10 +815,8 @@
},
{
"cell_type": "code",
- "execution_count": 48,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 34,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -885,10 +851,8 @@
},
{
"cell_type": "code",
- "execution_count": 49,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 35,
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(100, 200)\n",
@@ -897,7 +861,7 @@
},
{
"cell_type": "code",
- "execution_count": 50,
+ "execution_count": 36,
"metadata": {},
"outputs": [
{
@@ -906,7 +870,7 @@
"False"
]
},
- "execution_count": 50,
+ "execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
@@ -917,7 +881,7 @@
},
{
"cell_type": "code",
- "execution_count": 51,
+ "execution_count": 37,
"metadata": {},
"outputs": [
{
@@ -926,7 +890,7 @@
"True"
]
},
- "execution_count": 51,
+ "execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
@@ -944,7 +908,7 @@
},
{
"cell_type": "code",
- "execution_count": 52,
+ "execution_count": 38,
"metadata": {},
"outputs": [
{
@@ -953,7 +917,7 @@
"True"
]
},
- "execution_count": 52,
+ "execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
@@ -984,7 +948,7 @@
},
{
"cell_type": "code",
- "execution_count": 53,
+ "execution_count": 39,
"metadata": {},
"outputs": [
{
@@ -992,10 +956,10 @@
"evalue": "'<=' not supported between instances of 'Rectangle' and 'Rectangle'",
"output_type": "error",
"traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mr1\u001b[0m \u001b[1;33m<=\u001b[0m \u001b[0mr2\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[1;31mTypeError\u001b[0m: '<=' not supported between instances of 'Rectangle' and 'Rectangle'"
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [39]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mr1\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m<\u001b[39;49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m \u001b[49m\u001b[43mr2\u001b[49m\n",
+ "\u001b[0;31mTypeError\u001b[0m: '<=' not supported between instances of 'Rectangle' and 'Rectangle'"
]
}
],
@@ -1028,10 +992,8 @@
},
{
"cell_type": "code",
- "execution_count": 54,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 40,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -1045,10 +1007,8 @@
},
{
"cell_type": "code",
- "execution_count": 55,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 41,
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -1056,7 +1016,7 @@
},
{
"cell_type": "code",
- "execution_count": 56,
+ "execution_count": 42,
"metadata": {},
"outputs": [
{
@@ -1065,7 +1025,7 @@
"10"
]
},
- "execution_count": 56,
+ "execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
@@ -1076,10 +1036,8 @@
},
{
"cell_type": "code",
- "execution_count": 57,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 43,
+ "metadata": {},
"outputs": [],
"source": [
"r1.width = 100"
@@ -1087,7 +1045,7 @@
},
{
"cell_type": "code",
- "execution_count": 58,
+ "execution_count": 44,
"metadata": {},
"outputs": [
{
@@ -1096,7 +1054,7 @@
"Rectangle(100, 20)"
]
},
- "execution_count": 58,
+ "execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
@@ -1125,15 +1083,13 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "In Pytyhon we can use some special **decorators** (more on those later) to encapsulate our property getters and setters:"
+ "In Python we can use some special **decorators** (more on those later) to encapsulate our property getters and setters:"
]
},
{
"cell_type": "code",
- "execution_count": 59,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 45,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -1167,10 +1123,8 @@
},
{
"cell_type": "code",
- "execution_count": 60,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 46,
+ "metadata": {},
"outputs": [],
"source": [
"r1 = Rectangle(10, 20)"
@@ -1178,7 +1132,7 @@
},
{
"cell_type": "code",
- "execution_count": 61,
+ "execution_count": 47,
"metadata": {},
"outputs": [
{
@@ -1187,7 +1141,7 @@
"10"
]
},
- "execution_count": 61,
+ "execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
@@ -1198,10 +1152,8 @@
},
{
"cell_type": "code",
- "execution_count": 62,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 48,
+ "metadata": {},
"outputs": [],
"source": [
"r1.width = 100"
@@ -1209,7 +1161,7 @@
},
{
"cell_type": "code",
- "execution_count": 63,
+ "execution_count": 49,
"metadata": {},
"outputs": [
{
@@ -1218,7 +1170,7 @@
"Rectangle(100, 20)"
]
},
- "execution_count": 63,
+ "execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
@@ -1229,7 +1181,7 @@
},
{
"cell_type": "code",
- "execution_count": 64,
+ "execution_count": 50,
"metadata": {},
"outputs": [
{
@@ -1237,11 +1189,11 @@
"evalue": "Width must be positive.",
"output_type": "error",
"traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mr1\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwidth\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[1;32m\u001b[0m in \u001b[0;36mwidth\u001b[1;34m(self, width)\u001b[0m\n\u001b[0;32m 14\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 15\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mwidth\u001b[0m \u001b[1;33m<=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 16\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Width must be positive.'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 17\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_width\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
- "\u001b[1;31mValueError\u001b[0m: Width must be positive."
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [50]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m r1\u001b[38;5;241m.\u001b[39mwidth \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m10\u001b[39m\n",
+ "Input \u001b[0;32mIn [45]\u001b[0m, in \u001b[0;36mRectangle.width\u001b[0;34m(self, width)\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[38;5;129m@width\u001b[39m\u001b[38;5;241m.\u001b[39msetter\n\u001b[1;32m 14\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mwidth\u001b[39m(\u001b[38;5;28mself\u001b[39m, width):\n\u001b[1;32m 15\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m width \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[0;32m---> 16\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mWidth must be positive.\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m 17\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_width \u001b[38;5;241m=\u001b[39m width\n",
+ "\u001b[0;31mValueError\u001b[0m: Width must be positive."
]
}
],
@@ -1258,10 +1210,8 @@
},
{
"cell_type": "code",
- "execution_count": 65,
- "metadata": {
- "collapsed": true
- },
+ "execution_count": 51,
+ "metadata": {},
"outputs": [],
"source": [
"class Rectangle:\n",
@@ -1298,7 +1248,7 @@
},
{
"cell_type": "code",
- "execution_count": 66,
+ "execution_count": 52,
"metadata": {},
"outputs": [
{
@@ -1306,12 +1256,12 @@
"evalue": "Width must be positive.",
"output_type": "error",
"traceback": [
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
- "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
- "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mr1\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mRectangle\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
- "\u001b[1;32m\u001b[0m in \u001b[0;36m__init__\u001b[1;34m(self, width, height)\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_height\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mNone\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;31m# now we call our accessor methods to set the width and height\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwidth\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mheight\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mheight\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
- "\u001b[1;32m\u001b[0m in \u001b[0;36mwidth\u001b[1;34m(self, width)\u001b[0m\n\u001b[0;32m 17\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 18\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mwidth\u001b[0m \u001b[1;33m<=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 19\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'Width must be positive.'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 20\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_width\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mwidth\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 21\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
- "\u001b[1;31mValueError\u001b[0m: Width must be positive."
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [52]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m r1 \u001b[38;5;241m=\u001b[39m \u001b[43mRectangle\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m)\u001b[49m\n",
+ "Input \u001b[0;32mIn [51]\u001b[0m, in \u001b[0;36mRectangle.__init__\u001b[0;34m(self, width, height)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_height \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 5\u001b[0m \u001b[38;5;66;03m# now we call our accessor methods to set the width and height\u001b[39;00m\n\u001b[0;32m----> 6\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mwidth \u001b[38;5;241m=\u001b[39m width\n\u001b[1;32m 7\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mheight \u001b[38;5;241m=\u001b[39m height\n",
+ "Input \u001b[0;32mIn [51]\u001b[0m, in \u001b[0;36mRectangle.width\u001b[0;34m(self, width)\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[38;5;129m@width\u001b[39m\u001b[38;5;241m.\u001b[39msetter\n\u001b[1;32m 17\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mwidth\u001b[39m(\u001b[38;5;28mself\u001b[39m, width):\n\u001b[1;32m 18\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m width \u001b[38;5;241m<\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[0;32m---> 19\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mWidth must be positive.\u001b[39m\u001b[38;5;124m'\u001b[39m)\n\u001b[1;32m 20\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_width \u001b[38;5;241m=\u001b[39m width\n",
+ "\u001b[0;31mValueError\u001b[0m: Width must be positive."
]
}
],
@@ -1323,7 +1273,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "There more we should be doing, like checking that the width and height being passed in are numeric types, and so on. Especially during the `__init__` phase - we would rather raise an exception when the object is being created rather than delay things and raise an exception when the user calls some method like `area` - that way the exception will be on the line that creates the object - makes debugging much easier!"
+ "There is more we should be doing, like checking that the width and height being passed in are numeric types, and so on. Especially during the `__init__` phase - we would rather raise an exception when the object is being created rather than delay things and raise an exception when the user calls some method like `area` - that way the exception will be on the line that creates the object - makes debugging much easier!"
]
},
{
@@ -1336,7 +1286,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -1350,7 +1300,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.6.2"
+ "version": "3.9.10"
}
},
"nbformat": 4,
diff --git a/Part 1/Section 03 - Variables and Memory/04 - Dynamic vs Static Typing.ipynb b/Part 1/Section 03 - Variables and Memory/04 - Dynamic vs Static Typing.ipynb
index d08e4055..d136bb33 100644
--- a/Part 1/Section 03 - Variables and Memory/04 - Dynamic vs Static Typing.ipynb
+++ b/Part 1/Section 03 - Variables and Memory/04 - Dynamic vs Static Typing.ipynb
@@ -11,7 +11,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Python is dunamically typed.\n",
+ "Python is dynamically typed.\n",
"\n",
"This means that the type of a variable is simply the type of the object the variable name points to (references). The variable itself has no associated type."
]
diff --git a/Part 1/Section 03 - Variables and Memory/08 - Shared References and Mutability.ipynb b/Part 1/Section 03 - Variables and Memory/08 - Shared References and Mutability.ipynb
index 3c6d16cb..ffb92fce 100644
--- a/Part 1/Section 03 - Variables and Memory/08 - Shared References and Mutability.ipynb
+++ b/Part 1/Section 03 - Variables and Memory/08 - Shared References and Mutability.ipynb
@@ -286,7 +286,7 @@
"\n",
"This is safe for Python to do because integer objects are **immutable**. \n",
"\n",
- "So, even though *a* and *b* initially shared the same mempry address, we can never modify *a*'s value by \"modifying\" *b*'s value. \n",
+ "So, even though *a* and *b* initially shared the same memory address, we can never modify *a*'s value by \"modifying\" *b*'s value. \n",
"\n",
"The only way to change *b*'s value is to change it's reference, which will never affect *a*."
]
diff --git a/Part 1/Section 04 - Numeric Types/02 - Integers - Operations.ipynb b/Part 1/Section 04 - Numeric Types/02 - Integers - Operations.ipynb
index 80713251..a973143c 100644
--- a/Part 1/Section 04 - Numeric Types/02 - Integers - Operations.ipynb
+++ b/Part 1/Section 04 - Numeric Types/02 - Integers - Operations.ipynb
@@ -13,7 +13,7 @@
"collapsed": true
},
"source": [
- "Addition, subtraction, multiplication and exponentiation of integers always result in an integer."
+ "Addition, subtraction, multiplication and exponentiation of integers always result in an integer. (In the case of exponentiation this holds only for positive integer exponents.)"
]
},
{
diff --git a/Part 1/Section 06 - First-Class Functions/03 - Lambdas and Sorting.ipynb b/Part 1/Section 06 - First-Class Functions/03 - Lambdas and Sorting.ipynb
index f60ad05a..deff2b3f 100644
--- a/Part 1/Section 06 - First-Class Functions/03 - Lambdas and Sorting.ipynb
+++ b/Part 1/Section 06 - First-Class Functions/03 - Lambdas and Sorting.ipynb
@@ -60,7 +60,7 @@
"\n",
"What if we wanted to make a case-insensitive sort?\n",
"\n",
- "Python's **sorted** function kas a keyword-only argument that allows us to modify the values that are used to sort the list."
+ "Python's **sorted** function has a keyword-only argument that allows us to modify the values that are used to sort the list."
]
},
{
diff --git a/Part 1/Section 07 - Scopes, Closures and Decorators/02 - Nonlocal Scopes.ipynb b/Part 1/Section 07 - Scopes, Closures and Decorators/02 - Nonlocal Scopes.ipynb
index e250d7fb..84ae579e 100644
--- a/Part 1/Section 07 - Scopes, Closures and Decorators/02 - Nonlocal Scopes.ipynb
+++ b/Part 1/Section 07 - Scopes, Closures and Decorators/02 - Nonlocal Scopes.ipynb
@@ -11,7 +11,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Functions defined inside anther function can reference variables from that enclosing scope, just like functions can reference variables from the global scope."
+ "Functions defined inside another function can reference variables from that enclosing scope, just like functions can reference variables from the global scope."
]
},
{
diff --git a/Part 1/Section 07 - Scopes, Closures and Decorators/03 - Closures.ipynb b/Part 1/Section 07 - Scopes, Closures and Decorators/03 - Closures.ipynb
index ce9fefa8..1ae2ffef 100644
--- a/Part 1/Section 07 - Scopes, Closures and Decorators/03 - Closures.ipynb
+++ b/Part 1/Section 07 - Scopes, Closures and Decorators/03 - Closures.ipynb
@@ -274,7 +274,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As we saw in the lecture, we can set up nonlocal variables in different inner functionsd that reference the same outer scope variable, i.e. we have a free variable that is shared between two closures. This works because both non local variables and the outer local variable all point back to the same cell object."
+ "As we saw in the lecture, we can set up nonlocal variables in different inner functions that reference the same outer scope variable, i.e. we have a free variable that is shared between two closures. This works because both non local variables and the outer local variable all point back to the same cell object."
]
},
{
diff --git a/Part 1/Section 07 - Scopes, Closures and Decorators/06 - Decorators - Part 1.ipynb b/Part 1/Section 07 - Scopes, Closures and Decorators/06 - Decorators - Part 1.ipynb
index 919c8673..1f998866 100644
--- a/Part 1/Section 07 - Scopes, Closures and Decorators/06 - Decorators - Part 1.ipynb
+++ b/Part 1/Section 07 - Scopes, Closures and Decorators/06 - Decorators - Part 1.ipynb
@@ -645,6 +645,7 @@
" nonlocal count\n",
" count += 1\n",
" print(\"{0} was called {1} times\".format(fn.__name__, count))\n",
+ " return fn(*args, **kwargs)\n",
"\n",
" return inner"
]
diff --git a/Part 1/Section 07 - Scopes, Closures and Decorators/09 - Decorator Application - Memoization.ipynb b/Part 1/Section 07 - Scopes, Closures and Decorators/09 - Decorator Application - Memoization.ipynb
index 69225a59..a5d8c00e 100644
--- a/Part 1/Section 07 - Scopes, Closures and Decorators/09 - Decorator Application - Memoization.ipynb
+++ b/Part 1/Section 07 - Scopes, Closures and Decorators/09 - Decorator Application - Memoization.ipynb
@@ -1094,7 +1094,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "You'll not how Python had to recalculate `fib` for `10, 9,` etc. This is because the cache can only contain 10 items, so when we calculated `fib(20)`, it stored fib for `20, 19, ..., 11` (10 items) and therefore the oldest items fib `10, 9, ..., 1` were removed from the cache to make space."
+ "Note how Python had to recalculate `fib` for `10, 9,` etc. This is because the cache can only contain 10 items, so when we calculated `fib(20)`, it stored fib for `20, 19, ..., 11` (10 items) and therefore the oldest items fib `10, 9, ..., 1` were removed from the cache to make space."
]
},
{
diff --git a/Part 1/Section 10 - Python. Updates/01 - Relevant Python 3.10 Changes.ipynb b/Part 1/Section 10 - Python. Updates/01 - Relevant Python 3.10 Changes.ipynb
new file mode 100644
index 00000000..1e7fa9b4
--- /dev/null
+++ b/Part 1/Section 10 - Python. Updates/01 - Relevant Python 3.10 Changes.ipynb
@@ -0,0 +1,991 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c4d4fc49",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.10 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb1495a9",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.10 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.10.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "98c3ae0d",
+ "metadata": {},
+ "source": [
+ "Python 3.10 has improved it's error messages for syntax errors - the messages are more helpful and hopefully give you a better understanding of what may be syntactically wrong with your code."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ae4aa37",
+ "metadata": {},
+ "source": [
+ "#### Structural Pattern Matching"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d18177a2",
+ "metadata": {},
+ "source": [
+ "One thing I often hear people ask, is, what's the Python equivalent of a `switch` statement."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36a77514",
+ "metadata": {},
+ "source": [
+ "Until now, the answer has alwasy been - there isn't one. Use `if...elif` constructs."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "56fdb138",
+ "metadata": {},
+ "source": [
+ "Python 3.10 introduces a new language element (`match`) to implement something called **pattern matching**, that can be used to replicate this `switch` behavior you might be used to in other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e1cf8b9d",
+ "metadata": {},
+ "source": [
+ "I'll cover some of the basics here, but you should refer to the Python [docs](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement) for more information, as well as the [pep](https://peps.python.org/pep-0634/) for this feature and a [tutorial pep](https://peps.python.org/pep-0636/)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1417630a",
+ "metadata": {},
+ "source": [
+ "Let's start with a simple `match` statement:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "bbecc554",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\":\n",
+ " return \"Hmm, coffee!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm not scared of snakes!\"\n",
+ " case \"Rust\":\n",
+ " return \"Don't drink too much water!\"\n",
+ " case \"Go\":\n",
+ " return \"Collect $200\"\n",
+ " case _:\n",
+ " return \"I'm sorry...\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d5669e92",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm not scared of snakes!\""
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "90cecc86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Collect $200'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Go\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "f9feb023",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm sorry...\""
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"COBOL\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ee7c21fb",
+ "metadata": {},
+ "source": [
+ "Here we were able to define a \"default\" match pattern by using the underscore (`_`) as our pattern - this `_` is called a **wildcard**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b76575de",
+ "metadata": {},
+ "source": [
+ "So this is very much like the \"plain\" switch statement found in some other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e55dd9f",
+ "metadata": {},
+ "source": [
+ "But, this is where things get ineteresting, pattern matching can do much more than the simple example we just saw."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f8d495f2",
+ "metadata": {},
+ "source": [
+ "For example, you can have multiple pattern matching:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "6d5fcc0c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\" | \"Javascript\":\n",
+ " return \"Love those braces!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm a lumberjack and I don't need no braces\"\n",
+ " case _:\n",
+ " return \"I have no clue!\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "02cf21af",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Java\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "853368f3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Javascript\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "066f985e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm a lumberjack and I don't need no braces\""
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7fc43e7f",
+ "metadata": {},
+ "source": [
+ "We could match against one or more literals by using the OR pattern (`|`)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36064a9c",
+ "metadata": {},
+ "source": [
+ "Let's look at one more example, this time matching **multiple values**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "31978910",
+ "metadata": {},
+ "source": [
+ "Suppose we have some kind of command language for driving a remote controlled robot in a maze, picking up and dropping items as it moves around. Our robot is very simple, it can move in only a few directions, and one step at a time. So to move forward three spaces, we would issue three `move forward` commands.\n",
+ "\n",
+ "Additional commands are `move backward`, `move left`, `move right`. We also have a few other commands our robot understands: `pick` and `drop` for picking up and dropping objects it might find."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63944ea5",
+ "metadata": {},
+ "source": [
+ "We might write a command interpreter this way:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f9077f13",
+ "metadata": {},
+ "source": [
+ "Let's start by using some symbols to represent the robot's actions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "2dde5d86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'F': '→', 'B': '←', 'L': '↑', 'R': '↓', 'pick': '⤣', 'drop': '⤥'}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "symbols = {\n",
+ " \"F\": \"\\u2192\", \n",
+ " \"B\": \"\\u2190\", \n",
+ " \"L\": \"\\u2191\", \n",
+ " \"R\": \"\\u2193\", \n",
+ " \"pick\": \"\\u2923\", \n",
+ " \"drop\": \"\\u2925\"\n",
+ "}\n",
+ "\n",
+ "symbols"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "faab4c09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case \"move F\":\n",
+ " return symbols[\"F\"]\n",
+ " case \"move B\":\n",
+ " return symbols[\"B\"]\n",
+ " case \"move L\":\n",
+ " return symbols[\"L\"]\n",
+ " case \"move R\":\n",
+ " return symbols[\"R\"]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24555fab",
+ "metadata": {},
+ "source": [
+ "Then we could issue commands such as:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b673a044",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"move L\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b411438f",
+ "metadata": {},
+ "source": [
+ "Or multiple sequences by maybe using a list of such commands, effectively creating a sequential program for our robot:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "cf94014f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['→', '→', '↑', '⤣', '↓', '↑', '→', '⤥']"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op(\"move F\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"pick\"),\n",
+ " op(\"move R\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c520053b",
+ "metadata": {},
+ "source": [
+ "We could use something called **capturing** matched sub-patterns to simply our code somewhat:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "e7da20cf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case [\"move\", (\"F\" | \"B\" | \"L\" |\"R\") as direction]:\n",
+ " return symbols[direction]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symvols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "c2a1c617",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op([\"move\", \"L\"])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4edeb3dc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'⤣'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"pick\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "b13504aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "fly does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op(\"fly\")\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6769c228",
+ "metadata": {},
+ "source": [
+ "This is kind of tedious, it would be nicer to write commands such as `move F F L` and `move R L F` instead."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "055d2c60",
+ "metadata": {},
+ "source": [
+ "There are many ways we could solve this, but pattern matching on multiple values can be really useful here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "372bdb17",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions]:\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c77bec44",
+ "metadata": {},
+ "source": [
+ "What happens here is that the pattern matcher will recognize the first word `move` and then interpret the remaining words collection them in the `directions` variable (so this syntax is very similar to unpacking)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ef78058",
+ "metadata": {},
+ "source": [
+ "We can now rewrite our program this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "88c0c024",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('→', '→', '↑'), '⤣', ('↓', '↑', '→'), '⤥']"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op([\"move\", \"F\", \"F\", \"L\"]),\n",
+ " op(\"pick\"),\n",
+ " op([\"move\", \"R\", \"L\", \"F\"]),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ddc0f2e",
+ "metadata": {},
+ "source": [
+ "But now we have a slight problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "ed30a762",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " 'up'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f6bbbd53",
+ "metadata": {},
+ "source": [
+ "We would rather just get our custom `ValueError`. To do this we can place a **guard** on our `case` for the `move` command, that will not only do the match but also test an additional condition:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8d441175",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions] if set(directions) < symbols.keys():\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "441a53f6",
+ "metadata": {},
+ "source": [
+ "That `if ` statement (the **guard**) will only let the case block execute if the match is true **and** that `if` expression evaludates to `True`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "708c5d16",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " ['move', 'up'] does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ecf5f83",
+ "metadata": {},
+ "source": [
+ "There are many other ways we could have done this - probably better than this, but this was to illustrate how the multiple value matching can work!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84bec678",
+ "metadata": {},
+ "source": [
+ "I urge you to read at least this [tutorial (pep 636)](https://peps.python.org/pep-0636/) on pattern matching."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5b6a7b09",
+ "metadata": {},
+ "source": [
+ "#### The `zip` Function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1294e5f6",
+ "metadata": {},
+ "source": [
+ "We use the built-in `zip` function all the time. As we know, the `zip` will stop iterating after the first of the iterables provided in the arguments is exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "e33aa60d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30)]"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = ['a', 'b', 'c']\n",
+ "l2 = [10, 20, 30, 40]\n",
+ "\n",
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7d310af8",
+ "metadata": {},
+ "source": [
+ "As you can see the last element of `l2` is not included in the result since `l1` only had three elements."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9cf9570",
+ "metadata": {},
+ "source": [
+ "We can also use the `zip_longest` function in the `itertools` module to iterate over the longest iterable, providing some default value for any other iterable that has been exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "aefa3055",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from itertools import zip_longest"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "ce4779c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30), ('???', 40)]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip_longest(l1, l2, fillvalue='???'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0eb2f702",
+ "metadata": {},
+ "source": [
+ "But what if we want to only zip iterables that have the **same** length? We would need to test the length of each iterable first - but if those were iterators instead of iterables, we will have exhausted the iterator, and `zip` would come back \"empty\":"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "3b704410",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da0d866f",
+ "metadata": {},
+ "source": [
+ "We could test to see if `l1` and `l2` are the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "bc7d34c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "len(list(l1)) == len(list(l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0a4a1974",
+ "metadata": {},
+ "source": [
+ "But, if we now try to `zip` them:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "1c3928b9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[]"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ee310e9",
+ "metadata": {},
+ "source": [
+ "In Python 3.10, the `zip` function now has a keyword-only parameter called `strict` that will just do the zip, but throw an exception if one of the arguments get exhausted before the others:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "54722489",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "zip() argument 2 is shorter than argument 1\n"
+ ]
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))\n",
+ "\n",
+ "try:\n",
+ " list(zip(l1, l2, strict=True))\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2635211a",
+ "metadata": {},
+ "source": [
+ "And works just fine if the arguments all have the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "7fb672cb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[(0, 0, 0), (1, 1, 1), (4, 8, 16), (9, 27, 81)]"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(4))\n",
+ "l3 = (i ** 4 for i in range(4))\n",
+ "\n",
+ "list(zip(l1, l2, l3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "501fec3b",
+ "metadata": {},
+ "source": [
+ "So why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dab4260e",
+ "metadata": {},
+ "source": [
+ "In **many** cases, our code zips iterables that we expect to be of the same length. To avoid bugs in our program, we should check that this condition is true, otherwise zip will silently just zip based on the shortest one. But as we saw with iterators, that can be difficult to do without exhausting the very iterators we are trying to zip. (it can be done, it's just more code)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c73e5ad1",
+ "metadata": {},
+ "source": [
+ "So, if you are one of the lucky devs that gets to write Python 3.10 (or higher :-) ) code, you can just use `strict` whenever you zip things together and expect that they are all of the same length. Much easier to do it this way (and, as we discuss in Exception handling, falls into the category of \"ask forgiveness later\" which we saw was the preferred way (in general) to handle exceptions in our apps, as opposed to the \"look before you leap\" approach we would have to use to test the argument lengths."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "400a56c1",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 1/Section 10 - Python. Updates/02 - Relevant Python 3.9 Changes.ipynb b/Part 1/Section 10 - Python. Updates/02 - Relevant Python 3.9 Changes.ipynb
new file mode 100644
index 00000000..698dadce
--- /dev/null
+++ b/Part 1/Section 10 - Python. Updates/02 - Relevant Python 3.9 Changes.ipynb
@@ -0,0 +1,2343 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c45f0998",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.9 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2e965eba",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.9 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.9.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "39255227",
+ "metadata": {},
+ "source": [
+ "#### Time Zones"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "26750adb",
+ "metadata": {},
+ "source": [
+ "We don't cover 3rd party libraries in this course, but if you've worked with Python in a production environment, you will likely have come across the dreaded timezone and Daylight Savings issues that plague datetimes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7cdfe8a5",
+ "metadata": {},
+ "source": [
+ "Most likely you will have resorted to using the `pytz` and `python-dateutil` libraries to help with that."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bc000883",
+ "metadata": {},
+ "source": [
+ "Now, Python 3.9 is proud to introduce the `zoneinfo` module to deal with timezones properly. About time too!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c2d652dd",
+ "metadata": {},
+ "source": [
+ "For full info on this, refer to [PEP 615](https://peps.python.org/pep-0615/).\n",
+ "\n",
+ "And the Python [docs](https://docs.python.org/3.9/library/zoneinfo.html#module-zoneinfo).\n",
+ "\n",
+ "**Windows Users**: you will likely need to add a dependency on the `tzdata` [library](https://pypi.org/project/tzdata/) for the IANA time zone database. See [this note](https://docs.python.org/3.9/library/zoneinfo.html#data-sources)\n",
+ "\n",
+ "You should also take a look at this [presentation](https://pganssle-talks.github.io/chipy-nov-2020-zoneinfo/#/) by Paul Ganssle who wrote that module - very interesting read!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "80255944",
+ "metadata": {},
+ "source": [
+ "Let's look at how we might have handled timezone and DST using `pytz` and `dateutil`, and contrast that to how we can use the new `zoneinfo` module instead."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "ec129288",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import zoneinfo\n",
+ "from datetime import datetime, timezone\n",
+ "from zoneinfo import ZoneInfo\n",
+ "\n",
+ "import dateutil\n",
+ "import pytz"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "beadc4e2",
+ "metadata": {},
+ "source": [
+ "Let's list out all the defined time zones:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d0058e73",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in pytz.all_timezones:\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f18fa2c9",
+ "metadata": {},
+ "source": [
+ "With the `zoneinfo` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "9d2cf9d1",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "Factory\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in sorted(zoneinfo.available_timezones()):\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a1887cf",
+ "metadata": {},
+ "source": [
+ "Are the time zones defined by `pytz` and `zoneinfo` the same? Yes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8f8df276",
+ "metadata": {},
+ "source": [
+ "In this example, let's take our current time in UTC, and convert it to some other time zone, say `Australia/Melbourne`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77f1b8d9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "now_utc_naive = datetime.utcnow()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "f8586215",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_naive"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a452220a",
+ "metadata": {},
+ "source": [
+ "The problem here is that we have a _naive_ datetime (i.e. one without an attached timezone)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d1d10809",
+ "metadata": {},
+ "source": [
+ "We can make this naive datetime time zone aware by tacking on the timezone (since we know it is UTC):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "db60736b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware = now_utc_naive.replace(tzinfo=timezone.utc)\n",
+ "now_utc_aware"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8282b097",
+ "metadata": {},
+ "source": [
+ "Or, we could use the `pytz` library to do the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "0d7434f7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 377626, tzinfo=)"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pytz.utc.localize(datetime.utcnow())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e613c2e1",
+ "metadata": {},
+ "source": [
+ "Now that we have a time zone aware datetime, we can convert it to another timezone using `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "94b0b5c9",
+ "metadata": {},
+ "source": [
+ "First, let's pick a time zone from `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "833b5ff9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_melbourne = pytz.timezone('Australia/Melbourne')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ce4323c1",
+ "metadata": {},
+ "source": [
+ "And now we localize our aware datetime to this time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "d23fd3c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_melbourne)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "260bd7ff",
+ "metadata": {},
+ "source": [
+ "We could do both these steps in a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "6559daf7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(pytz.timezone('Australia/Melbourne'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6be99718",
+ "metadata": {},
+ "source": [
+ "Now, let's do the same thing using the `zoneinfo` module."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8c9b22bb",
+ "metadata": {},
+ "source": [
+ "Let's pick the same target time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "30c58db3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_zi_dublin = ZoneInfo(\"Europe/Dublin\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f77b5b0",
+ "metadata": {},
+ "source": [
+ "And the let's convert our aware datetime to that time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "1623322d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_zi_dublin)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4536470f",
+ "metadata": {},
+ "source": [
+ "Or, we can also write this as a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "337c3955",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(ZoneInfo(\"Europe/Dublin\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4076195d",
+ "metadata": {},
+ "source": [
+ "#### The `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "41d86e28",
+ "metadata": {},
+ "source": [
+ "Several enhancements or additions have been to the math library."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bd3de95f",
+ "metadata": {},
+ "source": [
+ "The `math` module already had the `gcd` function to calculate the great common divisor of two numbers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "911df27e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4154629e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "9"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85abe1fa",
+ "metadata": {},
+ "source": [
+ "But now `gcd` can take multiple arguments, not just two:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "d64ea0d9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45, 18, 15)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0503d78a",
+ "metadata": {},
+ "source": [
+ "The `lcm` (least common multiple) function has been added:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "b4c25fef",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "12"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.lcm(2, 3, 4)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "58a4c3cd",
+ "metadata": {},
+ "source": [
+ "#### Dictionary Unions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2c05f130",
+ "metadata": {},
+ "source": [
+ "When we discussed dictionaries in this course, we saw that we could combine two dictionaries using unpacking:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "136c8836",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'a': 1, 'b': 2, 'c': 3}\n",
+ "d2 = {'c': 30, 'd': 40}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "81331802",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "{**d1, **d2}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "97ca030f",
+ "metadata": {},
+ "source": [
+ "As we saw the second dictionary's key/value pair \"overwrote\" the key/value pair from the first dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b361771e",
+ "metadata": {},
+ "source": [
+ "We could also use the `ChainMap` function in the `collections` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "d633f16c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import ChainMap"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "ad250dfd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "merged = ChainMap(d1, d2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "1deeb8f2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 3, 40)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "merged['a'], merged['c'], merged['d']"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1751d47a",
+ "metadata": {},
+ "source": [
+ "As you can see, in the `ChainMap`, the firest occurrence of the key is used - so in this case `c` comes from `d1`, not `d2`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1c63e893",
+ "metadata": {},
+ "source": [
+ "Both of these ways of \"combining\" dictionaries work well - but they are not very intuitive, and need a little attention to what happens when you have common keys in the dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aca5787b",
+ "metadata": {},
+ "source": [
+ "Think of concatenating lists where we can simply use the `+` operator - this is very intuitive:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "de850747",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69429bab",
+ "metadata": {},
+ "source": [
+ "Now dictionaries are not like lists, but they are closely related to **sets**. With sets, we have the **union** operator (`|`):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "dcb8a7b5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a', 'b', 'c', 'd'}"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "s1 = {'a', 'b', 'c'}\n",
+ "s2 = {'c', 'd'}\n",
+ "\n",
+ "s1 | s2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "32c20dfb",
+ "metadata": {},
+ "source": [
+ "Python 3.9 introduces support for the **union** (`|`) operation between dictionaries as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "af3fcc01",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "851ffadc",
+ "metadata": {},
+ "source": [
+ "Just like with the `{**d1, **d2}` approach, the value for `c` came from the second dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb6fc060",
+ "metadata": {},
+ "source": [
+ "And just like with that technique we can control this by switching the order of the dictionaries in the union:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "05555100",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 3, 'd': 40, 'a': 1, 'b': 2}"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d2 | d1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "739e210f",
+ "metadata": {},
+ "source": [
+ "One question we should have, is what happens to the insertion order that Python dictionaries now guarantee?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "f8759da5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'c': 3, 'a': 1, 'b': 2}\n",
+ "d2 = {'d': 40, 'c': 30}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "e06e3966",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 30, 'a': 1, 'b': 2, 'd': 40}"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8e0e1c2e",
+ "metadata": {},
+ "source": [
+ "As you can see, even though the **value** for `c` came from the **second** dictionary, the original inertion order of the **keys** is maintained, so `c` is still in first position in the union of the two dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e12dee6a",
+ "metadata": {},
+ "source": [
+ "#### String Methods"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f69f79e4",
+ "metadata": {},
+ "source": [
+ "Often we need to remove some prefix or suffix in a string."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "67496793",
+ "metadata": {},
+ "source": [
+ "For example, we may have this list of string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "9da4cabe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data = [\n",
+ " \"(log) [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "30de1de8",
+ "metadata": {},
+ "source": [
+ "And we want to clean these up and remove the `(log) ` prefix (including the space)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84a6c502",
+ "metadata": {},
+ "source": [
+ "We can certainly do it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "8a60ecdc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "45fa082e",
+ "metadata": {},
+ "source": [
+ "You might be tempted to use the `lstrip` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "74e60a43",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5e045ebc",
+ "metadata": {},
+ "source": [
+ "This appears to work, but `lstrip` (and `rstrip`) does not interpet `\"(log )\"` as a string, but rather a **sequence** of characters, and each one will be removed - so you might end up with this problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "ddc6e3a8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data2 = [\n",
+ " \"(log) log: [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) log: [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) log: [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) log: [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "d87cd3c5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[': [2022-03-01T13:30:01] Log record 1',\n",
+ " ': [2022-03-01T13:30:02] Log record 2',\n",
+ " ': [2022-03-01T13:30:03] Log record 3',\n",
+ " ': [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f73aac3",
+ "metadata": {},
+ "source": [
+ "Now that removed a lot more than expected everything from those strings, unlike the replace, which will replace only the first occurrence by default:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "eaf8792b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 34,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0aca0211",
+ "metadata": {},
+ "source": [
+ "Python 3,9 introduces two new string methods to do this without having to use `replace`, namely the `removeprefix()` and `removesuffix()` methods:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "b320eb46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "d4ebaf46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data2\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f7a2ffd4",
+ "metadata": {},
+ "source": [
+ "Note that if the prefix (or suffix) is not found, nothing happens, the new string will be the same as the original (i.e. no exception is raised):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "829cb63b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Python rocks!'"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'Python rocks!'.removeprefix('Java')"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 1/Section 10 - Python. Updates/03 - Python 3.8 - Assignment Expressions.ipynb b/Part 1/Section 10 - Python. Updates/03 - Python 3.8 - Assignment Expressions.ipynb
new file mode 100644
index 00000000..53e8b672
--- /dev/null
+++ b/Part 1/Section 10 - Python. Updates/03 - Python 3.8 - Assignment Expressions.ipynb
@@ -0,0 +1,1082 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "17ad44da",
+ "metadata": {},
+ "source": [
+ "### Python 3.8 - Assignment Expressions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "40b0045a",
+ "metadata": {},
+ "source": [
+ "Another enhancement to the Python core language that was introduced in Python 3.8 is **assignment expressions**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cad52d44",
+ "metadata": {},
+ "source": [
+ "You can see the pep for it here: [pep 572](https://peps.python.org/pep-0572/)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "285f5b11",
+ "metadata": {},
+ "source": [
+ "Remember that an expression is simply a snippet of code that is evaluated.\n",
+ "\n",
+ "The following are all examples of expressions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "357659ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "c7b05302",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "a68603b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'PYTHON'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "201b3156",
+ "metadata": {},
+ "source": [
+ "And an assignment is simply when we assign an expression result to a variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "b08e7b15",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2\n",
+ "b = [1, 2, 3] + [4, 5, 6]\n",
+ "c = \" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "54232d7a",
+ "metadata": {},
+ "source": [
+ "As you can see, we have to different steps here.\n",
+ "\n",
+ "We assign the result of an expression (the right hand side) to a variable (the left hand side) using the equals (`=`) sign."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e0ca1920",
+ "metadata": {},
+ "source": [
+ "So we have two **distinct** (totally separate) aspects here - the expression, and the assignment."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "90b2d0ab",
+ "metadata": {},
+ "source": [
+ "So what are **expression assignments**?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2065f05",
+ "metadata": {},
+ "source": [
+ "Expression assignments allows us to assign expressions to a variable **inside** an expression, using the `:=` operator (the so-called *walrus* operator)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0c400c75",
+ "metadata": {},
+ "source": [
+ "Confusing? :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "084caec6",
+ "metadata": {},
+ "source": [
+ "Let's take a look at a very simple example first:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "985d592b",
+ "metadata": {},
+ "source": [
+ "Starting with an expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "c9b56fb0",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b89a8762",
+ "metadata": {},
+ "source": [
+ "We could assign the result of that expression to some variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "225ca5f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1513437a",
+ "metadata": {},
+ "source": [
+ "But, we could also write the expression and assignment this way (not the parentheses that enclose the expression):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "572aaf6a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8d0e2885",
+ "metadata": {},
+ "source": [
+ "With the expression assignment operator, we could actually assign the result of that expression inside the expression itself:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "0fa9c199",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(x := 1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1eafbee8",
+ "metadata": {},
+ "source": [
+ "As you can see, the expression returned a result (`3`), but it also assigned that result to the variable `x`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "915d5b48",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e35a8501",
+ "metadata": {},
+ "source": [
+ "Note that the parentheses in this case are **necessary** - simply writing this would not work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "890070de",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "SyntaxError",
+ "evalue": "invalid syntax (746607632.py, line 1)",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;36m Input \u001b[0;32mIn [10]\u001b[0;36m\u001b[0m\n\u001b[0;31m x := 1 + 2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
+ ]
+ }
+ ],
+ "source": [
+ "x := 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d0b5f281",
+ "metadata": {},
+ "source": [
+ "This is because the `:=` operator must be used inside an **expression**, so we can force it by using the parentheses."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3195a0a8",
+ "metadata": {},
+ "source": [
+ "We could even do this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "6d1e232c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (x := 10 + 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "35a7ed36",
+ "metadata": {},
+ "source": [
+ "Then, `a`, and `x` are:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "96bf1532",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(30, 30)"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a, x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "638c195a",
+ "metadata": {},
+ "source": [
+ "Yeah, even more confusing! But in a minute I'll show you why this can be very useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a625536",
+ "metadata": {},
+ "source": [
+ "Before we move on to that, let's see how this assignment expression works when we deal with mutable objects such as lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "a2ee53ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (l2 := [1, 2] + [3, 4])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e58d69f",
+ "metadata": {},
+ "source": [
+ "Here, `l1` was the result of the concatenation of the two lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "2d3ae1a4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1, id(l1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "88aee44a",
+ "metadata": {},
+ "source": [
+ "But what about `l2`? It should be a list with the same values, but is it the same object reference as `l1`?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "fc8fe138",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l2, id(l2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "243f0d28",
+ "metadata": {},
+ "source": [
+ "And indeed, they are not only the same values, but the same object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e7268ec5",
+ "metadata": {},
+ "source": [
+ "Usually this is not an issue, but keep it in mind because you end up with shared references that you may not realize exist."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e27c849e",
+ "metadata": {},
+ "source": [
+ "So now, why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a57d9679",
+ "metadata": {},
+ "source": [
+ "Often, we end up writing expressions in terms of other sub expressions, not just for clarity, but sometimes to **avoid repeating** function calls or expression evaluations."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9a686538",
+ "metadata": {},
+ "source": [
+ "#### Example 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3131d1f1",
+ "metadata": {},
+ "source": [
+ "Suppose we have some long running function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "f66dd3b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import time\n",
+ "import math\n",
+ "\n",
+ "def slow_function(x, y):\n",
+ " time.sleep(0.5)\n",
+ " return round(math.sqrt(x**2 + y**2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ddce261",
+ "metadata": {},
+ "source": [
+ "Now executing this function will take about 2 seconds to run every time it is called, even when calling it with the same values (we could of course use some LRU caching, but only if the function is **deterministic** - if the function is reading data from a web site, or a database, the result for the same arguments may not be the same and so LRU caching is not even a viable option in this case).\n",
+ "\n",
+ "> A **deterministic** function is a function that for the **same** inputs, always returns the **same** result:\n",
+ ">\n",
+ "> Obviously the function we have above is deterministic, but this one would not be:\n",
+ ">```\n",
+ ">def get_price(symbol):\n",
+ "> # query an API for latest price for symbol\n",
+ "> price = ...\n",
+ "> return price\n",
+ ">``` \n",
+ "> A function that returns the current date or time, or a random number, etc are all non-deterministic functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e503d9b",
+ "metadata": {},
+ "source": [
+ "So, LRU caching is not always an option."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "05027bcc",
+ "metadata": {},
+ "source": [
+ "Let's see an example of why we would want to assign the result of our long running function to a variable, instead of just using it directly."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "a9babf8f",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "from time import perf_counter\n",
+ "\n",
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " if slow_function(i, i) % 2 == 0:\n",
+ " even_results.append(slow_function(i, i))\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3bdd4e15",
+ "metadata": {},
+ "source": [
+ "Well that was painfully slow!\n",
+ "\n",
+ "But notice that we are calling the same function, with the same arguments twice - we can eliminate that!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "19453896",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " result = slow_function(i, i)\n",
+ " if result % 2 == 0:\n",
+ " even_results.append(result)\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b6091cb",
+ "metadata": {},
+ "source": [
+ "So we are able to speed this code up, by using that interim `result` variable - also note how `result` is basically a throw away variable (we typically would not use such a variable outside the loop itself - exceptions happen of course)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8acf631f",
+ "metadata": {},
+ "source": [
+ "But notice something about that code? It's ugly looking - we are building up a list by running through a loop and adding to an initially empty list, one element at a time."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6293f28c",
+ "metadata": {},
+ "source": [
+ "We can do better! List comprehensions of course."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9cdff5a7",
+ "metadata": {},
+ "source": [
+ "But... we can't write that `result = slow_function(i, i)` in our list comprehension - so we would be back to the original (and slower) may of doing it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0d89b92d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " slow_function(i, i)\n",
+ " for i in range(10)\n",
+ " if slow_function(i, i) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8db81b84",
+ "metadata": {},
+ "source": [
+ ":-("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6c42d90a",
+ "metadata": {},
+ "source": [
+ "And this is where the assignment expression operator comes in very handy:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "eefb7ce7",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " result\n",
+ " for i in range(10)\n",
+ " if (result := slow_function(i, i)) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c1c77b0c",
+ "metadata": {},
+ "source": [
+ "Notice how using the `:=` operator, we assign the result of `slow_function(i, i)` to `result` as part of the expression itself, and then re-use that computed value for the elements of the list."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9e3744d",
+ "metadata": {},
+ "source": [
+ "You may be asking yourself, why not write it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "db2bc22b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "cd112bb8",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'result' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m result \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mresult\u001b[49m \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "\u001b[0;31mNameError\u001b[0m: name 'result' is not defined"
+ ]
+ }
+ ],
+ "source": [
+ "even_results = [\n",
+ " (result := slow_function(i, i))\n",
+ " for i in range(10)\n",
+ " if result % 2 == 0\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5c0229a0",
+ "metadata": {},
+ "source": [
+ "This happens because in a list comprehension, the loop starts running, then the `if` clause (if any) is evaluated, and then the element expression is evaluated - hence why we place the assignment expression in the `if`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cc652ad3",
+ "metadata": {},
+ "source": [
+ "**Example 2**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "093978ca",
+ "metadata": {},
+ "source": [
+ "Here's another scenario where this new operator could be quite useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "edbdc1b7",
+ "metadata": {},
+ "source": [
+ "You want to return the result of an expression but only if it satisfies some criteria.\n",
+ "\n",
+ "For example, let's say we write a generator function to produce n even random integers between 1 and 10:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "a75a9138",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import random\n",
+ "\n",
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while cnt <= n:\n",
+ " cnt += 1\n",
+ " number = random.randint(0, 10)\n",
+ " if number % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9f19d723",
+ "metadata": {},
+ "source": [
+ "We can then call the generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "53f19b5e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76ac9cf0",
+ "metadata": {},
+ "source": [
+ "We can make our code a little more concise without losing readability by using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "b849d145",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while (cnt := cnt + 1) <= n:\n",
+ " if (number := random.randint(0, 10)) % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "b847739e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5621f621",
+ "metadata": {},
+ "source": [
+ "#### Example 3"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e1719fd",
+ "metadata": {},
+ "source": [
+ "Here's another example where we are consuming some generator, until some condition is met."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9822e4d5",
+ "metadata": {},
+ "source": [
+ "Let's write a generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "623069a1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def gen():\n",
+ " while True:\n",
+ " yield list(range(random.randint(0, 10)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da617a93",
+ "metadata": {},
+ "source": [
+ "And let's print out a frew values from this generator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "56b83447",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[]\n",
+ "[0]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4, 5, 6, 7]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "for _ in range(10):\n",
+ " print(next(my_gen))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ad1bb10e",
+ "metadata": {},
+ "source": [
+ "You'll notice that the fourth element is a list with 2 values.\n",
+ "\n",
+ "What we want to do now, is process the lists yielded by the generator, until we hit a list with two values, at which point we want to stop processing it."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "25d4dab3",
+ "metadata": {},
+ "source": [
+ "We could do it this way with a `while` loop:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "f5a068ab",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while True:\n",
+ " l = next(my_gen)\n",
+ " if len(l) <= 2:\n",
+ " break\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fcf1f1a2",
+ "metadata": {},
+ "source": [
+ "Instead, we could re-write this way using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "7568cf9c",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while len(l := next(my_gen)) > 2:\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d9f1b587",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 1/Section 10 - Python. Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb b/Part 1/Section 10 - Python. Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
new file mode 100644
index 00000000..699f8626
--- /dev/null
+++ b/Part 1/Section 10 - Python. Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
@@ -0,0 +1,1476 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c314393b",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.8 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cbe45497",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.8 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.8.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7089277d",
+ "metadata": {},
+ "source": [
+ "#### Positional Only Parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "61154c87",
+ "metadata": {},
+ "source": [
+ "It is now possible to define **positional-only** parameters for Python functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63037bda",
+ "metadata": {},
+ "source": [
+ "As we saw earlier in this course, when you define positional parameters in a function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "13c1ba59",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4928079",
+ "metadata": {},
+ "source": [
+ "the user is free to pass arguments either positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "0bb6fea5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "be1cfa90",
+ "metadata": {},
+ "source": [
+ "or, as named arguments:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "cb04e54f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(b=2, a=1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "617077dd",
+ "metadata": {},
+ "source": [
+ "Some functions in Python's built-ins ared defined in such a way that certain parameters can **only** be passed positionally, for example the `print` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77c6fa8a",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on built-in function print in module builtins:\n",
+ "\n",
+ "print(...)\n",
+ " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
+ " \n",
+ " Prints the values to a stream, or to sys.stdout by default.\n",
+ " Optional keyword arguments:\n",
+ " file: a file-like object (stream); defaults to the current sys.stdout.\n",
+ " sep: string inserted between values, default a space.\n",
+ " end: string appended after the last value, default a newline.\n",
+ " flush: whether to forcibly flush the stream.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(print)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "248c2581",
+ "metadata": {},
+ "source": [
+ "That `value` cannot be passed by name:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "529c5dac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "'value' is an invalid keyword argument for print()\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(value=\"hello\")\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f4baed67",
+ "metadata": {},
+ "source": [
+ "Instead, the parameter **must** be passed positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "8c147557",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2840374",
+ "metadata": {},
+ "source": [
+ "Until Python 3.8, it was not possible to reproduce such behavior with user-defined functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "158674a9",
+ "metadata": {},
+ "source": [
+ "Now you can, by using the slash character(`/`). Parameters defined **before** the `/` become **positional-only** parameters:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "aeebd0f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "858727b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "4f73c741",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "my_func() got some positional-only arguments passed as keyword arguments: 'a, b'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " my_func(a=1, b=2)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f5967700",
+ "metadata": {},
+ "source": [
+ "You can of course mix this along with the special parameters `*` and `**`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "d17254b3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /, *, c):\n",
+ " print(a + b + c)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b35d884e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "13\n"
+ ]
+ }
+ ],
+ "source": [
+ "my_func(1, 2, c=10)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "573aca30",
+ "metadata": {},
+ "source": [
+ "#### f-string Enhancements"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "89ee51f9",
+ "metadata": {},
+ "source": [
+ "Often we use f-strings to interpolate the name of a variable and it's value:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "f79a630b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "a, b = \"hello\", \"world\"\n",
+ "print(f\"a={a}, b={b}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24747607",
+ "metadata": {},
+ "source": [
+ "Python 3.8 provides a shortcut way of doing the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "3ae5c0c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a='hello', b='world'\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=}, {b=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "141558b4",
+ "metadata": {},
+ "source": [
+ "You can even use [format specifiers](https://docs.python.org/3/library/string.html#formatspec)\n",
+ "to further customize the output:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "e75716ac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=:s}, {b=:s}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4dcdc5d0",
+ "metadata": {},
+ "source": [
+ "Or when dealing with other types:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "362bf6b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime\n",
+ "from math import pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "c91b7536",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = datetime.utcnow()\n",
+ "e = pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "545c77a2",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=datetime.datetime(2022, 3, 20, 6, 1, 13, 990493), e=3.141592653589793\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=}, {e=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4637ecd5",
+ "metadata": {},
+ "source": [
+ "And applying some format specifiers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "75c4052b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=2022-03-20 06:01:13, e=3.142\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=:%Y-%m-%d %H:%M:%S}, {e=:.3f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "076773ed",
+ "metadata": {},
+ "source": [
+ "It will even display the text of an expression if you use one in your f-string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0ce46ace",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1 + 2=3, ' '.join(sentence)='Python rocks!'\n"
+ ]
+ }
+ ],
+ "source": [
+ "sentence = [\"Python\", \"rocks!\"]\n",
+ "print(f\"{1 + 2=}, {' '.join(sentence)=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e3783ea",
+ "metadata": {},
+ "source": [
+ "#### The `as_integer_ratio()` Method"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "15ccd5ad",
+ "metadata": {},
+ "source": [
+ "The types `bool`, `int` and `Fraction` now all implement an `as_integer_ratio()` method which returns a tuple consisting of the numerator and denominator. Remember that `Decimal` and `float` already implement the same method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8313fc80",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from fractions import Fraction"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "7a1ae84a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "f = Fraction(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "a94fc3ed",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(2, 3)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "f.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "f32942ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(12, 1)"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 12\n",
+ "a.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "06980a8c",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 1)"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "flag = True\n",
+ "flag.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a3091e0e",
+ "metadata": {},
+ "source": [
+ "The advantage of this is mainly for polymorphism (or duck-typing), where you can now use `as_integer_ratio` irrespective of whether the variable is a `bool`, an `int`, a `float`, a `Decimal` or a `Fraction`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "8a362bf8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from decimal import Decimal"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "ab4a78aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(33, 100)"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Decimal(\"0.33\").as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "5ee29a47",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(7070651414971679, 2251799813685248)"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(3.14).as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "df1e85de",
+ "metadata": {},
+ "source": [
+ "#### The `lru_cache` decorator"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "226efb47",
+ "metadata": {},
+ "source": [
+ "As we saw in this course, we can use the `lru_cache` decorator to appky an LRU cache to our functions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "20501526",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import lru_cache"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "07d699f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache(maxsize=3)\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "45a0cd5a",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fea747d4",
+ "metadata": {},
+ "source": [
+ "If we don't specify `maxsize`, it will default to `128`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "447be276",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache()\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "53fee4fd",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5cf8e33a",
+ "metadata": {},
+ "source": [
+ "The change made to this decorator in Python 3.8 allows us not to use those empty parentheses:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "4185658b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76a9aed5",
+ "metadata": {},
+ "source": [
+ "#### `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0af410c0",
+ "metadata": {},
+ "source": [
+ "Many examples I use throughout this course calculate the Euclidean distance between two points:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "b511addc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "0b66c006",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1.4142135623730951\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = (0, 0)\n",
+ "b = (1, 1)\n",
+ "\n",
+ "dist = math.sqrt((b[0] - a[1]) ** 2 + (b[1] - a[1]) ** 2)\n",
+ "print(dist)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d276589d",
+ "metadata": {},
+ "source": [
+ "Now, it's much easier using the `dist()` function the `math` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "1f774757",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1.4142135623730951"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.dist(a, b)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "13afb1f1",
+ "metadata": {},
+ "source": [
+ "#### The `namedtuple` Implementation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a22a839e",
+ "metadata": {},
+ "source": [
+ "Actually these changes were added to Python 3.7, but since I don't have a separate lecture for Python 3.7 changes (most did not apply to this course), here it is."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1a579fbb",
+ "metadata": {},
+ "source": [
+ "The `_source` attribute was **removed**. There quite a discussion on this, and the the core dev who implemented and supported this essentially gave up trying to keep this in - it was deemed to cause too much \"overhead\". So, sadly (wearing my teacher's hat), it is gone. It is no more. It's not pining, it's just dead. :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d5e3bfd0",
+ "metadata": {},
+ "source": [
+ "The method I showed you for defining defaults for named tuples still works, and could still be used, but Python 3.7 added the `defaults` parameter to the named tuple definition."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "3538a2c2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import namedtuple"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "id": "024bcc51",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults=(10, 20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "id": "9dd8a877",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "id": "db7f47e7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 40,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fb0bc811",
+ "metadata": {},
+ "source": [
+ "You don't have to specify defaults for everything, but if you do not, be aware that defaults will be applied from **right** to **left**. Which makes sense given that in Python non-defaulted parameters must be defined **before** defaulted parameters."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "id": "8f6ad2ca",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = (20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "id": "bc9d5345",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "id": "eceeaec2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "64188b1c",
+ "metadata": {},
+ "source": [
+ "Note that with this way of specifying defaults you can easily define the same default for all items in the named tuple using the `*` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "id": "8b36d7c3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c d e f\", defaults=(\"xyz\",) * 6)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "id": "1d448806",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "id": "b16758de",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a='xyz', b='xyz', c='xyz', d='xyz', e='xyz', f='xyz')"
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bbcbaf53",
+ "metadata": {},
+ "source": [
+ "Just be careful if you use a **mutable** type to do this!!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "id": "91b28470",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = ([],) * 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "id": "cad11f5c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "id": "0cb7ceac",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[], b=[], c=[])"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "id": "466d9520",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt.a.append(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "id": "74826099",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[10]"
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt.a"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6d00b122",
+ "metadata": {},
+ "source": [
+ "But watch this!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "id": "4759e6f4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[10], b=[10], c=[10])"
+ ]
+ },
+ "execution_count": 52,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "972c666e",
+ "metadata": {},
+ "source": [
+ "I hope you understand what happened here without me telling you!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6590d73a",
+ "metadata": {},
+ "source": [
+ "The **same** list object was re-used 3 times in the defaults."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "720e13bb",
+ "metadata": {},
+ "source": [
+ "You can easily recover your defaults using the `_field_defaults` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "id": "586498ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a, b, c\", defaults=(1, 2, 3))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "id": "20f4012e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 3}"
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "NT._field_defaults"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70c3a717",
+ "metadata": {},
+ "source": [
+ "One change of note in Python 3.8, the `_as_dict()` method now returns a standard dictionary (key ordered in the same way as the named tuple). Prior to this version, it would return an `OrderedDict` since standard Python dictionaries did not guarantee any specific key order, but since they now do, there's no need to use the `DefaultDict` anymore."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ecb5b3a0",
+ "metadata": {},
+ "source": [
+ "#### Other Things"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9d8ec24b",
+ "metadata": {},
+ "source": [
+ "These are few other odds and ends that you might find of interest:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3602bbab",
+ "metadata": {},
+ "source": [
+ "The built-in `reversed` function now works with dictionary views:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "id": "4f68e46b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = {'a': 1, 'b': 2}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "id": "83fc356d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['a', 'b']"
+ ]
+ },
+ "execution_count": 56,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(d.keys())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "id": "10648abb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['b', 'a']"
+ ]
+ },
+ "execution_count": 57,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.keys()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "id": "4a4885c3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[2, 1]"
+ ]
+ },
+ "execution_count": 58,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.values()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 59,
+ "id": "13785eb9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('b', 2), ('a', 1)]"
+ ]
+ },
+ "execution_count": 59,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.items()))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e14d5c14",
+ "metadata": {},
+ "source": [
+ "The `continue` statement was not permitted in the `finally` clause of a loop, but is now supported."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fe507127",
+ "metadata": {},
+ "source": [
+ "Earlier in Part 1, we discussed string interning, as well as how a small selection of integers are essentially \"cached\" by Python and re-used whenever the literal is encountered. This meant we could use `is` instead of `==` in some cases, and that helped us get a clearer understanding of what's going on. **BUT**, as we also discussed, you should **not**, in practice, use `is` for comparing objects such as integers, strings, etc (usually we are more interested in whether is the same value, rather than the identical object) - the fact that this works is an implementation detail and not guaranteed to work the same way from one Python version to another.\n",
+ "\n",
+ "Although linters will usually catch those kinds of issues, not everyone uses a Python linter - so Python 3.8 will now emit a **warning** if you compare variables of certain types with literal constants!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 60,
+ "id": "e659956e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/3780910533.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 1\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 60,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 1\n",
+ "a is 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 61,
+ "id": "d970904d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/4272392880.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 'hello'\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 61,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 'hello'\n",
+ "a is 'hello'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "01c01a49",
+ "metadata": {},
+ "source": [
+ "But we do not get a warning in a situation such as this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 62,
+ "id": "c0d535bc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 62,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = [1, 2, 3]\n",
+ "\n",
+ "a is [1, 2, 3]"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 1/Section 10 - Extras/01 - Python 3.6 Highlights.ipynb b/Part 1/Section 10 - Python. Updates/05 - Python 3.6 Highlights.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/01 - Python 3.6 Highlights.ipynb
rename to Part 1/Section 10 - Python. Updates/05 - Python 3.6 Highlights.ipynb
diff --git a/Part 1/Section 10 - Extras/02 - Python 3.6 - Dictionary Ordering.ipynb b/Part 1/Section 10 - Python. Updates/06 - Python 3.6 - Dictionary Ordering.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/02 - Python 3.6 - Dictionary Ordering.ipynb
rename to Part 1/Section 10 - Python. Updates/06 - Python 3.6 - Dictionary Ordering.ipynb
diff --git a/Part 1/Section 10 - Extras/03 - Python 3.6 - Preserved Order of kwargs - Named Tuple Application.ipynb b/Part 1/Section 10 - Python. Updates/07 - Python 3.6 - Preserved Order of kwargs - Named Tuple Application.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/03 - Python 3.6 - Preserved Order of kwargs - Named Tuple Application.ipynb
rename to Part 1/Section 10 - Python. Updates/07 - Python 3.6 - Preserved Order of kwargs - Named Tuple Application.ipynb
diff --git a/Part 1/Section 10 - Extras/04 - Python 3.6 - Underscores and Numeric Literals.ipynb b/Part 1/Section 10 - Python. Updates/08 - Python 3.6 - Underscores and Numeric Literals.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/04 - Python 3.6 - Underscores and Numeric Literals.ipynb
rename to Part 1/Section 10 - Python. Updates/08 - Python 3.6 - Underscores and Numeric Literals.ipynb
diff --git a/Part 1/Section 10 - Extras/05 - Python 3.6 - f-Strings.ipynb b/Part 1/Section 10 - Python. Updates/09 - Python 3.6 - f-Strings.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/05 - Python 3.6 - f-Strings.ipynb
rename to Part 1/Section 10 - Python. Updates/09 - Python 3.6 - f-Strings.ipynb
diff --git a/Part 1/Section 10 - Extras/06 - Random Seeds.ipynb b/Part 1/Section 11 - Extras/09 - Random Seeds.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/06 - Random Seeds.ipynb
rename to Part 1/Section 11 - Extras/09 - Random Seeds.ipynb
diff --git a/Part 1/Section 10 - Extras/07 - Random Choices.ipynb b/Part 1/Section 11 - Extras/10 - Random Choices.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/07 - Random Choices.ipynb
rename to Part 1/Section 11 - Extras/10 - Random Choices.ipynb
diff --git a/Part 1/Section 10 - Extras/08 - Random Samples.ipynb b/Part 1/Section 11 - Extras/11 - Random Samples.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/08 - Random Samples.ipynb
rename to Part 1/Section 11 - Extras/11 - Random Samples.ipynb
diff --git a/Part 1/Section 10 - Extras/09 - Timing code using timeit.ipynb b/Part 1/Section 11 - Extras/12 - Timing code using timeit.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/09 - Timing code using timeit.ipynb
rename to Part 1/Section 11 - Extras/12 - Timing code using timeit.ipynb
diff --git a/Part 1/Section 10 - Extras/10 - Don't Use args and kwargs Names Blindly.ipynb b/Part 1/Section 11 - Extras/13 - Don't Use args and kwargs Names Blindly.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/10 - Don't Use args and kwargs Names Blindly.ipynb
rename to Part 1/Section 11 - Extras/13 - Don't Use args and kwargs Names Blindly.ipynb
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example1.py b/Part 1/Section 11 - Extras/14 -command line arguments/example1.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example1.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example1.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example10.py b/Part 1/Section 11 - Extras/14 -command line arguments/example10.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example10.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example10.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example2.py b/Part 1/Section 11 - Extras/14 -command line arguments/example2.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example2.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example2.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example3.py b/Part 1/Section 11 - Extras/14 -command line arguments/example3.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example3.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example3.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example4.py b/Part 1/Section 11 - Extras/14 -command line arguments/example4.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example4.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example4.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example5.py b/Part 1/Section 11 - Extras/14 -command line arguments/example5.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example5.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example5.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example6.py b/Part 1/Section 11 - Extras/14 -command line arguments/example6.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example6.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example6.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example7.py b/Part 1/Section 11 - Extras/14 -command line arguments/example7.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example7.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example7.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example8.py b/Part 1/Section 11 - Extras/14 -command line arguments/example8.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example8.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example8.py
diff --git a/Part 1/Section 10 - Extras/11 -command line arguments/example9.py b/Part 1/Section 11 - Extras/14 -command line arguments/example9.py
similarity index 100%
rename from Part 1/Section 10 - Extras/11 -command line arguments/example9.py
rename to Part 1/Section 11 - Extras/14 -command line arguments/example9.py
diff --git a/Part 1/Section 10 - Extras/12 - Sentinel Values for Parameter Defaults.ipynb b/Part 1/Section 11 - Extras/15 - Sentinel Values for Parameter Defaults.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/12 - Sentinel Values for Parameter Defaults.ipynb
rename to Part 1/Section 11 - Extras/15 - Sentinel Values for Parameter Defaults.ipynb
diff --git a/Part 1/Section 10 - Extras/13 - Simulating a simple Switch in Python.ipynb b/Part 1/Section 11 - Extras/16 - Simulating a simple Switch in Python.ipynb
similarity index 100%
rename from Part 1/Section 10 - Extras/13 - Simulating a simple Switch in Python.ipynb
rename to Part 1/Section 11 - Extras/16 - Simulating a simple Switch in Python.ipynb
diff --git a/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators as Function Arguments.ipynb b/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators as Function Arguments.ipynb
new file mode 100644
index 00000000..7035375c
--- /dev/null
+++ b/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators as Function Arguments.ipynb
@@ -0,0 +1,2623 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Caveat of Using Iterators as Function Arguments"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When a function requires an iterable for one of its arguments, it will also work with any iterator (since iterators are themselves iterables).\n",
+ "\n",
+ "But things can go wrong if you do that!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's say we have an iterator that returns a collection of random numbers, and we want, for each such collection, find the minimum amd maximum value:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "import random"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "class Randoms:\n",
+ " def __init__(self, n):\n",
+ " self.n = n\n",
+ " self.i = 0\n",
+ " \n",
+ " def __iter__(self):\n",
+ " return self\n",
+ " \n",
+ " def __next__(self):\n",
+ " if self.i >= self.n:\n",
+ " raise StopIteration\n",
+ " else:\n",
+ " self.i += 1\n",
+ " return random.randint(0, 100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[49, 97, 53, 5, 33, 65, 62, 51, 100, 38]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(0)\n",
+ "l = list(Randoms(10))\n",
+ "print(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we can easily find the min and max values:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(5, 100)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "min(l), max(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But watch what happens if we do this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "random.seed(0)\n",
+ "l = Randoms(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "5"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "min(l)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "ValueError",
+ "evalue": "max() arg is an empty sequence",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
+ "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmax\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
+ "\u001b[1;31mValueError\u001b[0m: max() arg is an empty sequence"
+ ]
+ }
+ ],
+ "source": [
+ "max(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That's because when `min` ran, it iterated over the **iterator** `Randoms(10)`. When we called `max` on the same iterator, it had already been exhausted - i.e. the argument to max was now empty!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, be really careful when using iterators!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's another more practical example.\n",
+ "\n",
+ "Let's go back to our `cars.csv` data file and write some code that will return the car names and MPG - except we also want to return a value indicating the percentage of the car's MPG to the least fuel efficient car in the list.\n",
+ "\n",
+ "To do so we will need to iterate over the file twice - once to figure out the largest MPG value, and another time to make the calculation MPG/min_mpg * 100."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's just quickly see what our file looks like:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Car;MPG;Cylinders;Displacement;Horsepower;Weight;Acceleration;Model;Origin\n",
+ "STRING;DOUBLE;INT;DOUBLE;DOUBLE;DOUBLE;DOUBLE;INT;CAT\n",
+ "Chevrolet Chevelle Malibu;18.0;8;307.0;130.0;3504.;12.0;70;US\n",
+ "Buick Skylark 320;15.0;8;350.0;165.0;3693.;11.5;70;US\n",
+ "Plymouth Satellite;18.0;8;318.0;150.0;3436.;11.0;70;US\n",
+ "AMC Rebel SST;16.0;8;304.0;150.0;3433.;12.0;70;US\n",
+ "Ford Torino;17.0;8;302.0;140.0;3449.;10.5;70;US\n",
+ "Ford Galaxie 500;15.0;8;429.0;198.0;4341.;10.0;70;US\n",
+ "Chevrolet Impala;14.0;8;454.0;220.0;4354.;9.0;70;US\n",
+ "Plymouth Fury iii;14.0;8;440.0;215.0;4312.;8.5;70;US\n",
+ "Pontiac Catalina;14.0;8;455.0;225.0;4425.;10.0;70;US\n",
+ "AMC Ambassador DPL;15.0;8;390.0;190.0;3850.;8.5;70;US\n",
+ "Citroen DS-21 Pallas;0;4;133.0;115.0;3090.;17.5;70;Europe\n",
+ "Chevrolet Chevelle Concours (sw);0;8;350.0;165.0;4142.;11.5;70;US\n",
+ "Ford Torino (sw);0;8;351.0;153.0;4034.;11.0;70;US\n",
+ "Plymouth Satellite (sw);0;8;383.0;175.0;4166.;10.5;70;US\n",
+ "AMC Rebel SST (sw);0;8;360.0;175.0;3850.;11.0;70;US\n",
+ "Dodge Challenger SE;15.0;8;383.0;170.0;3563.;10.0;70;US\n",
+ "Plymouth 'Cuda 340;14.0;8;340.0;160.0;3609.;8.0;70;US\n",
+ "Ford Mustang Boss 302;0;8;302.0;140.0;3353.;8.0;70;US\n",
+ "Chevrolet Monte Carlo;15.0;8;400.0;150.0;3761.;9.5;70;US\n",
+ "Buick Estate Wagon (sw);14.0;8;455.0;225.0;3086.;10.0;70;US\n",
+ "Toyota Corolla Mark ii;24.0;4;113.0;95.00;2372.;15.0;70;Japan\n",
+ "Plymouth Duster;22.0;6;198.0;95.00;2833.;15.5;70;US\n",
+ "AMC Hornet;18.0;6;199.0;97.00;2774.;15.5;70;US\n",
+ "Ford Maverick;21.0;6;200.0;85.00;2587.;16.0;70;US\n",
+ "Datsun PL510;27.0;4;97.00;88.00;2130.;14.5;70;Japan\n",
+ "Volkswagen 1131 Deluxe Sedan;26.0;4;97.00;46.00;1835.;20.5;70;Europe\n",
+ "Peugeot 504;25.0;4;110.0;87.00;2672.;17.5;70;Europe\n",
+ "Audi 100 LS;24.0;4;107.0;90.00;2430.;14.5;70;Europe\n",
+ "Saab 99e;25.0;4;104.0;95.00;2375.;17.5;70;Europe\n",
+ "BMW 2002;26.0;4;121.0;113.0;2234.;12.5;70;Europe\n",
+ "AMC Gremlin;21.0;6;199.0;90.00;2648.;15.0;70;US\n",
+ "Ford F250;10.0;8;360.0;215.0;4615.;14.0;70;US\n",
+ "Chevy C20;10.0;8;307.0;200.0;4376.;15.0;70;US\n",
+ "Dodge D200;11.0;8;318.0;210.0;4382.;13.5;70;US\n",
+ "Hi 1200D;9.0;8;304.0;193.0;4732.;18.5;70;US\n",
+ "Datsun PL510;27.0;4;97.00;88.00;2130.;14.5;71;Japan\n",
+ "Chevrolet Vega 2300;28.0;4;140.0;90.00;2264.;15.5;71;US\n",
+ "Toyota Corolla;25.0;4;113.0;95.00;2228.;14.0;71;Japan\n",
+ "Ford Pinto;25.0;4;98.00;0;2046.;19.0;71;US\n",
+ "Volkswagen Super Beetle 117;0;4;97.00;48.00;1978.;20.0;71;Europe\n",
+ "AMC Gremlin;19.0;6;232.0;100.0;2634.;13.0;71;US\n",
+ "Plymouth Satellite Custom;16.0;6;225.0;105.0;3439.;15.5;71;US\n",
+ "Chevrolet Chevelle Malibu;17.0;6;250.0;100.0;3329.;15.5;71;US\n",
+ "Ford Torino 500;19.0;6;250.0;88.00;3302.;15.5;71;US\n",
+ "AMC Matador;18.0;6;232.0;100.0;3288.;15.5;71;US\n",
+ "Chevrolet Impala;14.0;8;350.0;165.0;4209.;12.0;71;US\n",
+ "Pontiac Catalina Brougham;14.0;8;400.0;175.0;4464.;11.5;71;US\n",
+ "Ford Galaxie 500;14.0;8;351.0;153.0;4154.;13.5;71;US\n",
+ "Plymouth Fury iii;14.0;8;318.0;150.0;4096.;13.0;71;US\n",
+ "Dodge Monaco (sw);12.0;8;383.0;180.0;4955.;11.5;71;US\n",
+ "Ford Country Squire (sw);13.0;8;400.0;170.0;4746.;12.0;71;US\n",
+ "Pontiac Safari (sw);13.0;8;400.0;175.0;5140.;12.0;71;US\n",
+ "AMC Hornet Sportabout (sw);18.0;6;258.0;110.0;2962.;13.5;71;US\n",
+ "Chevrolet Vega (sw);22.0;4;140.0;72.00;2408.;19.0;71;US\n",
+ "Pontiac Firebird;19.0;6;250.0;100.0;3282.;15.0;71;US\n",
+ "Ford Mustang;18.0;6;250.0;88.00;3139.;14.5;71;US\n",
+ "Mercury Capri 2000;23.0;4;122.0;86.00;2220.;14.0;71;US\n",
+ "Opel 1900;28.0;4;116.0;90.00;2123.;14.0;71;Europe\n",
+ "Peugeot 304;30.0;4;79.00;70.00;2074.;19.5;71;Europe\n",
+ "Fiat 124B;30.0;4;88.00;76.00;2065.;14.5;71;Europe\n",
+ "Toyota Corolla 1200;31.0;4;71.00;65.00;1773.;19.0;71;Japan\n",
+ "Datsun 1200;35.0;4;72.00;69.00;1613.;18.0;71;Japan\n",
+ "Volkswagen Model 111;27.0;4;97.00;60.00;1834.;19.0;71;Europe\n",
+ "Plymouth Cricket;26.0;4;91.00;70.00;1955.;20.5;71;US\n",
+ "Toyota Corolla Hardtop;24.0;4;113.0;95.00;2278.;15.5;72;Japan\n",
+ "Dodge Colt Hardtop;25.0;4;97.50;80.00;2126.;17.0;72;US\n",
+ "Volkswagen Type 3;23.0;4;97.00;54.00;2254.;23.5;72;Europe\n",
+ "Chevrolet Vega;20.0;4;140.0;90.00;2408.;19.5;72;US\n",
+ "Ford Pinto Runabout;21.0;4;122.0;86.00;2226.;16.5;72;US\n",
+ "Chevrolet Impala;13.0;8;350.0;165.0;4274.;12.0;72;US\n",
+ "Pontiac Catalina;14.0;8;400.0;175.0;4385.;12.0;72;US\n",
+ "Plymouth Fury III;15.0;8;318.0;150.0;4135.;13.5;72;US\n",
+ "Ford Galaxie 500;14.0;8;351.0;153.0;4129.;13.0;72;US\n",
+ "AMC Ambassador SST;17.0;8;304.0;150.0;3672.;11.5;72;US\n",
+ "Mercury Marquis;11.0;8;429.0;208.0;4633.;11.0;72;US\n",
+ "Buick LeSabre Custom;13.0;8;350.0;155.0;4502.;13.5;72;US\n",
+ "Oldsmobile Delta 88 Royale;12.0;8;350.0;160.0;4456.;13.5;72;US\n",
+ "Chrysler Newport Royal;13.0;8;400.0;190.0;4422.;12.5;72;US\n",
+ "Mazda RX2 Coupe;19.0;3;70.00;97.00;2330.;13.5;72;Japan\n",
+ "AMC Matador (sw);15.0;8;304.0;150.0;3892.;12.5;72;US\n",
+ "Chevrolet Chevelle Concours (sw);13.0;8;307.0;130.0;4098.;14.0;72;US\n",
+ "Ford Gran Torino (sw);13.0;8;302.0;140.0;4294.;16.0;72;US\n",
+ "Plymouth Satellite Custom (sw);14.0;8;318.0;150.0;4077.;14.0;72;US\n",
+ "Volvo 145e (sw);18.0;4;121.0;112.0;2933.;14.5;72;Europe\n",
+ "Volkswagen 411 (sw);22.0;4;121.0;76.00;2511.;18.0;72;Europe\n",
+ "Peugeot 504 (sw);21.0;4;120.0;87.00;2979.;19.5;72;Europe\n",
+ "Renault 12 (sw);26.0;4;96.00;69.00;2189.;18.0;72;Europe\n",
+ "Ford Pinto (sw);22.0;4;122.0;86.00;2395.;16.0;72;US\n",
+ "Datsun 510 (sw);28.0;4;97.00;92.00;2288.;17.0;72;Japan\n",
+ "Toyota Corolla Mark II (sw);23.0;4;120.0;97.00;2506.;14.5;72;Japan\n",
+ "Dodge Colt (sw);28.0;4;98.00;80.00;2164.;15.0;72;US\n",
+ "Toyota Corolla 1600 (sw);27.0;4;97.00;88.00;2100.;16.5;72;Japan\n",
+ "Buick Century 350;13.0;8;350.0;175.0;4100.;13.0;73;US\n",
+ "AMC Matador;14.0;8;304.0;150.0;3672.;11.5;73;US\n",
+ "Chevrolet Malibu;13.0;8;350.0;145.0;3988.;13.0;73;US\n",
+ "Ford Gran Torino;14.0;8;302.0;137.0;4042.;14.5;73;US\n",
+ "Dodge Coronet Custom;15.0;8;318.0;150.0;3777.;12.5;73;US\n",
+ "Mercury Marquis Brougham;12.0;8;429.0;198.0;4952.;11.5;73;US\n",
+ "Chevrolet Caprice Classic;13.0;8;400.0;150.0;4464.;12.0;73;US\n",
+ "Ford LTD;13.0;8;351.0;158.0;4363.;13.0;73;US\n",
+ "Plymouth Fury Gran Sedan;14.0;8;318.0;150.0;4237.;14.5;73;US\n",
+ "Chrysler New Yorker Brougham;13.0;8;440.0;215.0;4735.;11.0;73;US\n",
+ "Buick Electra 225 Custom;12.0;8;455.0;225.0;4951.;11.0;73;US\n",
+ "AMC Ambassador Brougham;13.0;8;360.0;175.0;3821.;11.0;73;US\n",
+ "Plymouth Valiant;18.0;6;225.0;105.0;3121.;16.5;73;US\n",
+ "Chevrolet Nova Custom;16.0;6;250.0;100.0;3278.;18.0;73;US\n",
+ "AMC Hornet;18.0;6;232.0;100.0;2945.;16.0;73;US\n",
+ "Ford Maverick;18.0;6;250.0;88.00;3021.;16.5;73;US\n",
+ "Plymouth Duster;23.0;6;198.0;95.00;2904.;16.0;73;US\n",
+ "Volkswagen Super Beetle;26.0;4;97.00;46.00;1950.;21.0;73;Europe\n",
+ "Chevrolet Impala;11.0;8;400.0;150.0;4997.;14.0;73;US\n",
+ "Ford Country;12.0;8;400.0;167.0;4906.;12.5;73;US\n",
+ "Plymouth Custom Suburb;13.0;8;360.0;170.0;4654.;13.0;73;US\n",
+ "Oldsmobile Vista Cruiser;12.0;8;350.0;180.0;4499.;12.5;73;US\n",
+ "AMC Gremlin;18.0;6;232.0;100.0;2789.;15.0;73;US\n",
+ "Toyota Camry;20.0;4;97.00;88.00;2279.;19.0;73;Japan\n",
+ "Chevrolet Vega;21.0;4;140.0;72.00;2401.;19.5;73;US\n",
+ "Datsun 610;22.0;4;108.0;94.00;2379.;16.5;73;Japan\n",
+ "Mazda RX3;18.0;3;70.00;90.00;2124.;13.5;73;Japan\n",
+ "Ford Pinto;19.0;4;122.0;85.00;2310.;18.5;73;US\n",
+ "Mercury Capri v6;21.0;6;155.0;107.0;2472.;14.0;73;US\n",
+ "Fiat 124 Sport Coupe;26.0;4;98.00;90.00;2265.;15.5;73;Europe\n",
+ "Chevrolet Monte Carlo S;15.0;8;350.0;145.0;4082.;13.0;73;US\n",
+ "Pontiac Grand Prix;16.0;8;400.0;230.0;4278.;9.50;73;US\n",
+ "Fiat 128;29.0;4;68.00;49.00;1867.;19.5;73;Europe\n",
+ "Opel Manta;24.0;4;116.0;75.00;2158.;15.5;73;Europe\n",
+ "Audi 100LS;20.0;4;114.0;91.00;2582.;14.0;73;Europe\n",
+ "Volvo 144ea;19.0;4;121.0;112.0;2868.;15.5;73;Europe\n",
+ "Dodge Dart Custom;15.0;8;318.0;150.0;3399.;11.0;73;US\n",
+ "Saab 99le;24.0;4;121.0;110.0;2660.;14.0;73;Europe\n",
+ "Toyota Mark II;20.0;6;156.0;122.0;2807.;13.5;73;Japan\n",
+ "Oldsmobile Omega;11.0;8;350.0;180.0;3664.;11.0;73;US\n",
+ "Plymouth Duster;20.0;6;198.0;95.00;3102.;16.5;74;US\n",
+ "Ford Maverick;21.0;6;200.0;0;2875.;17.0;74;US\n",
+ "AMC Hornet;19.0;6;232.0;100.0;2901.;16.0;74;US\n",
+ "Chevrolet Nova;15.0;6;250.0;100.0;3336.;17.0;74;US\n",
+ "Datsun B210;31.0;4;79.00;67.00;1950.;19.0;74;Japan\n",
+ "Ford Pinto;26.0;4;122.0;80.00;2451.;16.5;74;US\n",
+ "Toyota Corolla 1200;32.0;4;71.00;65.00;1836.;21.0;74;Japan\n",
+ "Chevrolet Vega;25.0;4;140.0;75.00;2542.;17.0;74;US\n",
+ "Chevrolet Chevelle Malibu Classic;16.0;6;250.0;100.0;3781.;17.0;74;US\n",
+ "AMC Matador;16.0;6;258.0;110.0;3632.;18.0;74;US\n",
+ "Plymouth Satellite Sebring;18.0;6;225.0;105.0;3613.;16.5;74;US\n",
+ "Ford Gran Torino;16.0;8;302.0;140.0;4141.;14.0;74;US\n",
+ "Buick Century Luxus (sw);13.0;8;350.0;150.0;4699.;14.5;74;US\n",
+ "Dodge Coronet Custom (sw);14.0;8;318.0;150.0;4457.;13.5;74;US\n",
+ "Ford Gran Torino (sw);14.0;8;302.0;140.0;4638.;16.0;74;US\n",
+ "AMC Matador (sw);14.0;8;304.0;150.0;4257.;15.5;74;US\n",
+ "Audi Fox;29.0;4;98.00;83.00;2219.;16.5;74;Europe\n",
+ "Volkswagen Dasher;26.0;4;79.00;67.00;1963.;15.5;74;Europe\n",
+ "Opel Manta;26.0;4;97.00;78.00;2300.;14.5;74;Europe\n",
+ "Toyota Corolla;31.0;4;76.00;52.00;1649.;16.5;74;Japan\n",
+ "Datsun 710;32.0;4;83.00;61.00;2003.;19.0;74;Japan\n",
+ "Dodge Colt;28.0;4;90.00;75.00;2125.;14.5;74;US\n",
+ "Fiat 128;24.0;4;90.00;75.00;2108.;15.5;74;Europe\n",
+ "Fiat 124 TC;26.0;4;116.0;75.00;2246.;14.0;74;Europe\n",
+ "Honda Civic;24.0;4;120.0;97.00;2489.;15.0;74;Japan\n",
+ "Subaru;26.0;4;108.0;93.00;2391.;15.5;74;Japan\n",
+ "Fiat x1.9;31.0;4;79.00;67.00;2000.;16.0;74;Europe\n",
+ "Plymouth Valiant Custom;19.0;6;225.0;95.00;3264.;16.0;75;US\n",
+ "Chevrolet Nova;18.0;6;250.0;105.0;3459.;16.0;75;US\n",
+ "Mercury Monarch;15.0;6;250.0;72.00;3432.;21.0;75;US\n",
+ "Ford Maverick;15.0;6;250.0;72.00;3158.;19.5;75;US\n",
+ "Pontiac Catalina;16.0;8;400.0;170.0;4668.;11.5;75;US\n",
+ "Chevrolet Bel Air;15.0;8;350.0;145.0;4440.;14.0;75;US\n",
+ "Plymouth Grand Fury;16.0;8;318.0;150.0;4498.;14.5;75;US\n",
+ "Ford LTD;14.0;8;351.0;148.0;4657.;13.5;75;US\n",
+ "Buick Century;17.0;6;231.0;110.0;3907.;21.0;75;US\n",
+ "Chevrolete Chevelle Malibu;16.0;6;250.0;105.0;3897.;18.5;75;US\n",
+ "AMC Matador;15.0;6;258.0;110.0;3730.;19.0;75;US\n",
+ "Plymouth Fury;18.0;6;225.0;95.00;3785.;19.0;75;US\n",
+ "Buick Skyhawk;21.0;6;231.0;110.0;3039.;15.0;75;US\n",
+ "Chevrolet Monza 2+2;20.0;8;262.0;110.0;3221.;13.5;75;US\n",
+ "Ford Mustang II;13.0;8;302.0;129.0;3169.;12.0;75;US\n",
+ "Toyota Corolla;29.0;4;97.00;75.00;2171.;16.0;75;Japan\n",
+ "Ford Pinto;23.0;4;140.0;83.00;2639.;17.0;75;US\n",
+ "AMC Gremlin;20.0;6;232.0;100.0;2914.;16.0;75;US\n",
+ "Pontiac Astro;23.0;4;140.0;78.00;2592.;18.5;75;US\n",
+ "Toyota Corolla;24.0;4;134.0;96.00;2702.;13.5;75;Japan\n",
+ "Volkswagen Dasher;25.0;4;90.00;71.00;2223.;16.5;75;Europe\n",
+ "Datsun 710;24.0;4;119.0;97.00;2545.;17.0;75;Japan\n",
+ "Ford Pinto;18.0;6;171.0;97.00;2984.;14.5;75;US\n",
+ "Volkswagen Rabbit;29.0;4;90.00;70.00;1937.;14.0;75;Europe\n",
+ "AMC Pacer;19.0;6;232.0;90.00;3211.;17.0;75;US\n",
+ "Audi 100LS;23.0;4;115.0;95.00;2694.;15.0;75;Europe\n",
+ "Peugeot 504;23.0;4;120.0;88.00;2957.;17.0;75;Europe\n",
+ "Volvo 244DL;22.0;4;121.0;98.00;2945.;14.5;75;Europe\n",
+ "Saab 99LE;25.0;4;121.0;115.0;2671.;13.5;75;Europe\n",
+ "Honda Civic CVCC;33.0;4;91.00;53.00;1795.;17.5;75;Japan\n",
+ "Fiat 131;28.0;4;107.0;86.00;2464.;15.5;76;Europe\n",
+ "Opel 1900;25.0;4;116.0;81.00;2220.;16.9;76;Europe\n",
+ "Capri ii;25.0;4;140.0;92.00;2572.;14.9;76;US\n",
+ "Dodge Colt;26.0;4;98.00;79.00;2255.;17.7;76;US\n",
+ "Renault 12tl;27.0;4;101.0;83.00;2202.;15.3;76;Europe\n",
+ "Chevrolet Chevelle Malibu Classic;17.5;8;305.0;140.0;4215.;13.0;76;US\n",
+ "Dodge Coronet Brougham;16.0;8;318.0;150.0;4190.;13.0;76;US\n",
+ "AMC Matador;15.5;8;304.0;120.0;3962.;13.9;76;US\n",
+ "Ford Gran Torino;14.5;8;351.0;152.0;4215.;12.8;76;US\n",
+ "Plymouth Valiant;22.0;6;225.0;100.0;3233.;15.4;76;US\n",
+ "Chevrolet Nova;22.0;6;250.0;105.0;3353.;14.5;76;US\n",
+ "Ford Maverick;24.0;6;200.0;81.00;3012.;17.6;76;US\n",
+ "AMC Hornet;22.5;6;232.0;90.00;3085.;17.6;76;US\n",
+ "Chevrolet Chevette;29.0;4;85.00;52.00;2035.;22.2;76;US\n",
+ "Chevrolet Woody;24.5;4;98.00;60.00;2164.;22.1;76;US\n",
+ "Volkswagen Rabbit;29.0;4;90.00;70.00;1937.;14.2;76;Europe\n",
+ "Honda Civic;33.0;4;91.00;53.00;1795.;17.4;76;Japan\n",
+ "Dodge Aspen SE;20.0;6;225.0;100.0;3651.;17.7;76;US\n",
+ "Ford Grenada ghia;18.0;6;250.0;78.00;3574.;21.0;76;US\n",
+ "Pontiac Ventura SJ;18.5;6;250.0;110.0;3645.;16.2;76;US\n",
+ "AMC Pacer d/l;17.5;6;258.0;95.00;3193.;17.8;76;US\n",
+ "Volkswagen Rabbit;29.5;4;97.00;71.00;1825.;12.2;76;Europe\n",
+ "Datsun B-210;32.0;4;85.00;70.00;1990.;17.0;76;Japan\n",
+ "Toyota Corolla;28.0;4;97.00;75.00;2155.;16.4;76;Japan\n",
+ "Ford Pinto;26.5;4;140.0;72.00;2565.;13.6;76;US\n",
+ "Volvo 245;20.0;4;130.0;102.0;3150.;15.7;76;Europe\n",
+ "Plymouth Volare Premier v8;13.0;8;318.0;150.0;3940.;13.2;76;US\n",
+ "Peugeot 504;19.0;4;120.0;88.00;3270.;21.9;76;Europe\n",
+ "Toyota Mark II;19.0;6;156.0;108.0;2930.;15.5;76;Japan\n",
+ "Mercedes-Benz 280s;16.5;6;168.0;120.0;3820.;16.7;76;Europe\n",
+ "Cadillac Seville;16.5;8;350.0;180.0;4380.;12.1;76;US\n",
+ "Chevrolet C10;13.0;8;350.0;145.0;4055.;12.0;76;US\n",
+ "Ford F108;13.0;8;302.0;130.0;3870.;15.0;76;US\n",
+ "Dodge D100;13.0;8;318.0;150.0;3755.;14.0;76;US\n",
+ "Honda Accord CVCC;31.5;4;98.00;68.00;2045.;18.5;77;Japan\n",
+ "Buick Opel Isuzu Deluxe;30.0;4;111.0;80.00;2155.;14.8;77;US\n",
+ "Renault 5 GTL;36.0;4;79.00;58.00;1825.;18.6;77;Europe\n",
+ "Plymouth Arrow GS;25.5;4;122.0;96.00;2300.;15.5;77;US\n",
+ "Datsun F-10 Hatchback;33.5;4;85.00;70.00;1945.;16.8;77;Japan\n",
+ "Chevrolet Caprice Classic;17.5;8;305.0;145.0;3880.;12.5;77;US\n",
+ "Oldsmobile Cutlass Supreme;17.0;8;260.0;110.0;4060.;19.0;77;US\n",
+ "Dodge Monaco Brougham;15.5;8;318.0;145.0;4140.;13.7;77;US\n",
+ "Mercury Cougar Brougham;15.0;8;302.0;130.0;4295.;14.9;77;US\n",
+ "Chevrolet Concours;17.5;6;250.0;110.0;3520.;16.4;77;US\n",
+ "Buick Skylark;20.5;6;231.0;105.0;3425.;16.9;77;US\n",
+ "Plymouth Volare Custom;19.0;6;225.0;100.0;3630.;17.7;77;US\n",
+ "Ford Grenada;18.5;6;250.0;98.00;3525.;19.0;77;US\n",
+ "Pontiac Grand Prix LJ;16.0;8;400.0;180.0;4220.;11.1;77;US\n",
+ "Chevrolet Monte Carlo Landau;15.5;8;350.0;170.0;4165.;11.4;77;US\n",
+ "Chrysler Cordoba;15.5;8;400.0;190.0;4325.;12.2;77;US\n",
+ "Ford Thunderbird;16.0;8;351.0;149.0;4335.;14.5;77;US\n",
+ "Volkswagen Rabbit Custom;29.0;4;97.00;78.00;1940.;14.5;77;Europe\n",
+ "Pontiac Sunbird Coupe;24.5;4;151.0;88.00;2740.;16.0;77;US\n",
+ "Toyota Corolla Liftback;26.0;4;97.00;75.00;2265.;18.2;77;Japan\n",
+ "Ford Mustang II 2+2;25.5;4;140.0;89.00;2755.;15.8;77;US\n",
+ "Chevrolet Chevette;30.5;4;98.00;63.00;2051.;17.0;77;US\n",
+ "Dodge Colt m/m;33.5;4;98.00;83.00;2075.;15.9;77;US\n",
+ "Subaru DL;30.0;4;97.00;67.00;1985.;16.4;77;Japan\n",
+ "Volkswagen Dasher;30.5;4;97.00;78.00;2190.;14.1;77;Europe\n",
+ "Datsun 810;22.0;6;146.0;97.00;2815.;14.5;77;Japan\n",
+ "BMW 320i;21.5;4;121.0;110.0;2600.;12.8;77;Europe\n",
+ "Mazda RX-4;21.5;3;80.00;110.0;2720.;13.5;77;Japan\n",
+ "Volkswagen Rabbit Custom Diesel;43.1;4;90.00;48.00;1985.;21.5;78;Europe\n",
+ "Ford Fiesta;36.1;4;98.00;66.00;1800.;14.4;78;US\n",
+ "Mazda GLC Deluxe;32.8;4;78.00;52.00;1985.;19.4;78;Japan\n",
+ "Datsun B210 GX;39.4;4;85.00;70.00;2070.;18.6;78;Japan\n",
+ "Honda Civic CVCC;36.1;4;91.00;60.00;1800.;16.4;78;Japan\n",
+ "Oldsmobile Cutlass Salon Brougham;19.9;8;260.0;110.0;3365.;15.5;78;US\n",
+ "Dodge Diplomat;19.4;8;318.0;140.0;3735.;13.2;78;US\n",
+ "Mercury Monarch ghia;20.2;8;302.0;139.0;3570.;12.8;78;US\n",
+ "Pontiac Phoenix LJ;19.2;6;231.0;105.0;3535.;19.2;78;US\n",
+ "Chevrolet Malibu;20.5;6;200.0;95.00;3155.;18.2;78;US\n",
+ "Ford Fairmont (auto);20.2;6;200.0;85.00;2965.;15.8;78;US\n",
+ "Ford Fairmont (man);25.1;4;140.0;88.00;2720.;15.4;78;US\n",
+ "Plymouth Volare;20.5;6;225.0;100.0;3430.;17.2;78;US\n",
+ "AMC Concord;19.4;6;232.0;90.00;3210.;17.2;78;US\n",
+ "Buick Century Special;20.6;6;231.0;105.0;3380.;15.8;78;US\n",
+ "Mercury Zephyr;20.8;6;200.0;85.00;3070.;16.7;78;US\n",
+ "Dodge Aspen;18.6;6;225.0;110.0;3620.;18.7;78;US\n",
+ "AMC Concord d/l;18.1;6;258.0;120.0;3410.;15.1;78;US\n",
+ "Chevrolet Monte Carlo Landau;19.2;8;305.0;145.0;3425.;13.2;78;US\n",
+ "Buick Regal Sport Coupe (turbo);17.7;6;231.0;165.0;3445.;13.4;78;US\n",
+ "Ford Futura;18.1;8;302.0;139.0;3205.;11.2;78;US\n",
+ "Dodge Magnum XE;17.5;8;318.0;140.0;4080.;13.7;78;US\n",
+ "Chevrolet Chevette;30.0;4;98.00;68.00;2155.;16.5;78;US\n",
+ "Toyota Corolla;27.5;4;134.0;95.00;2560.;14.2;78;Japan\n",
+ "Datsun 510;27.2;4;119.0;97.00;2300.;14.7;78;Japan\n",
+ "Dodge Omni;30.9;4;105.0;75.00;2230.;14.5;78;US\n",
+ "Toyota Celica GT Liftback;21.1;4;134.0;95.00;2515.;14.8;78;Japan\n",
+ "Plymouth Sapporo;23.2;4;156.0;105.0;2745.;16.7;78;US\n",
+ "Oldsmobile Starfire SX;23.8;4;151.0;85.00;2855.;17.6;78;US\n",
+ "Datsun 200-SX;23.9;4;119.0;97.00;2405.;14.9;78;Japan\n",
+ "Audi 5000;20.3;5;131.0;103.0;2830.;15.9;78;Europe\n",
+ "Volvo 264gl;17.0;6;163.0;125.0;3140.;13.6;78;Europe\n",
+ "Saab 99gle;21.6;4;121.0;115.0;2795.;15.7;78;Europe\n",
+ "Peugeot 604sl;16.2;6;163.0;133.0;3410.;15.8;78;Europe\n",
+ "Volkswagen Scirocco;31.5;4;89.00;71.00;1990.;14.9;78;Europe\n",
+ "Honda Accord LX;29.5;4;98.00;68.00;2135.;16.6;78;Japan\n",
+ "Pontiac Lemans V6;21.5;6;231.0;115.0;3245.;15.4;79;US\n",
+ "Mercury Zephyr 6;19.8;6;200.0;85.00;2990.;18.2;79;US\n",
+ "Ford Fairmont 4;22.3;4;140.0;88.00;2890.;17.3;79;US\n",
+ "AMC Concord DL 6;20.2;6;232.0;90.00;3265.;18.2;79;US\n",
+ "Dodge Aspen 6;20.6;6;225.0;110.0;3360.;16.6;79;US\n",
+ "Chevrolet Caprice Classic;17.0;8;305.0;130.0;3840.;15.4;79;US\n",
+ "Ford LTD Landau;17.6;8;302.0;129.0;3725.;13.4;79;US\n",
+ "Mercury Grand Marquis;16.5;8;351.0;138.0;3955.;13.2;79;US\n",
+ "Dodge St. Regis;18.2;8;318.0;135.0;3830.;15.2;79;US\n",
+ "Buick Estate Wagon (sw);16.9;8;350.0;155.0;4360.;14.9;79;US\n",
+ "Ford Country Squire (sw);15.5;8;351.0;142.0;4054.;14.3;79;US\n",
+ "Chevrolet Malibu Classic (sw);19.2;8;267.0;125.0;3605.;15.0;79;US\n",
+ "Chrysler Lebaron Town @ Country (sw);18.5;8;360.0;150.0;3940.;13.0;79;US\n",
+ "Volkswagen Rabbit Custom;31.9;4;89.00;71.00;1925.;14.0;79;Europe\n",
+ "Mazda GLC Deluxe;34.1;4;86.00;65.00;1975.;15.2;79;Japan\n",
+ "Dodge Colt Hatchback Custom;35.7;4;98.00;80.00;1915.;14.4;79;US\n",
+ "AMC Spirit DL;27.4;4;121.0;80.00;2670.;15.0;79;US\n",
+ "Mercedes Benz 300d;25.4;5;183.0;77.00;3530.;20.1;79;Europe\n",
+ "Cadillac Eldorado;23.0;8;350.0;125.0;3900.;17.4;79;US\n",
+ "Peugeot 504;27.2;4;141.0;71.00;3190.;24.8;79;Europe\n",
+ "Oldsmobile Cutlass Salon Brougham;23.9;8;260.0;90.00;3420.;22.2;79;US\n",
+ "Plymouth Horizon;34.2;4;105.0;70.00;2200.;13.2;79;US\n",
+ "Plymouth Horizon TC3;34.5;4;105.0;70.00;2150.;14.9;79;US\n",
+ "Datsun 210;31.8;4;85.00;65.00;2020.;19.2;79;Japan\n",
+ "Fiat Strada Custom;37.3;4;91.00;69.00;2130.;14.7;79;Europe\n",
+ "Buick Skylark Limited;28.4;4;151.0;90.00;2670.;16.0;79;US\n",
+ "Chevrolet Citation;28.8;6;173.0;115.0;2595.;11.3;79;US\n",
+ "Oldsmobile Omega Brougham;26.8;6;173.0;115.0;2700.;12.9;79;US\n",
+ "Pontiac Phoenix;33.5;4;151.0;90.00;2556.;13.2;79;US\n",
+ "Volkswagen Rabbit;41.5;4;98.00;76.00;2144.;14.7;80;Europe\n",
+ "Toyota Corolla Tercel;38.1;4;89.00;60.00;1968.;18.8;80;Japan\n",
+ "Chevrolet Chevette;32.1;4;98.00;70.00;2120.;15.5;80;US\n",
+ "Datsun 310;37.2;4;86.00;65.00;2019.;16.4;80;Japan\n",
+ "Chevrolet Citation;28.0;4;151.0;90.00;2678.;16.5;80;US\n",
+ "Ford Fairmont;26.4;4;140.0;88.00;2870.;18.1;80;US\n",
+ "AMC Concord;24.3;4;151.0;90.00;3003.;20.1;80;US\n",
+ "Dodge Aspen;19.1;6;225.0;90.00;3381.;18.7;80;US\n",
+ "Audi 4000;34.3;4;97.00;78.00;2188.;15.8;80;Europe\n",
+ "Toyota Corolla Liftback;29.8;4;134.0;90.00;2711.;15.5;80;Japan\n",
+ "Mazda 626;31.3;4;120.0;75.00;2542.;17.5;80;Japan\n",
+ "Datsun 510 Hatchback;37.0;4;119.0;92.00;2434.;15.0;80;Japan\n",
+ "Toyota Corolla;32.2;4;108.0;75.00;2265.;15.2;80;Japan\n",
+ "Mazda GLC;46.6;4;86.00;65.00;2110.;17.9;80;Japan\n",
+ "Dodge Colt;27.9;4;156.0;105.0;2800.;14.4;80;US\n",
+ "Datsun 210;40.8;4;85.00;65.00;2110.;19.2;80;Japan\n",
+ "Volkswagen Rabbit C (Diesel);44.3;4;90.00;48.00;2085.;21.7;80;Europe\n",
+ "Volkswagen Dasher (diesel);43.4;4;90.00;48.00;2335.;23.7;80;Europe\n",
+ "Audi 5000s (diesel);36.4;5;121.0;67.00;2950.;19.9;80;Europe\n",
+ "Mercedes-Benz 240d;30.0;4;146.0;67.00;3250.;21.8;80;Europe\n",
+ "Honda Civic 1500 gl;44.6;4;91.00;67.00;1850.;13.8;80;Japan\n",
+ "Renault Lecar Deluxe;40.9;4;85.00;0;1835.;17.3;80;Europe\n",
+ "Subaru DL;33.8;4;97.00;67.00;2145.;18.0;80;Japan\n",
+ "Volkswagen Rabbit;29.8;4;89.00;62.00;1845.;15.3;80;Europe\n",
+ "Datsun 280-ZX;32.7;6;168.0;132.0;2910.;11.4;80;Japan\n",
+ "Mazda RX-7 GS;23.7;3;70.00;100.0;2420.;12.5;80;Japan\n",
+ "Triumph TR7 Coupe;35.0;4;122.0;88.00;2500.;15.1;80;Europe\n",
+ "Ford Mustang Cobra;23.6;4;140.0;0;2905.;14.3;80;US\n",
+ "Honda Accord;32.4;4;107.0;72.00;2290.;17.0;80;Japan\n",
+ "Plymouth Reliant;27.2;4;135.0;84.00;2490.;15.7;81;US\n",
+ "Buick Skylark;26.6;4;151.0;84.00;2635.;16.4;81;US\n",
+ "Dodge Aries Wagon (sw);25.8;4;156.0;92.00;2620.;14.4;81;US\n",
+ "Chevrolet Citation;23.5;6;173.0;110.0;2725.;12.6;81;US\n",
+ "Plymouth Reliant;30.0;4;135.0;84.00;2385.;12.9;81;US\n",
+ "Toyota Starlet;39.1;4;79.00;58.00;1755.;16.9;81;Japan\n",
+ "Plymouth Champ;39.0;4;86.00;64.00;1875.;16.4;81;US\n",
+ "Honda Civic 1300;35.1;4;81.00;60.00;1760.;16.1;81;Japan\n",
+ "Subaru;32.3;4;97.00;67.00;2065.;17.8;81;Japan\n",
+ "Datsun 210 MPG;37.0;4;85.00;65.00;1975.;19.4;81;Japan\n",
+ "Toyota Tercel;37.7;4;89.00;62.00;2050.;17.3;81;Japan\n",
+ "Mazda GLC 4;34.1;4;91.00;68.00;1985.;16.0;81;Japan\n",
+ "Plymouth Horizon 4;34.7;4;105.0;63.00;2215.;14.9;81;US\n",
+ "Ford Escort 4W;34.4;4;98.00;65.00;2045.;16.2;81;US\n",
+ "Ford Escort 2H;29.9;4;98.00;65.00;2380.;20.7;81;US\n",
+ "Volkswagen Jetta;33.0;4;105.0;74.00;2190.;14.2;81;Europe\n",
+ "Renault 18i;34.5;4;100.0;0;2320.;15.8;81;Europe\n",
+ "Honda Prelude;33.7;4;107.0;75.00;2210.;14.4;81;Japan\n",
+ "Toyota Corolla;32.4;4;108.0;75.00;2350.;16.8;81;Japan\n",
+ "Datsun 200SX;32.9;4;119.0;100.0;2615.;14.8;81;Japan\n",
+ "Mazda 626;31.6;4;120.0;74.00;2635.;18.3;81;Japan\n",
+ "Peugeot 505s Turbo Diesel;28.1;4;141.0;80.00;3230.;20.4;81;Europe\n",
+ "Saab 900s;0;4;121.0;110.0;2800.;15.4;81;Europe\n",
+ "Volvo Diesel;30.7;6;145.0;76.00;3160.;19.6;81;Europe\n",
+ "Toyota Cressida;25.4;6;168.0;116.0;2900.;12.6;81;Japan\n",
+ "Datsun 810 Maxima;24.2;6;146.0;120.0;2930.;13.8;81;Japan\n",
+ "Buick Century;22.4;6;231.0;110.0;3415.;15.8;81;US\n",
+ "Oldsmobile Cutlass LS;26.6;8;350.0;105.0;3725.;19.0;81;US\n",
+ "Ford Grenada gl;20.2;6;200.0;88.00;3060.;17.1;81;US\n",
+ "Chrysler Lebaron Salon;17.6;6;225.0;85.00;3465.;16.6;81;US\n",
+ "Chevrolet Cavalier;28.0;4;112.0;88.00;2605.;19.6;82;US\n",
+ "Chevrolet Cavalier Wagon;27.0;4;112.0;88.00;2640.;18.6;82;US\n",
+ "Chevrolet Cavalier 2-door;34.0;4;112.0;88.00;2395.;18.0;82;US\n",
+ "Pontiac J2000 SE Hatchback;31.0;4;112.0;85.00;2575.;16.2;82;US\n",
+ "Dodge Aries SE;29.0;4;135.0;84.00;2525.;16.0;82;US\n",
+ "Pontiac Phoenix;27.0;4;151.0;90.00;2735.;18.0;82;US\n",
+ "Ford Fairmont Futura;24.0;4;140.0;92.00;2865.;16.4;82;US\n",
+ "AMC Concord DL;23.0;4;151.0;0;3035.;20.5;82;US\n",
+ "Volkswagen Rabbit l;36.0;4;105.0;74.00;1980.;15.3;82;Europe\n",
+ "Mazda GLC Custom l;37.0;4;91.00;68.00;2025.;18.2;82;Japan\n",
+ "Mazda GLC Custom;31.0;4;91.00;68.00;1970.;17.6;82;Japan\n",
+ "Plymouth Horizon Miser;38.0;4;105.0;63.00;2125.;14.7;82;US\n",
+ "Mercury Lynx l;36.0;4;98.00;70.00;2125.;17.3;82;US\n",
+ "Nissan Stanza XE;36.0;4;120.0;88.00;2160.;14.5;82;Japan\n",
+ "Honda Accord;36.0;4;107.0;75.00;2205.;14.5;82;Japan\n",
+ "Toyota Corolla;34.0;4;108.0;70.00;2245;16.9;82;Japan\n",
+ "Honda Civic;38.0;4;91.00;67.00;1965.;15.0;82;Japan\n",
+ "Honda Civic (auto);32.0;4;91.00;67.00;1965.;15.7;82;Japan\n",
+ "Datsun 310 GX;38.0;4;91.00;67.00;1995.;16.2;82;Japan\n",
+ "Buick Century Limited;25.0;6;181.0;110.0;2945.;16.4;82;US\n",
+ "Oldsmobile Cutlass Ciera (diesel);38.0;6;262.0;85.00;3015.;17.0;82;US\n",
+ "Chrysler Lebaron Medallion;26.0;4;156.0;92.00;2585.;14.5;82;US\n",
+ "Ford Grenada l;22.0;6;232.0;112.0;2835;14.7;82;US\n",
+ "Toyota Celica GT;32.0;4;144.0;96.00;2665.;13.9;82;Japan\n",
+ "Dodge Charger 2.2;36.0;4;135.0;84.00;2370.;13.0;82;US\n",
+ "Chevrolet Camaro;27.0;4;151.0;90.00;2950.;17.3;82;US\n",
+ "Ford Mustang GL;27.0;4;140.0;86.00;2790.;15.6;82;US\n",
+ "Volkswagen Pickup;44.0;4;97.00;52.00;2130.;24.6;82;Europe\n",
+ "Dodge Rampage;32.0;4;135.0;84.00;2295.;11.6;82;US\n",
+ "Ford Ranger;28.0;4;120.0;79.00;2625.;18.6;82;US\n",
+ "Chevy S-10;31.0;4;119.0;82.00;2720.;19.4;82;US\n"
+ ]
+ }
+ ],
+ "source": [
+ "f = open('cars.csv')\n",
+ "for row in f:\n",
+ " print(row, end='')\n",
+ "f.close() "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "def parse_data_row(row):\n",
+ " row = row.strip('\\n').split(';')\n",
+ " return row[0], float(row[1])\n",
+ "\n",
+ "def max_mpg(data):\n",
+ " # get an iterator for data (which should be an iterable of some kind)\n",
+ " max_mpg = 0\n",
+ " for row in data:\n",
+ " _, mpg = parse_data_row(row)\n",
+ " if mpg > max_mpg:\n",
+ " max_mpg = mpg\n",
+ " return max_mpg"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "46.6\n"
+ ]
+ }
+ ],
+ "source": [
+ "f = open('cars.csv')\n",
+ "next(f)\n",
+ "next(f)\n",
+ "print(max_mpg(f))\n",
+ "f.close()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "def list_data(data, mpg_max):\n",
+ " for row in data:\n",
+ " car, mpg = parse_data_row(row)\n",
+ " mpg_perc = mpg / mpg_max * 100\n",
+ " print(f'{car}: {mpg_perc:.2f}%')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Chevrolet Chevelle Malibu: 38.63%\n",
+ "Buick Skylark 320: 32.19%\n",
+ "Plymouth Satellite: 38.63%\n",
+ "AMC Rebel SST: 34.33%\n",
+ "Ford Torino: 36.48%\n",
+ "Ford Galaxie 500: 32.19%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "AMC Ambassador DPL: 32.19%\n",
+ "Citroen DS-21 Pallas: 0.00%\n",
+ "Chevrolet Chevelle Concours (sw): 0.00%\n",
+ "Ford Torino (sw): 0.00%\n",
+ "Plymouth Satellite (sw): 0.00%\n",
+ "AMC Rebel SST (sw): 0.00%\n",
+ "Dodge Challenger SE: 32.19%\n",
+ "Plymouth 'Cuda 340: 30.04%\n",
+ "Ford Mustang Boss 302: 0.00%\n",
+ "Chevrolet Monte Carlo: 32.19%\n",
+ "Buick Estate Wagon (sw): 30.04%\n",
+ "Toyota Corolla Mark ii: 51.50%\n",
+ "Plymouth Duster: 47.21%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 45.06%\n",
+ "Datsun PL510: 57.94%\n",
+ "Volkswagen 1131 Deluxe Sedan: 55.79%\n",
+ "Peugeot 504: 53.65%\n",
+ "Audi 100 LS: 51.50%\n",
+ "Saab 99e: 53.65%\n",
+ "BMW 2002: 55.79%\n",
+ "AMC Gremlin: 45.06%\n",
+ "Ford F250: 21.46%\n",
+ "Chevy C20: 21.46%\n",
+ "Dodge D200: 23.61%\n",
+ "Hi 1200D: 19.31%\n",
+ "Datsun PL510: 57.94%\n",
+ "Chevrolet Vega 2300: 60.09%\n",
+ "Toyota Corolla: 53.65%\n",
+ "Ford Pinto: 53.65%\n",
+ "Volkswagen Super Beetle 117: 0.00%\n",
+ "AMC Gremlin: 40.77%\n",
+ "Plymouth Satellite Custom: 34.33%\n",
+ "Chevrolet Chevelle Malibu: 36.48%\n",
+ "Ford Torino 500: 40.77%\n",
+ "AMC Matador: 38.63%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Pontiac Catalina Brougham: 30.04%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Dodge Monaco (sw): 25.75%\n",
+ "Ford Country Squire (sw): 27.90%\n",
+ "Pontiac Safari (sw): 27.90%\n",
+ "AMC Hornet Sportabout (sw): 38.63%\n",
+ "Chevrolet Vega (sw): 47.21%\n",
+ "Pontiac Firebird: 40.77%\n",
+ "Ford Mustang: 38.63%\n",
+ "Mercury Capri 2000: 49.36%\n",
+ "Opel 1900: 60.09%\n",
+ "Peugeot 304: 64.38%\n",
+ "Fiat 124B: 64.38%\n",
+ "Toyota Corolla 1200: 66.52%\n",
+ "Datsun 1200: 75.11%\n",
+ "Volkswagen Model 111: 57.94%\n",
+ "Plymouth Cricket: 55.79%\n",
+ "Toyota Corolla Hardtop: 51.50%\n",
+ "Dodge Colt Hardtop: 53.65%\n",
+ "Volkswagen Type 3: 49.36%\n",
+ "Chevrolet Vega: 42.92%\n",
+ "Ford Pinto Runabout: 45.06%\n",
+ "Chevrolet Impala: 27.90%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "Plymouth Fury III: 32.19%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "AMC Ambassador SST: 36.48%\n",
+ "Mercury Marquis: 23.61%\n",
+ "Buick LeSabre Custom: 27.90%\n",
+ "Oldsmobile Delta 88 Royale: 25.75%\n",
+ "Chrysler Newport Royal: 27.90%\n",
+ "Mazda RX2 Coupe: 40.77%\n",
+ "AMC Matador (sw): 32.19%\n",
+ "Chevrolet Chevelle Concours (sw): 27.90%\n",
+ "Ford Gran Torino (sw): 27.90%\n",
+ "Plymouth Satellite Custom (sw): 30.04%\n",
+ "Volvo 145e (sw): 38.63%\n",
+ "Volkswagen 411 (sw): 47.21%\n",
+ "Peugeot 504 (sw): 45.06%\n",
+ "Renault 12 (sw): 55.79%\n",
+ "Ford Pinto (sw): 47.21%\n",
+ "Datsun 510 (sw): 60.09%\n",
+ "Toyota Corolla Mark II (sw): 49.36%\n",
+ "Dodge Colt (sw): 60.09%\n",
+ "Toyota Corolla 1600 (sw): 57.94%\n",
+ "Buick Century 350: 27.90%\n",
+ "AMC Matador: 30.04%\n",
+ "Chevrolet Malibu: 27.90%\n",
+ "Ford Gran Torino: 30.04%\n",
+ "Dodge Coronet Custom: 32.19%\n",
+ "Mercury Marquis Brougham: 25.75%\n",
+ "Chevrolet Caprice Classic: 27.90%\n",
+ "Ford LTD: 27.90%\n",
+ "Plymouth Fury Gran Sedan: 30.04%\n",
+ "Chrysler New Yorker Brougham: 27.90%\n",
+ "Buick Electra 225 Custom: 25.75%\n",
+ "AMC Ambassador Brougham: 27.90%\n",
+ "Plymouth Valiant: 38.63%\n",
+ "Chevrolet Nova Custom: 34.33%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 38.63%\n",
+ "Plymouth Duster: 49.36%\n",
+ "Volkswagen Super Beetle: 55.79%\n",
+ "Chevrolet Impala: 23.61%\n",
+ "Ford Country: 25.75%\n",
+ "Plymouth Custom Suburb: 27.90%\n",
+ "Oldsmobile Vista Cruiser: 25.75%\n",
+ "AMC Gremlin: 38.63%\n",
+ "Toyota Camry: 42.92%\n",
+ "Chevrolet Vega: 45.06%\n",
+ "Datsun 610: 47.21%\n",
+ "Mazda RX3: 38.63%\n",
+ "Ford Pinto: 40.77%\n",
+ "Mercury Capri v6: 45.06%\n",
+ "Fiat 124 Sport Coupe: 55.79%\n",
+ "Chevrolet Monte Carlo S: 32.19%\n",
+ "Pontiac Grand Prix: 34.33%\n",
+ "Fiat 128: 62.23%\n",
+ "Opel Manta: 51.50%\n",
+ "Audi 100LS: 42.92%\n",
+ "Volvo 144ea: 40.77%\n",
+ "Dodge Dart Custom: 32.19%\n",
+ "Saab 99le: 51.50%\n",
+ "Toyota Mark II: 42.92%\n",
+ "Oldsmobile Omega: 23.61%\n",
+ "Plymouth Duster: 42.92%\n",
+ "Ford Maverick: 45.06%\n",
+ "AMC Hornet: 40.77%\n",
+ "Chevrolet Nova: 32.19%\n",
+ "Datsun B210: 66.52%\n",
+ "Ford Pinto: 55.79%\n",
+ "Toyota Corolla 1200: 68.67%\n",
+ "Chevrolet Vega: 53.65%\n",
+ "Chevrolet Chevelle Malibu Classic: 34.33%\n",
+ "AMC Matador: 34.33%\n",
+ "Plymouth Satellite Sebring: 38.63%\n",
+ "Ford Gran Torino: 34.33%\n",
+ "Buick Century Luxus (sw): 27.90%\n",
+ "Dodge Coronet Custom (sw): 30.04%\n",
+ "Ford Gran Torino (sw): 30.04%\n",
+ "AMC Matador (sw): 30.04%\n",
+ "Audi Fox: 62.23%\n",
+ "Volkswagen Dasher: 55.79%\n",
+ "Opel Manta: 55.79%\n",
+ "Toyota Corolla: 66.52%\n",
+ "Datsun 710: 68.67%\n",
+ "Dodge Colt: 60.09%\n",
+ "Fiat 128: 51.50%\n",
+ "Fiat 124 TC: 55.79%\n",
+ "Honda Civic: 51.50%\n",
+ "Subaru: 55.79%\n",
+ "Fiat x1.9: 66.52%\n",
+ "Plymouth Valiant Custom: 40.77%\n",
+ "Chevrolet Nova: 38.63%\n",
+ "Mercury Monarch: 32.19%\n",
+ "Ford Maverick: 32.19%\n",
+ "Pontiac Catalina: 34.33%\n",
+ "Chevrolet Bel Air: 32.19%\n",
+ "Plymouth Grand Fury: 34.33%\n",
+ "Ford LTD: 30.04%\n",
+ "Buick Century: 36.48%\n",
+ "Chevrolete Chevelle Malibu: 34.33%\n",
+ "AMC Matador: 32.19%\n",
+ "Plymouth Fury: 38.63%\n",
+ "Buick Skyhawk: 45.06%\n",
+ "Chevrolet Monza 2+2: 42.92%\n",
+ "Ford Mustang II: 27.90%\n",
+ "Toyota Corolla: 62.23%\n",
+ "Ford Pinto: 49.36%\n",
+ "AMC Gremlin: 42.92%\n",
+ "Pontiac Astro: 49.36%\n",
+ "Toyota Corolla: 51.50%\n",
+ "Volkswagen Dasher: 53.65%\n",
+ "Datsun 710: 51.50%\n",
+ "Ford Pinto: 38.63%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "AMC Pacer: 40.77%\n",
+ "Audi 100LS: 49.36%\n",
+ "Peugeot 504: 49.36%\n",
+ "Volvo 244DL: 47.21%\n",
+ "Saab 99LE: 53.65%\n",
+ "Honda Civic CVCC: 70.82%\n",
+ "Fiat 131: 60.09%\n",
+ "Opel 1900: 53.65%\n",
+ "Capri ii: 53.65%\n",
+ "Dodge Colt: 55.79%\n",
+ "Renault 12tl: 57.94%\n",
+ "Chevrolet Chevelle Malibu Classic: 37.55%\n",
+ "Dodge Coronet Brougham: 34.33%\n",
+ "AMC Matador: 33.26%\n",
+ "Ford Gran Torino: 31.12%\n",
+ "Plymouth Valiant: 47.21%\n",
+ "Chevrolet Nova: 47.21%\n",
+ "Ford Maverick: 51.50%\n",
+ "AMC Hornet: 48.28%\n",
+ "Chevrolet Chevette: 62.23%\n",
+ "Chevrolet Woody: 52.58%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "Honda Civic: 70.82%\n",
+ "Dodge Aspen SE: 42.92%\n",
+ "Ford Grenada ghia: 38.63%\n",
+ "Pontiac Ventura SJ: 39.70%\n",
+ "AMC Pacer d/l: 37.55%\n",
+ "Volkswagen Rabbit: 63.30%\n",
+ "Datsun B-210: 68.67%\n",
+ "Toyota Corolla: 60.09%\n",
+ "Ford Pinto: 56.87%\n",
+ "Volvo 245: 42.92%\n",
+ "Plymouth Volare Premier v8: 27.90%\n",
+ "Peugeot 504: 40.77%\n",
+ "Toyota Mark II: 40.77%\n",
+ "Mercedes-Benz 280s: 35.41%\n",
+ "Cadillac Seville: 35.41%\n",
+ "Chevrolet C10: 27.90%\n",
+ "Ford F108: 27.90%\n",
+ "Dodge D100: 27.90%\n",
+ "Honda Accord CVCC: 67.60%\n",
+ "Buick Opel Isuzu Deluxe: 64.38%\n",
+ "Renault 5 GTL: 77.25%\n",
+ "Plymouth Arrow GS: 54.72%\n",
+ "Datsun F-10 Hatchback: 71.89%\n",
+ "Chevrolet Caprice Classic: 37.55%\n",
+ "Oldsmobile Cutlass Supreme: 36.48%\n",
+ "Dodge Monaco Brougham: 33.26%\n",
+ "Mercury Cougar Brougham: 32.19%\n",
+ "Chevrolet Concours: 37.55%\n",
+ "Buick Skylark: 43.99%\n",
+ "Plymouth Volare Custom: 40.77%\n",
+ "Ford Grenada: 39.70%\n",
+ "Pontiac Grand Prix LJ: 34.33%\n",
+ "Chevrolet Monte Carlo Landau: 33.26%\n",
+ "Chrysler Cordoba: 33.26%\n",
+ "Ford Thunderbird: 34.33%\n",
+ "Volkswagen Rabbit Custom: 62.23%\n",
+ "Pontiac Sunbird Coupe: 52.58%\n",
+ "Toyota Corolla Liftback: 55.79%\n",
+ "Ford Mustang II 2+2: 54.72%\n",
+ "Chevrolet Chevette: 65.45%\n",
+ "Dodge Colt m/m: 71.89%\n",
+ "Subaru DL: 64.38%\n",
+ "Volkswagen Dasher: 65.45%\n",
+ "Datsun 810: 47.21%\n",
+ "BMW 320i: 46.14%\n",
+ "Mazda RX-4: 46.14%\n",
+ "Volkswagen Rabbit Custom Diesel: 92.49%\n",
+ "Ford Fiesta: 77.47%\n",
+ "Mazda GLC Deluxe: 70.39%\n",
+ "Datsun B210 GX: 84.55%\n",
+ "Honda Civic CVCC: 77.47%\n",
+ "Oldsmobile Cutlass Salon Brougham: 42.70%\n",
+ "Dodge Diplomat: 41.63%\n",
+ "Mercury Monarch ghia: 43.35%\n",
+ "Pontiac Phoenix LJ: 41.20%\n",
+ "Chevrolet Malibu: 43.99%\n",
+ "Ford Fairmont (auto): 43.35%\n",
+ "Ford Fairmont (man): 53.86%\n",
+ "Plymouth Volare: 43.99%\n",
+ "AMC Concord: 41.63%\n",
+ "Buick Century Special: 44.21%\n",
+ "Mercury Zephyr: 44.64%\n",
+ "Dodge Aspen: 39.91%\n",
+ "AMC Concord d/l: 38.84%\n",
+ "Chevrolet Monte Carlo Landau: 41.20%\n",
+ "Buick Regal Sport Coupe (turbo): 37.98%\n",
+ "Ford Futura: 38.84%\n",
+ "Dodge Magnum XE: 37.55%\n",
+ "Chevrolet Chevette: 64.38%\n",
+ "Toyota Corolla: 59.01%\n",
+ "Datsun 510: 58.37%\n",
+ "Dodge Omni: 66.31%\n",
+ "Toyota Celica GT Liftback: 45.28%\n",
+ "Plymouth Sapporo: 49.79%\n",
+ "Oldsmobile Starfire SX: 51.07%\n",
+ "Datsun 200-SX: 51.29%\n",
+ "Audi 5000: 43.56%\n",
+ "Volvo 264gl: 36.48%\n",
+ "Saab 99gle: 46.35%\n",
+ "Peugeot 604sl: 34.76%\n",
+ "Volkswagen Scirocco: 67.60%\n",
+ "Honda Accord LX: 63.30%\n",
+ "Pontiac Lemans V6: 46.14%\n",
+ "Mercury Zephyr 6: 42.49%\n",
+ "Ford Fairmont 4: 47.85%\n",
+ "AMC Concord DL 6: 43.35%\n",
+ "Dodge Aspen 6: 44.21%\n",
+ "Chevrolet Caprice Classic: 36.48%\n",
+ "Ford LTD Landau: 37.77%\n",
+ "Mercury Grand Marquis: 35.41%\n",
+ "Dodge St. Regis: 39.06%\n",
+ "Buick Estate Wagon (sw): 36.27%\n",
+ "Ford Country Squire (sw): 33.26%\n",
+ "Chevrolet Malibu Classic (sw): 41.20%\n",
+ "Chrysler Lebaron Town @ Country (sw): 39.70%\n",
+ "Volkswagen Rabbit Custom: 68.45%\n",
+ "Mazda GLC Deluxe: 73.18%\n",
+ "Dodge Colt Hatchback Custom: 76.61%\n",
+ "AMC Spirit DL: 58.80%\n",
+ "Mercedes Benz 300d: 54.51%\n",
+ "Cadillac Eldorado: 49.36%\n",
+ "Peugeot 504: 58.37%\n",
+ "Oldsmobile Cutlass Salon Brougham: 51.29%\n",
+ "Plymouth Horizon: 73.39%\n",
+ "Plymouth Horizon TC3: 74.03%\n",
+ "Datsun 210: 68.24%\n",
+ "Fiat Strada Custom: 80.04%\n",
+ "Buick Skylark Limited: 60.94%\n",
+ "Chevrolet Citation: 61.80%\n",
+ "Oldsmobile Omega Brougham: 57.51%\n",
+ "Pontiac Phoenix: 71.89%\n",
+ "Volkswagen Rabbit: 89.06%\n",
+ "Toyota Corolla Tercel: 81.76%\n",
+ "Chevrolet Chevette: 68.88%\n",
+ "Datsun 310: 79.83%\n",
+ "Chevrolet Citation: 60.09%\n",
+ "Ford Fairmont: 56.65%\n",
+ "AMC Concord: 52.15%\n",
+ "Dodge Aspen: 40.99%\n",
+ "Audi 4000: 73.61%\n",
+ "Toyota Corolla Liftback: 63.95%\n",
+ "Mazda 626: 67.17%\n",
+ "Datsun 510 Hatchback: 79.40%\n",
+ "Toyota Corolla: 69.10%\n",
+ "Mazda GLC: 100.00%\n",
+ "Dodge Colt: 59.87%\n",
+ "Datsun 210: 87.55%\n",
+ "Volkswagen Rabbit C (Diesel): 95.06%\n",
+ "Volkswagen Dasher (diesel): 93.13%\n",
+ "Audi 5000s (diesel): 78.11%\n",
+ "Mercedes-Benz 240d: 64.38%\n",
+ "Honda Civic 1500 gl: 95.71%\n",
+ "Renault Lecar Deluxe: 87.77%\n",
+ "Subaru DL: 72.53%\n",
+ "Volkswagen Rabbit: 63.95%\n",
+ "Datsun 280-ZX: 70.17%\n",
+ "Mazda RX-7 GS: 50.86%\n",
+ "Triumph TR7 Coupe: 75.11%\n",
+ "Ford Mustang Cobra: 50.64%\n",
+ "Honda Accord: 69.53%\n",
+ "Plymouth Reliant: 58.37%\n",
+ "Buick Skylark: 57.08%\n",
+ "Dodge Aries Wagon (sw): 55.36%\n",
+ "Chevrolet Citation: 50.43%\n",
+ "Plymouth Reliant: 64.38%\n",
+ "Toyota Starlet: 83.91%\n",
+ "Plymouth Champ: 83.69%\n",
+ "Honda Civic 1300: 75.32%\n",
+ "Subaru: 69.31%\n",
+ "Datsun 210 MPG: 79.40%\n",
+ "Toyota Tercel: 80.90%\n",
+ "Mazda GLC 4: 73.18%\n",
+ "Plymouth Horizon 4: 74.46%\n",
+ "Ford Escort 4W: 73.82%\n",
+ "Ford Escort 2H: 64.16%\n",
+ "Volkswagen Jetta: 70.82%\n",
+ "Renault 18i: 74.03%\n",
+ "Honda Prelude: 72.32%\n",
+ "Toyota Corolla: 69.53%\n",
+ "Datsun 200SX: 70.60%\n",
+ "Mazda 626: 67.81%\n",
+ "Peugeot 505s Turbo Diesel: 60.30%\n",
+ "Saab 900s: 0.00%\n",
+ "Volvo Diesel: 65.88%\n",
+ "Toyota Cressida: 54.51%\n",
+ "Datsun 810 Maxima: 51.93%\n",
+ "Buick Century: 48.07%\n",
+ "Oldsmobile Cutlass LS: 57.08%\n",
+ "Ford Grenada gl: 43.35%\n",
+ "Chrysler Lebaron Salon: 37.77%\n",
+ "Chevrolet Cavalier: 60.09%\n",
+ "Chevrolet Cavalier Wagon: 57.94%\n",
+ "Chevrolet Cavalier 2-door: 72.96%\n",
+ "Pontiac J2000 SE Hatchback: 66.52%\n",
+ "Dodge Aries SE: 62.23%\n",
+ "Pontiac Phoenix: 57.94%\n",
+ "Ford Fairmont Futura: 51.50%\n",
+ "AMC Concord DL: 49.36%\n",
+ "Volkswagen Rabbit l: 77.25%\n",
+ "Mazda GLC Custom l: 79.40%\n",
+ "Mazda GLC Custom: 66.52%\n",
+ "Plymouth Horizon Miser: 81.55%\n",
+ "Mercury Lynx l: 77.25%\n",
+ "Nissan Stanza XE: 77.25%\n",
+ "Honda Accord: 77.25%\n",
+ "Toyota Corolla: 72.96%\n",
+ "Honda Civic: 81.55%\n",
+ "Honda Civic (auto): 68.67%\n",
+ "Datsun 310 GX: 81.55%\n",
+ "Buick Century Limited: 53.65%\n",
+ "Oldsmobile Cutlass Ciera (diesel): 81.55%\n",
+ "Chrysler Lebaron Medallion: 55.79%\n",
+ "Ford Grenada l: 47.21%\n",
+ "Toyota Celica GT: 68.67%\n",
+ "Dodge Charger 2.2: 77.25%\n",
+ "Chevrolet Camaro: 57.94%\n",
+ "Ford Mustang GL: 57.94%\n",
+ "Volkswagen Pickup: 94.42%\n",
+ "Dodge Rampage: 68.67%\n",
+ "Ford Ranger: 60.09%\n",
+ "Chevy S-10: 66.52%\n"
+ ]
+ }
+ ],
+ "source": [
+ "f = open('cars.csv')\n",
+ "next(f), next(f)\n",
+ "list_data(f, 46.6)\n",
+ "f.close()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's try and put these together:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "max=46.6\n"
+ ]
+ }
+ ],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " next(f)\n",
+ " next(f)\n",
+ " max_ = max_mpg(f)\n",
+ " print(f'max={max_}')\n",
+ " list_data(f, max_)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "No output from `list_data`!!\n",
+ "\n",
+ "That's because when we called `list_data` we had already exhausted the data file in the call to `max_mpg`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our only option is to either create the iterator twice:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Chevrolet Chevelle Malibu: 38.63%\n",
+ "Buick Skylark 320: 32.19%\n",
+ "Plymouth Satellite: 38.63%\n",
+ "AMC Rebel SST: 34.33%\n",
+ "Ford Torino: 36.48%\n",
+ "Ford Galaxie 500: 32.19%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "AMC Ambassador DPL: 32.19%\n",
+ "Citroen DS-21 Pallas: 0.00%\n",
+ "Chevrolet Chevelle Concours (sw): 0.00%\n",
+ "Ford Torino (sw): 0.00%\n",
+ "Plymouth Satellite (sw): 0.00%\n",
+ "AMC Rebel SST (sw): 0.00%\n",
+ "Dodge Challenger SE: 32.19%\n",
+ "Plymouth 'Cuda 340: 30.04%\n",
+ "Ford Mustang Boss 302: 0.00%\n",
+ "Chevrolet Monte Carlo: 32.19%\n",
+ "Buick Estate Wagon (sw): 30.04%\n",
+ "Toyota Corolla Mark ii: 51.50%\n",
+ "Plymouth Duster: 47.21%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 45.06%\n",
+ "Datsun PL510: 57.94%\n",
+ "Volkswagen 1131 Deluxe Sedan: 55.79%\n",
+ "Peugeot 504: 53.65%\n",
+ "Audi 100 LS: 51.50%\n",
+ "Saab 99e: 53.65%\n",
+ "BMW 2002: 55.79%\n",
+ "AMC Gremlin: 45.06%\n",
+ "Ford F250: 21.46%\n",
+ "Chevy C20: 21.46%\n",
+ "Dodge D200: 23.61%\n",
+ "Hi 1200D: 19.31%\n",
+ "Datsun PL510: 57.94%\n",
+ "Chevrolet Vega 2300: 60.09%\n",
+ "Toyota Corolla: 53.65%\n",
+ "Ford Pinto: 53.65%\n",
+ "Volkswagen Super Beetle 117: 0.00%\n",
+ "AMC Gremlin: 40.77%\n",
+ "Plymouth Satellite Custom: 34.33%\n",
+ "Chevrolet Chevelle Malibu: 36.48%\n",
+ "Ford Torino 500: 40.77%\n",
+ "AMC Matador: 38.63%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Pontiac Catalina Brougham: 30.04%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Dodge Monaco (sw): 25.75%\n",
+ "Ford Country Squire (sw): 27.90%\n",
+ "Pontiac Safari (sw): 27.90%\n",
+ "AMC Hornet Sportabout (sw): 38.63%\n",
+ "Chevrolet Vega (sw): 47.21%\n",
+ "Pontiac Firebird: 40.77%\n",
+ "Ford Mustang: 38.63%\n",
+ "Mercury Capri 2000: 49.36%\n",
+ "Opel 1900: 60.09%\n",
+ "Peugeot 304: 64.38%\n",
+ "Fiat 124B: 64.38%\n",
+ "Toyota Corolla 1200: 66.52%\n",
+ "Datsun 1200: 75.11%\n",
+ "Volkswagen Model 111: 57.94%\n",
+ "Plymouth Cricket: 55.79%\n",
+ "Toyota Corolla Hardtop: 51.50%\n",
+ "Dodge Colt Hardtop: 53.65%\n",
+ "Volkswagen Type 3: 49.36%\n",
+ "Chevrolet Vega: 42.92%\n",
+ "Ford Pinto Runabout: 45.06%\n",
+ "Chevrolet Impala: 27.90%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "Plymouth Fury III: 32.19%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "AMC Ambassador SST: 36.48%\n",
+ "Mercury Marquis: 23.61%\n",
+ "Buick LeSabre Custom: 27.90%\n",
+ "Oldsmobile Delta 88 Royale: 25.75%\n",
+ "Chrysler Newport Royal: 27.90%\n",
+ "Mazda RX2 Coupe: 40.77%\n",
+ "AMC Matador (sw): 32.19%\n",
+ "Chevrolet Chevelle Concours (sw): 27.90%\n",
+ "Ford Gran Torino (sw): 27.90%\n",
+ "Plymouth Satellite Custom (sw): 30.04%\n",
+ "Volvo 145e (sw): 38.63%\n",
+ "Volkswagen 411 (sw): 47.21%\n",
+ "Peugeot 504 (sw): 45.06%\n",
+ "Renault 12 (sw): 55.79%\n",
+ "Ford Pinto (sw): 47.21%\n",
+ "Datsun 510 (sw): 60.09%\n",
+ "Toyota Corolla Mark II (sw): 49.36%\n",
+ "Dodge Colt (sw): 60.09%\n",
+ "Toyota Corolla 1600 (sw): 57.94%\n",
+ "Buick Century 350: 27.90%\n",
+ "AMC Matador: 30.04%\n",
+ "Chevrolet Malibu: 27.90%\n",
+ "Ford Gran Torino: 30.04%\n",
+ "Dodge Coronet Custom: 32.19%\n",
+ "Mercury Marquis Brougham: 25.75%\n",
+ "Chevrolet Caprice Classic: 27.90%\n",
+ "Ford LTD: 27.90%\n",
+ "Plymouth Fury Gran Sedan: 30.04%\n",
+ "Chrysler New Yorker Brougham: 27.90%\n",
+ "Buick Electra 225 Custom: 25.75%\n",
+ "AMC Ambassador Brougham: 27.90%\n",
+ "Plymouth Valiant: 38.63%\n",
+ "Chevrolet Nova Custom: 34.33%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 38.63%\n",
+ "Plymouth Duster: 49.36%\n",
+ "Volkswagen Super Beetle: 55.79%\n",
+ "Chevrolet Impala: 23.61%\n",
+ "Ford Country: 25.75%\n",
+ "Plymouth Custom Suburb: 27.90%\n",
+ "Oldsmobile Vista Cruiser: 25.75%\n",
+ "AMC Gremlin: 38.63%\n",
+ "Toyota Camry: 42.92%\n",
+ "Chevrolet Vega: 45.06%\n",
+ "Datsun 610: 47.21%\n",
+ "Mazda RX3: 38.63%\n",
+ "Ford Pinto: 40.77%\n",
+ "Mercury Capri v6: 45.06%\n",
+ "Fiat 124 Sport Coupe: 55.79%\n",
+ "Chevrolet Monte Carlo S: 32.19%\n",
+ "Pontiac Grand Prix: 34.33%\n",
+ "Fiat 128: 62.23%\n",
+ "Opel Manta: 51.50%\n",
+ "Audi 100LS: 42.92%\n",
+ "Volvo 144ea: 40.77%\n",
+ "Dodge Dart Custom: 32.19%\n",
+ "Saab 99le: 51.50%\n",
+ "Toyota Mark II: 42.92%\n",
+ "Oldsmobile Omega: 23.61%\n",
+ "Plymouth Duster: 42.92%\n",
+ "Ford Maverick: 45.06%\n",
+ "AMC Hornet: 40.77%\n",
+ "Chevrolet Nova: 32.19%\n",
+ "Datsun B210: 66.52%\n",
+ "Ford Pinto: 55.79%\n",
+ "Toyota Corolla 1200: 68.67%\n",
+ "Chevrolet Vega: 53.65%\n",
+ "Chevrolet Chevelle Malibu Classic: 34.33%\n",
+ "AMC Matador: 34.33%\n",
+ "Plymouth Satellite Sebring: 38.63%\n",
+ "Ford Gran Torino: 34.33%\n",
+ "Buick Century Luxus (sw): 27.90%\n",
+ "Dodge Coronet Custom (sw): 30.04%\n",
+ "Ford Gran Torino (sw): 30.04%\n",
+ "AMC Matador (sw): 30.04%\n",
+ "Audi Fox: 62.23%\n",
+ "Volkswagen Dasher: 55.79%\n",
+ "Opel Manta: 55.79%\n",
+ "Toyota Corolla: 66.52%\n",
+ "Datsun 710: 68.67%\n",
+ "Dodge Colt: 60.09%\n",
+ "Fiat 128: 51.50%\n",
+ "Fiat 124 TC: 55.79%\n",
+ "Honda Civic: 51.50%\n",
+ "Subaru: 55.79%\n",
+ "Fiat x1.9: 66.52%\n",
+ "Plymouth Valiant Custom: 40.77%\n",
+ "Chevrolet Nova: 38.63%\n",
+ "Mercury Monarch: 32.19%\n",
+ "Ford Maverick: 32.19%\n",
+ "Pontiac Catalina: 34.33%\n",
+ "Chevrolet Bel Air: 32.19%\n",
+ "Plymouth Grand Fury: 34.33%\n",
+ "Ford LTD: 30.04%\n",
+ "Buick Century: 36.48%\n",
+ "Chevrolete Chevelle Malibu: 34.33%\n",
+ "AMC Matador: 32.19%\n",
+ "Plymouth Fury: 38.63%\n",
+ "Buick Skyhawk: 45.06%\n",
+ "Chevrolet Monza 2+2: 42.92%\n",
+ "Ford Mustang II: 27.90%\n",
+ "Toyota Corolla: 62.23%\n",
+ "Ford Pinto: 49.36%\n",
+ "AMC Gremlin: 42.92%\n",
+ "Pontiac Astro: 49.36%\n",
+ "Toyota Corolla: 51.50%\n",
+ "Volkswagen Dasher: 53.65%\n",
+ "Datsun 710: 51.50%\n",
+ "Ford Pinto: 38.63%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "AMC Pacer: 40.77%\n",
+ "Audi 100LS: 49.36%\n",
+ "Peugeot 504: 49.36%\n",
+ "Volvo 244DL: 47.21%\n",
+ "Saab 99LE: 53.65%\n",
+ "Honda Civic CVCC: 70.82%\n",
+ "Fiat 131: 60.09%\n",
+ "Opel 1900: 53.65%\n",
+ "Capri ii: 53.65%\n",
+ "Dodge Colt: 55.79%\n",
+ "Renault 12tl: 57.94%\n",
+ "Chevrolet Chevelle Malibu Classic: 37.55%\n",
+ "Dodge Coronet Brougham: 34.33%\n",
+ "AMC Matador: 33.26%\n",
+ "Ford Gran Torino: 31.12%\n",
+ "Plymouth Valiant: 47.21%\n",
+ "Chevrolet Nova: 47.21%\n",
+ "Ford Maverick: 51.50%\n",
+ "AMC Hornet: 48.28%\n",
+ "Chevrolet Chevette: 62.23%\n",
+ "Chevrolet Woody: 52.58%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "Honda Civic: 70.82%\n",
+ "Dodge Aspen SE: 42.92%\n",
+ "Ford Grenada ghia: 38.63%\n",
+ "Pontiac Ventura SJ: 39.70%\n",
+ "AMC Pacer d/l: 37.55%\n",
+ "Volkswagen Rabbit: 63.30%\n",
+ "Datsun B-210: 68.67%\n",
+ "Toyota Corolla: 60.09%\n",
+ "Ford Pinto: 56.87%\n",
+ "Volvo 245: 42.92%\n",
+ "Plymouth Volare Premier v8: 27.90%\n",
+ "Peugeot 504: 40.77%\n",
+ "Toyota Mark II: 40.77%\n",
+ "Mercedes-Benz 280s: 35.41%\n",
+ "Cadillac Seville: 35.41%\n",
+ "Chevrolet C10: 27.90%\n",
+ "Ford F108: 27.90%\n",
+ "Dodge D100: 27.90%\n",
+ "Honda Accord CVCC: 67.60%\n",
+ "Buick Opel Isuzu Deluxe: 64.38%\n",
+ "Renault 5 GTL: 77.25%\n",
+ "Plymouth Arrow GS: 54.72%\n",
+ "Datsun F-10 Hatchback: 71.89%\n",
+ "Chevrolet Caprice Classic: 37.55%\n",
+ "Oldsmobile Cutlass Supreme: 36.48%\n",
+ "Dodge Monaco Brougham: 33.26%\n",
+ "Mercury Cougar Brougham: 32.19%\n",
+ "Chevrolet Concours: 37.55%\n",
+ "Buick Skylark: 43.99%\n",
+ "Plymouth Volare Custom: 40.77%\n",
+ "Ford Grenada: 39.70%\n",
+ "Pontiac Grand Prix LJ: 34.33%\n",
+ "Chevrolet Monte Carlo Landau: 33.26%\n",
+ "Chrysler Cordoba: 33.26%\n",
+ "Ford Thunderbird: 34.33%\n",
+ "Volkswagen Rabbit Custom: 62.23%\n",
+ "Pontiac Sunbird Coupe: 52.58%\n",
+ "Toyota Corolla Liftback: 55.79%\n",
+ "Ford Mustang II 2+2: 54.72%\n",
+ "Chevrolet Chevette: 65.45%\n",
+ "Dodge Colt m/m: 71.89%\n",
+ "Subaru DL: 64.38%\n",
+ "Volkswagen Dasher: 65.45%\n",
+ "Datsun 810: 47.21%\n",
+ "BMW 320i: 46.14%\n",
+ "Mazda RX-4: 46.14%\n",
+ "Volkswagen Rabbit Custom Diesel: 92.49%\n",
+ "Ford Fiesta: 77.47%\n",
+ "Mazda GLC Deluxe: 70.39%\n",
+ "Datsun B210 GX: 84.55%\n",
+ "Honda Civic CVCC: 77.47%\n",
+ "Oldsmobile Cutlass Salon Brougham: 42.70%\n",
+ "Dodge Diplomat: 41.63%\n",
+ "Mercury Monarch ghia: 43.35%\n",
+ "Pontiac Phoenix LJ: 41.20%\n",
+ "Chevrolet Malibu: 43.99%\n",
+ "Ford Fairmont (auto): 43.35%\n",
+ "Ford Fairmont (man): 53.86%\n",
+ "Plymouth Volare: 43.99%\n",
+ "AMC Concord: 41.63%\n",
+ "Buick Century Special: 44.21%\n",
+ "Mercury Zephyr: 44.64%\n",
+ "Dodge Aspen: 39.91%\n",
+ "AMC Concord d/l: 38.84%\n",
+ "Chevrolet Monte Carlo Landau: 41.20%\n",
+ "Buick Regal Sport Coupe (turbo): 37.98%\n",
+ "Ford Futura: 38.84%\n",
+ "Dodge Magnum XE: 37.55%\n",
+ "Chevrolet Chevette: 64.38%\n",
+ "Toyota Corolla: 59.01%\n",
+ "Datsun 510: 58.37%\n",
+ "Dodge Omni: 66.31%\n",
+ "Toyota Celica GT Liftback: 45.28%\n",
+ "Plymouth Sapporo: 49.79%\n",
+ "Oldsmobile Starfire SX: 51.07%\n",
+ "Datsun 200-SX: 51.29%\n",
+ "Audi 5000: 43.56%\n",
+ "Volvo 264gl: 36.48%\n",
+ "Saab 99gle: 46.35%\n",
+ "Peugeot 604sl: 34.76%\n",
+ "Volkswagen Scirocco: 67.60%\n",
+ "Honda Accord LX: 63.30%\n",
+ "Pontiac Lemans V6: 46.14%\n",
+ "Mercury Zephyr 6: 42.49%\n",
+ "Ford Fairmont 4: 47.85%\n",
+ "AMC Concord DL 6: 43.35%\n",
+ "Dodge Aspen 6: 44.21%\n",
+ "Chevrolet Caprice Classic: 36.48%\n",
+ "Ford LTD Landau: 37.77%\n",
+ "Mercury Grand Marquis: 35.41%\n",
+ "Dodge St. Regis: 39.06%\n",
+ "Buick Estate Wagon (sw): 36.27%\n",
+ "Ford Country Squire (sw): 33.26%\n",
+ "Chevrolet Malibu Classic (sw): 41.20%\n",
+ "Chrysler Lebaron Town @ Country (sw): 39.70%\n",
+ "Volkswagen Rabbit Custom: 68.45%\n",
+ "Mazda GLC Deluxe: 73.18%\n",
+ "Dodge Colt Hatchback Custom: 76.61%\n",
+ "AMC Spirit DL: 58.80%\n",
+ "Mercedes Benz 300d: 54.51%\n",
+ "Cadillac Eldorado: 49.36%\n",
+ "Peugeot 504: 58.37%\n",
+ "Oldsmobile Cutlass Salon Brougham: 51.29%\n",
+ "Plymouth Horizon: 73.39%\n",
+ "Plymouth Horizon TC3: 74.03%\n",
+ "Datsun 210: 68.24%\n",
+ "Fiat Strada Custom: 80.04%\n",
+ "Buick Skylark Limited: 60.94%\n",
+ "Chevrolet Citation: 61.80%\n",
+ "Oldsmobile Omega Brougham: 57.51%\n",
+ "Pontiac Phoenix: 71.89%\n",
+ "Volkswagen Rabbit: 89.06%\n",
+ "Toyota Corolla Tercel: 81.76%\n",
+ "Chevrolet Chevette: 68.88%\n",
+ "Datsun 310: 79.83%\n",
+ "Chevrolet Citation: 60.09%\n",
+ "Ford Fairmont: 56.65%\n",
+ "AMC Concord: 52.15%\n",
+ "Dodge Aspen: 40.99%\n",
+ "Audi 4000: 73.61%\n",
+ "Toyota Corolla Liftback: 63.95%\n",
+ "Mazda 626: 67.17%\n",
+ "Datsun 510 Hatchback: 79.40%\n",
+ "Toyota Corolla: 69.10%\n",
+ "Mazda GLC: 100.00%\n",
+ "Dodge Colt: 59.87%\n",
+ "Datsun 210: 87.55%\n",
+ "Volkswagen Rabbit C (Diesel): 95.06%\n",
+ "Volkswagen Dasher (diesel): 93.13%\n",
+ "Audi 5000s (diesel): 78.11%\n",
+ "Mercedes-Benz 240d: 64.38%\n",
+ "Honda Civic 1500 gl: 95.71%\n",
+ "Renault Lecar Deluxe: 87.77%\n",
+ "Subaru DL: 72.53%\n",
+ "Volkswagen Rabbit: 63.95%\n",
+ "Datsun 280-ZX: 70.17%\n",
+ "Mazda RX-7 GS: 50.86%\n",
+ "Triumph TR7 Coupe: 75.11%\n",
+ "Ford Mustang Cobra: 50.64%\n",
+ "Honda Accord: 69.53%\n",
+ "Plymouth Reliant: 58.37%\n",
+ "Buick Skylark: 57.08%\n",
+ "Dodge Aries Wagon (sw): 55.36%\n",
+ "Chevrolet Citation: 50.43%\n",
+ "Plymouth Reliant: 64.38%\n",
+ "Toyota Starlet: 83.91%\n",
+ "Plymouth Champ: 83.69%\n",
+ "Honda Civic 1300: 75.32%\n",
+ "Subaru: 69.31%\n",
+ "Datsun 210 MPG: 79.40%\n",
+ "Toyota Tercel: 80.90%\n",
+ "Mazda GLC 4: 73.18%\n",
+ "Plymouth Horizon 4: 74.46%\n",
+ "Ford Escort 4W: 73.82%\n",
+ "Ford Escort 2H: 64.16%\n",
+ "Volkswagen Jetta: 70.82%\n",
+ "Renault 18i: 74.03%\n",
+ "Honda Prelude: 72.32%\n",
+ "Toyota Corolla: 69.53%\n",
+ "Datsun 200SX: 70.60%\n",
+ "Mazda 626: 67.81%\n",
+ "Peugeot 505s Turbo Diesel: 60.30%\n",
+ "Saab 900s: 0.00%\n",
+ "Volvo Diesel: 65.88%\n",
+ "Toyota Cressida: 54.51%\n",
+ "Datsun 810 Maxima: 51.93%\n",
+ "Buick Century: 48.07%\n",
+ "Oldsmobile Cutlass LS: 57.08%\n",
+ "Ford Grenada gl: 43.35%\n",
+ "Chrysler Lebaron Salon: 37.77%\n",
+ "Chevrolet Cavalier: 60.09%\n",
+ "Chevrolet Cavalier Wagon: 57.94%\n",
+ "Chevrolet Cavalier 2-door: 72.96%\n",
+ "Pontiac J2000 SE Hatchback: 66.52%\n",
+ "Dodge Aries SE: 62.23%\n",
+ "Pontiac Phoenix: 57.94%\n",
+ "Ford Fairmont Futura: 51.50%\n",
+ "AMC Concord DL: 49.36%\n",
+ "Volkswagen Rabbit l: 77.25%\n",
+ "Mazda GLC Custom l: 79.40%\n",
+ "Mazda GLC Custom: 66.52%\n",
+ "Plymouth Horizon Miser: 81.55%\n",
+ "Mercury Lynx l: 77.25%\n",
+ "Nissan Stanza XE: 77.25%\n",
+ "Honda Accord: 77.25%\n",
+ "Toyota Corolla: 72.96%\n",
+ "Honda Civic: 81.55%\n",
+ "Honda Civic (auto): 68.67%\n",
+ "Datsun 310 GX: 81.55%\n",
+ "Buick Century Limited: 53.65%\n",
+ "Oldsmobile Cutlass Ciera (diesel): 81.55%\n",
+ "Chrysler Lebaron Medallion: 55.79%\n",
+ "Ford Grenada l: 47.21%\n",
+ "Toyota Celica GT: 68.67%\n",
+ "Dodge Charger 2.2: 77.25%\n",
+ "Chevrolet Camaro: 57.94%\n",
+ "Ford Mustang GL: 57.94%\n",
+ "Volkswagen Pickup: 94.42%\n",
+ "Dodge Rampage: 68.67%\n",
+ "Ford Ranger: 60.09%\n",
+ "Chevy S-10: 66.52%\n"
+ ]
+ }
+ ],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " next(f), next(f)\n",
+ " max_ = max_mpg(f)\n",
+ " \n",
+ "with open('cars.csv') as f:\n",
+ " next(f), next(f)\n",
+ " list_data(f, max_)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or we could read the entire data set into a list first - but of course if the file is huge we will have some potential for running out memory:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " data = [row for row in f][2:]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or, more simply:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " data = f.readlines()[2:]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Chevrolet Chevelle Malibu: 38.63%\n",
+ "Buick Skylark 320: 32.19%\n",
+ "Plymouth Satellite: 38.63%\n",
+ "AMC Rebel SST: 34.33%\n",
+ "Ford Torino: 36.48%\n",
+ "Ford Galaxie 500: 32.19%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "AMC Ambassador DPL: 32.19%\n",
+ "Citroen DS-21 Pallas: 0.00%\n",
+ "Chevrolet Chevelle Concours (sw): 0.00%\n",
+ "Ford Torino (sw): 0.00%\n",
+ "Plymouth Satellite (sw): 0.00%\n",
+ "AMC Rebel SST (sw): 0.00%\n",
+ "Dodge Challenger SE: 32.19%\n",
+ "Plymouth 'Cuda 340: 30.04%\n",
+ "Ford Mustang Boss 302: 0.00%\n",
+ "Chevrolet Monte Carlo: 32.19%\n",
+ "Buick Estate Wagon (sw): 30.04%\n",
+ "Toyota Corolla Mark ii: 51.50%\n",
+ "Plymouth Duster: 47.21%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 45.06%\n",
+ "Datsun PL510: 57.94%\n",
+ "Volkswagen 1131 Deluxe Sedan: 55.79%\n",
+ "Peugeot 504: 53.65%\n",
+ "Audi 100 LS: 51.50%\n",
+ "Saab 99e: 53.65%\n",
+ "BMW 2002: 55.79%\n",
+ "AMC Gremlin: 45.06%\n",
+ "Ford F250: 21.46%\n",
+ "Chevy C20: 21.46%\n",
+ "Dodge D200: 23.61%\n",
+ "Hi 1200D: 19.31%\n",
+ "Datsun PL510: 57.94%\n",
+ "Chevrolet Vega 2300: 60.09%\n",
+ "Toyota Corolla: 53.65%\n",
+ "Ford Pinto: 53.65%\n",
+ "Volkswagen Super Beetle 117: 0.00%\n",
+ "AMC Gremlin: 40.77%\n",
+ "Plymouth Satellite Custom: 34.33%\n",
+ "Chevrolet Chevelle Malibu: 36.48%\n",
+ "Ford Torino 500: 40.77%\n",
+ "AMC Matador: 38.63%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Pontiac Catalina Brougham: 30.04%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Dodge Monaco (sw): 25.75%\n",
+ "Ford Country Squire (sw): 27.90%\n",
+ "Pontiac Safari (sw): 27.90%\n",
+ "AMC Hornet Sportabout (sw): 38.63%\n",
+ "Chevrolet Vega (sw): 47.21%\n",
+ "Pontiac Firebird: 40.77%\n",
+ "Ford Mustang: 38.63%\n",
+ "Mercury Capri 2000: 49.36%\n",
+ "Opel 1900: 60.09%\n",
+ "Peugeot 304: 64.38%\n",
+ "Fiat 124B: 64.38%\n",
+ "Toyota Corolla 1200: 66.52%\n",
+ "Datsun 1200: 75.11%\n",
+ "Volkswagen Model 111: 57.94%\n",
+ "Plymouth Cricket: 55.79%\n",
+ "Toyota Corolla Hardtop: 51.50%\n",
+ "Dodge Colt Hardtop: 53.65%\n",
+ "Volkswagen Type 3: 49.36%\n",
+ "Chevrolet Vega: 42.92%\n",
+ "Ford Pinto Runabout: 45.06%\n",
+ "Chevrolet Impala: 27.90%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "Plymouth Fury III: 32.19%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "AMC Ambassador SST: 36.48%\n",
+ "Mercury Marquis: 23.61%\n",
+ "Buick LeSabre Custom: 27.90%\n",
+ "Oldsmobile Delta 88 Royale: 25.75%\n",
+ "Chrysler Newport Royal: 27.90%\n",
+ "Mazda RX2 Coupe: 40.77%\n",
+ "AMC Matador (sw): 32.19%\n",
+ "Chevrolet Chevelle Concours (sw): 27.90%\n",
+ "Ford Gran Torino (sw): 27.90%\n",
+ "Plymouth Satellite Custom (sw): 30.04%\n",
+ "Volvo 145e (sw): 38.63%\n",
+ "Volkswagen 411 (sw): 47.21%\n",
+ "Peugeot 504 (sw): 45.06%\n",
+ "Renault 12 (sw): 55.79%\n",
+ "Ford Pinto (sw): 47.21%\n",
+ "Datsun 510 (sw): 60.09%\n",
+ "Toyota Corolla Mark II (sw): 49.36%\n",
+ "Dodge Colt (sw): 60.09%\n",
+ "Toyota Corolla 1600 (sw): 57.94%\n",
+ "Buick Century 350: 27.90%\n",
+ "AMC Matador: 30.04%\n",
+ "Chevrolet Malibu: 27.90%\n",
+ "Ford Gran Torino: 30.04%\n",
+ "Dodge Coronet Custom: 32.19%\n",
+ "Mercury Marquis Brougham: 25.75%\n",
+ "Chevrolet Caprice Classic: 27.90%\n",
+ "Ford LTD: 27.90%\n",
+ "Plymouth Fury Gran Sedan: 30.04%\n",
+ "Chrysler New Yorker Brougham: 27.90%\n",
+ "Buick Electra 225 Custom: 25.75%\n",
+ "AMC Ambassador Brougham: 27.90%\n",
+ "Plymouth Valiant: 38.63%\n",
+ "Chevrolet Nova Custom: 34.33%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 38.63%\n",
+ "Plymouth Duster: 49.36%\n",
+ "Volkswagen Super Beetle: 55.79%\n",
+ "Chevrolet Impala: 23.61%\n",
+ "Ford Country: 25.75%\n",
+ "Plymouth Custom Suburb: 27.90%\n",
+ "Oldsmobile Vista Cruiser: 25.75%\n",
+ "AMC Gremlin: 38.63%\n",
+ "Toyota Camry: 42.92%\n",
+ "Chevrolet Vega: 45.06%\n",
+ "Datsun 610: 47.21%\n",
+ "Mazda RX3: 38.63%\n",
+ "Ford Pinto: 40.77%\n",
+ "Mercury Capri v6: 45.06%\n",
+ "Fiat 124 Sport Coupe: 55.79%\n",
+ "Chevrolet Monte Carlo S: 32.19%\n",
+ "Pontiac Grand Prix: 34.33%\n",
+ "Fiat 128: 62.23%\n",
+ "Opel Manta: 51.50%\n",
+ "Audi 100LS: 42.92%\n",
+ "Volvo 144ea: 40.77%\n",
+ "Dodge Dart Custom: 32.19%\n",
+ "Saab 99le: 51.50%\n",
+ "Toyota Mark II: 42.92%\n",
+ "Oldsmobile Omega: 23.61%\n",
+ "Plymouth Duster: 42.92%\n",
+ "Ford Maverick: 45.06%\n",
+ "AMC Hornet: 40.77%\n",
+ "Chevrolet Nova: 32.19%\n",
+ "Datsun B210: 66.52%\n",
+ "Ford Pinto: 55.79%\n",
+ "Toyota Corolla 1200: 68.67%\n",
+ "Chevrolet Vega: 53.65%\n",
+ "Chevrolet Chevelle Malibu Classic: 34.33%\n",
+ "AMC Matador: 34.33%\n",
+ "Plymouth Satellite Sebring: 38.63%\n",
+ "Ford Gran Torino: 34.33%\n",
+ "Buick Century Luxus (sw): 27.90%\n",
+ "Dodge Coronet Custom (sw): 30.04%\n",
+ "Ford Gran Torino (sw): 30.04%\n",
+ "AMC Matador (sw): 30.04%\n",
+ "Audi Fox: 62.23%\n",
+ "Volkswagen Dasher: 55.79%\n",
+ "Opel Manta: 55.79%\n",
+ "Toyota Corolla: 66.52%\n",
+ "Datsun 710: 68.67%\n",
+ "Dodge Colt: 60.09%\n",
+ "Fiat 128: 51.50%\n",
+ "Fiat 124 TC: 55.79%\n",
+ "Honda Civic: 51.50%\n",
+ "Subaru: 55.79%\n",
+ "Fiat x1.9: 66.52%\n",
+ "Plymouth Valiant Custom: 40.77%\n",
+ "Chevrolet Nova: 38.63%\n",
+ "Mercury Monarch: 32.19%\n",
+ "Ford Maverick: 32.19%\n",
+ "Pontiac Catalina: 34.33%\n",
+ "Chevrolet Bel Air: 32.19%\n",
+ "Plymouth Grand Fury: 34.33%\n",
+ "Ford LTD: 30.04%\n",
+ "Buick Century: 36.48%\n",
+ "Chevrolete Chevelle Malibu: 34.33%\n",
+ "AMC Matador: 32.19%\n",
+ "Plymouth Fury: 38.63%\n",
+ "Buick Skyhawk: 45.06%\n",
+ "Chevrolet Monza 2+2: 42.92%\n",
+ "Ford Mustang II: 27.90%\n",
+ "Toyota Corolla: 62.23%\n",
+ "Ford Pinto: 49.36%\n",
+ "AMC Gremlin: 42.92%\n",
+ "Pontiac Astro: 49.36%\n",
+ "Toyota Corolla: 51.50%\n",
+ "Volkswagen Dasher: 53.65%\n",
+ "Datsun 710: 51.50%\n",
+ "Ford Pinto: 38.63%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "AMC Pacer: 40.77%\n",
+ "Audi 100LS: 49.36%\n",
+ "Peugeot 504: 49.36%\n",
+ "Volvo 244DL: 47.21%\n",
+ "Saab 99LE: 53.65%\n",
+ "Honda Civic CVCC: 70.82%\n",
+ "Fiat 131: 60.09%\n",
+ "Opel 1900: 53.65%\n",
+ "Capri ii: 53.65%\n",
+ "Dodge Colt: 55.79%\n",
+ "Renault 12tl: 57.94%\n",
+ "Chevrolet Chevelle Malibu Classic: 37.55%\n",
+ "Dodge Coronet Brougham: 34.33%\n",
+ "AMC Matador: 33.26%\n",
+ "Ford Gran Torino: 31.12%\n",
+ "Plymouth Valiant: 47.21%\n",
+ "Chevrolet Nova: 47.21%\n",
+ "Ford Maverick: 51.50%\n",
+ "AMC Hornet: 48.28%\n",
+ "Chevrolet Chevette: 62.23%\n",
+ "Chevrolet Woody: 52.58%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "Honda Civic: 70.82%\n",
+ "Dodge Aspen SE: 42.92%\n",
+ "Ford Grenada ghia: 38.63%\n",
+ "Pontiac Ventura SJ: 39.70%\n",
+ "AMC Pacer d/l: 37.55%\n",
+ "Volkswagen Rabbit: 63.30%\n",
+ "Datsun B-210: 68.67%\n",
+ "Toyota Corolla: 60.09%\n",
+ "Ford Pinto: 56.87%\n",
+ "Volvo 245: 42.92%\n",
+ "Plymouth Volare Premier v8: 27.90%\n",
+ "Peugeot 504: 40.77%\n",
+ "Toyota Mark II: 40.77%\n",
+ "Mercedes-Benz 280s: 35.41%\n",
+ "Cadillac Seville: 35.41%\n",
+ "Chevrolet C10: 27.90%\n",
+ "Ford F108: 27.90%\n",
+ "Dodge D100: 27.90%\n",
+ "Honda Accord CVCC: 67.60%\n",
+ "Buick Opel Isuzu Deluxe: 64.38%\n",
+ "Renault 5 GTL: 77.25%\n",
+ "Plymouth Arrow GS: 54.72%\n",
+ "Datsun F-10 Hatchback: 71.89%\n",
+ "Chevrolet Caprice Classic: 37.55%\n",
+ "Oldsmobile Cutlass Supreme: 36.48%\n",
+ "Dodge Monaco Brougham: 33.26%\n",
+ "Mercury Cougar Brougham: 32.19%\n",
+ "Chevrolet Concours: 37.55%\n",
+ "Buick Skylark: 43.99%\n",
+ "Plymouth Volare Custom: 40.77%\n",
+ "Ford Grenada: 39.70%\n",
+ "Pontiac Grand Prix LJ: 34.33%\n",
+ "Chevrolet Monte Carlo Landau: 33.26%\n",
+ "Chrysler Cordoba: 33.26%\n",
+ "Ford Thunderbird: 34.33%\n",
+ "Volkswagen Rabbit Custom: 62.23%\n",
+ "Pontiac Sunbird Coupe: 52.58%\n",
+ "Toyota Corolla Liftback: 55.79%\n",
+ "Ford Mustang II 2+2: 54.72%\n",
+ "Chevrolet Chevette: 65.45%\n",
+ "Dodge Colt m/m: 71.89%\n",
+ "Subaru DL: 64.38%\n",
+ "Volkswagen Dasher: 65.45%\n",
+ "Datsun 810: 47.21%\n",
+ "BMW 320i: 46.14%\n",
+ "Mazda RX-4: 46.14%\n",
+ "Volkswagen Rabbit Custom Diesel: 92.49%\n",
+ "Ford Fiesta: 77.47%\n",
+ "Mazda GLC Deluxe: 70.39%\n",
+ "Datsun B210 GX: 84.55%\n",
+ "Honda Civic CVCC: 77.47%\n",
+ "Oldsmobile Cutlass Salon Brougham: 42.70%\n",
+ "Dodge Diplomat: 41.63%\n",
+ "Mercury Monarch ghia: 43.35%\n",
+ "Pontiac Phoenix LJ: 41.20%\n",
+ "Chevrolet Malibu: 43.99%\n",
+ "Ford Fairmont (auto): 43.35%\n",
+ "Ford Fairmont (man): 53.86%\n",
+ "Plymouth Volare: 43.99%\n",
+ "AMC Concord: 41.63%\n",
+ "Buick Century Special: 44.21%\n",
+ "Mercury Zephyr: 44.64%\n",
+ "Dodge Aspen: 39.91%\n",
+ "AMC Concord d/l: 38.84%\n",
+ "Chevrolet Monte Carlo Landau: 41.20%\n",
+ "Buick Regal Sport Coupe (turbo): 37.98%\n",
+ "Ford Futura: 38.84%\n",
+ "Dodge Magnum XE: 37.55%\n",
+ "Chevrolet Chevette: 64.38%\n",
+ "Toyota Corolla: 59.01%\n",
+ "Datsun 510: 58.37%\n",
+ "Dodge Omni: 66.31%\n",
+ "Toyota Celica GT Liftback: 45.28%\n",
+ "Plymouth Sapporo: 49.79%\n",
+ "Oldsmobile Starfire SX: 51.07%\n",
+ "Datsun 200-SX: 51.29%\n",
+ "Audi 5000: 43.56%\n",
+ "Volvo 264gl: 36.48%\n",
+ "Saab 99gle: 46.35%\n",
+ "Peugeot 604sl: 34.76%\n",
+ "Volkswagen Scirocco: 67.60%\n",
+ "Honda Accord LX: 63.30%\n",
+ "Pontiac Lemans V6: 46.14%\n",
+ "Mercury Zephyr 6: 42.49%\n",
+ "Ford Fairmont 4: 47.85%\n",
+ "AMC Concord DL 6: 43.35%\n",
+ "Dodge Aspen 6: 44.21%\n",
+ "Chevrolet Caprice Classic: 36.48%\n",
+ "Ford LTD Landau: 37.77%\n",
+ "Mercury Grand Marquis: 35.41%\n",
+ "Dodge St. Regis: 39.06%\n",
+ "Buick Estate Wagon (sw): 36.27%\n",
+ "Ford Country Squire (sw): 33.26%\n",
+ "Chevrolet Malibu Classic (sw): 41.20%\n",
+ "Chrysler Lebaron Town @ Country (sw): 39.70%\n",
+ "Volkswagen Rabbit Custom: 68.45%\n",
+ "Mazda GLC Deluxe: 73.18%\n",
+ "Dodge Colt Hatchback Custom: 76.61%\n",
+ "AMC Spirit DL: 58.80%\n",
+ "Mercedes Benz 300d: 54.51%\n",
+ "Cadillac Eldorado: 49.36%\n",
+ "Peugeot 504: 58.37%\n",
+ "Oldsmobile Cutlass Salon Brougham: 51.29%\n",
+ "Plymouth Horizon: 73.39%\n",
+ "Plymouth Horizon TC3: 74.03%\n",
+ "Datsun 210: 68.24%\n",
+ "Fiat Strada Custom: 80.04%\n",
+ "Buick Skylark Limited: 60.94%\n",
+ "Chevrolet Citation: 61.80%\n",
+ "Oldsmobile Omega Brougham: 57.51%\n",
+ "Pontiac Phoenix: 71.89%\n",
+ "Volkswagen Rabbit: 89.06%\n",
+ "Toyota Corolla Tercel: 81.76%\n",
+ "Chevrolet Chevette: 68.88%\n",
+ "Datsun 310: 79.83%\n",
+ "Chevrolet Citation: 60.09%\n",
+ "Ford Fairmont: 56.65%\n",
+ "AMC Concord: 52.15%\n",
+ "Dodge Aspen: 40.99%\n",
+ "Audi 4000: 73.61%\n",
+ "Toyota Corolla Liftback: 63.95%\n",
+ "Mazda 626: 67.17%\n",
+ "Datsun 510 Hatchback: 79.40%\n",
+ "Toyota Corolla: 69.10%\n",
+ "Mazda GLC: 100.00%\n",
+ "Dodge Colt: 59.87%\n",
+ "Datsun 210: 87.55%\n",
+ "Volkswagen Rabbit C (Diesel): 95.06%\n",
+ "Volkswagen Dasher (diesel): 93.13%\n",
+ "Audi 5000s (diesel): 78.11%\n",
+ "Mercedes-Benz 240d: 64.38%\n",
+ "Honda Civic 1500 gl: 95.71%\n",
+ "Renault Lecar Deluxe: 87.77%\n",
+ "Subaru DL: 72.53%\n",
+ "Volkswagen Rabbit: 63.95%\n",
+ "Datsun 280-ZX: 70.17%\n",
+ "Mazda RX-7 GS: 50.86%\n",
+ "Triumph TR7 Coupe: 75.11%\n",
+ "Ford Mustang Cobra: 50.64%\n",
+ "Honda Accord: 69.53%\n",
+ "Plymouth Reliant: 58.37%\n",
+ "Buick Skylark: 57.08%\n",
+ "Dodge Aries Wagon (sw): 55.36%\n",
+ "Chevrolet Citation: 50.43%\n",
+ "Plymouth Reliant: 64.38%\n",
+ "Toyota Starlet: 83.91%\n",
+ "Plymouth Champ: 83.69%\n",
+ "Honda Civic 1300: 75.32%\n",
+ "Subaru: 69.31%\n",
+ "Datsun 210 MPG: 79.40%\n",
+ "Toyota Tercel: 80.90%\n",
+ "Mazda GLC 4: 73.18%\n",
+ "Plymouth Horizon 4: 74.46%\n",
+ "Ford Escort 4W: 73.82%\n",
+ "Ford Escort 2H: 64.16%\n",
+ "Volkswagen Jetta: 70.82%\n",
+ "Renault 18i: 74.03%\n",
+ "Honda Prelude: 72.32%\n",
+ "Toyota Corolla: 69.53%\n",
+ "Datsun 200SX: 70.60%\n",
+ "Mazda 626: 67.81%\n",
+ "Peugeot 505s Turbo Diesel: 60.30%\n",
+ "Saab 900s: 0.00%\n",
+ "Volvo Diesel: 65.88%\n",
+ "Toyota Cressida: 54.51%\n",
+ "Datsun 810 Maxima: 51.93%\n",
+ "Buick Century: 48.07%\n",
+ "Oldsmobile Cutlass LS: 57.08%\n",
+ "Ford Grenada gl: 43.35%\n",
+ "Chrysler Lebaron Salon: 37.77%\n",
+ "Chevrolet Cavalier: 60.09%\n",
+ "Chevrolet Cavalier Wagon: 57.94%\n",
+ "Chevrolet Cavalier 2-door: 72.96%\n",
+ "Pontiac J2000 SE Hatchback: 66.52%\n",
+ "Dodge Aries SE: 62.23%\n",
+ "Pontiac Phoenix: 57.94%\n",
+ "Ford Fairmont Futura: 51.50%\n",
+ "AMC Concord DL: 49.36%\n",
+ "Volkswagen Rabbit l: 77.25%\n",
+ "Mazda GLC Custom l: 79.40%\n",
+ "Mazda GLC Custom: 66.52%\n",
+ "Plymouth Horizon Miser: 81.55%\n",
+ "Mercury Lynx l: 77.25%\n",
+ "Nissan Stanza XE: 77.25%\n",
+ "Honda Accord: 77.25%\n",
+ "Toyota Corolla: 72.96%\n",
+ "Honda Civic: 81.55%\n",
+ "Honda Civic (auto): 68.67%\n",
+ "Datsun 310 GX: 81.55%\n",
+ "Buick Century Limited: 53.65%\n",
+ "Oldsmobile Cutlass Ciera (diesel): 81.55%\n",
+ "Chrysler Lebaron Medallion: 55.79%\n",
+ "Ford Grenada l: 47.21%\n",
+ "Toyota Celica GT: 68.67%\n",
+ "Dodge Charger 2.2: 77.25%\n",
+ "Chevrolet Camaro: 57.94%\n",
+ "Ford Mustang GL: 57.94%\n",
+ "Volkswagen Pickup: 94.42%\n",
+ "Dodge Rampage: 68.67%\n",
+ "Ford Ranger: 60.09%\n",
+ "Chevy S-10: 66.52%\n"
+ ]
+ }
+ ],
+ "source": [
+ "max_ = max_mpg(data)\n",
+ "list_data(data, max_)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "collapsed": true
+ },
+ "source": [
+ "We may even write functions that need to iterate more than once over an iterable. For example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "def list_data(data):\n",
+ " max_mpg = 0\n",
+ " for row in data:\n",
+ " _, mpg = parse_data_row(row)\n",
+ " if mpg > max_mpg:\n",
+ " max_mpg = mpg\n",
+ " \n",
+ " for row in data:\n",
+ " car, mpg = parse_data_row(row)\n",
+ " mpg_perc = mpg / max_mpg * 100\n",
+ " print(f'{car}: {mpg_perc:.2f}%')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But this will not work if we pass an iterator as the argument:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " next(f)\n",
+ " next(f)\n",
+ " list_data(f)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We might want to be more defensive about this in our function, either by raising an exception if the argument is an iterator, or making an iterable from the iterator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "def list_data(data):\n",
+ " if iter(data) is data:\n",
+ " raise ValueError('data cannot be an iterator.')\n",
+ " max_mpg = 0\n",
+ " for row in data:\n",
+ " _, mpg = parse_data_row(row)\n",
+ " if mpg > max_mpg:\n",
+ " max_mpg = mpg\n",
+ " \n",
+ " for row in data:\n",
+ " car, mpg = parse_data_row(row)\n",
+ " mpg_perc = mpg / max_mpg * 100\n",
+ " print(f'{car}: {mpg_perc:.2f}%')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "ValueError",
+ "evalue": "data cannot be an iterator.",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
+ "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mf\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mf\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mlist_data\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mf\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
+ "\u001b[1;32m\u001b[0m in \u001b[0;36mlist_data\u001b[1;34m(data)\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mlist_data\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0miter\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mis\u001b[0m \u001b[0mdata\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'data cannot be an iterator.'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[0mmax_mpg\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mrow\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mdata\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
+ "\u001b[1;31mValueError\u001b[0m: data cannot be an iterator."
+ ]
+ }
+ ],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " next(f)\n",
+ " next(f)\n",
+ " list_data(f)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {
+ "collapsed": true
+ },
+ "outputs": [],
+ "source": [
+ "def list_data(data):\n",
+ " if iter(data) is data:\n",
+ " data = list(data)\n",
+ " \n",
+ " max_mpg = 0\n",
+ " for row in data:\n",
+ " _, mpg = parse_data_row(row)\n",
+ " if mpg > max_mpg:\n",
+ " max_mpg = mpg\n",
+ " \n",
+ " for row in data:\n",
+ " car, mpg = parse_data_row(row)\n",
+ " mpg_perc = mpg / max_mpg * 100\n",
+ " print(f'{car}: {mpg_perc:.2f}%')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Chevrolet Chevelle Malibu: 38.63%\n",
+ "Buick Skylark 320: 32.19%\n",
+ "Plymouth Satellite: 38.63%\n",
+ "AMC Rebel SST: 34.33%\n",
+ "Ford Torino: 36.48%\n",
+ "Ford Galaxie 500: 32.19%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "AMC Ambassador DPL: 32.19%\n",
+ "Citroen DS-21 Pallas: 0.00%\n",
+ "Chevrolet Chevelle Concours (sw): 0.00%\n",
+ "Ford Torino (sw): 0.00%\n",
+ "Plymouth Satellite (sw): 0.00%\n",
+ "AMC Rebel SST (sw): 0.00%\n",
+ "Dodge Challenger SE: 32.19%\n",
+ "Plymouth 'Cuda 340: 30.04%\n",
+ "Ford Mustang Boss 302: 0.00%\n",
+ "Chevrolet Monte Carlo: 32.19%\n",
+ "Buick Estate Wagon (sw): 30.04%\n",
+ "Toyota Corolla Mark ii: 51.50%\n",
+ "Plymouth Duster: 47.21%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 45.06%\n",
+ "Datsun PL510: 57.94%\n",
+ "Volkswagen 1131 Deluxe Sedan: 55.79%\n",
+ "Peugeot 504: 53.65%\n",
+ "Audi 100 LS: 51.50%\n",
+ "Saab 99e: 53.65%\n",
+ "BMW 2002: 55.79%\n",
+ "AMC Gremlin: 45.06%\n",
+ "Ford F250: 21.46%\n",
+ "Chevy C20: 21.46%\n",
+ "Dodge D200: 23.61%\n",
+ "Hi 1200D: 19.31%\n",
+ "Datsun PL510: 57.94%\n",
+ "Chevrolet Vega 2300: 60.09%\n",
+ "Toyota Corolla: 53.65%\n",
+ "Ford Pinto: 53.65%\n",
+ "Volkswagen Super Beetle 117: 0.00%\n",
+ "AMC Gremlin: 40.77%\n",
+ "Plymouth Satellite Custom: 34.33%\n",
+ "Chevrolet Chevelle Malibu: 36.48%\n",
+ "Ford Torino 500: 40.77%\n",
+ "AMC Matador: 38.63%\n",
+ "Chevrolet Impala: 30.04%\n",
+ "Pontiac Catalina Brougham: 30.04%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "Plymouth Fury iii: 30.04%\n",
+ "Dodge Monaco (sw): 25.75%\n",
+ "Ford Country Squire (sw): 27.90%\n",
+ "Pontiac Safari (sw): 27.90%\n",
+ "AMC Hornet Sportabout (sw): 38.63%\n",
+ "Chevrolet Vega (sw): 47.21%\n",
+ "Pontiac Firebird: 40.77%\n",
+ "Ford Mustang: 38.63%\n",
+ "Mercury Capri 2000: 49.36%\n",
+ "Opel 1900: 60.09%\n",
+ "Peugeot 304: 64.38%\n",
+ "Fiat 124B: 64.38%\n",
+ "Toyota Corolla 1200: 66.52%\n",
+ "Datsun 1200: 75.11%\n",
+ "Volkswagen Model 111: 57.94%\n",
+ "Plymouth Cricket: 55.79%\n",
+ "Toyota Corolla Hardtop: 51.50%\n",
+ "Dodge Colt Hardtop: 53.65%\n",
+ "Volkswagen Type 3: 49.36%\n",
+ "Chevrolet Vega: 42.92%\n",
+ "Ford Pinto Runabout: 45.06%\n",
+ "Chevrolet Impala: 27.90%\n",
+ "Pontiac Catalina: 30.04%\n",
+ "Plymouth Fury III: 32.19%\n",
+ "Ford Galaxie 500: 30.04%\n",
+ "AMC Ambassador SST: 36.48%\n",
+ "Mercury Marquis: 23.61%\n",
+ "Buick LeSabre Custom: 27.90%\n",
+ "Oldsmobile Delta 88 Royale: 25.75%\n",
+ "Chrysler Newport Royal: 27.90%\n",
+ "Mazda RX2 Coupe: 40.77%\n",
+ "AMC Matador (sw): 32.19%\n",
+ "Chevrolet Chevelle Concours (sw): 27.90%\n",
+ "Ford Gran Torino (sw): 27.90%\n",
+ "Plymouth Satellite Custom (sw): 30.04%\n",
+ "Volvo 145e (sw): 38.63%\n",
+ "Volkswagen 411 (sw): 47.21%\n",
+ "Peugeot 504 (sw): 45.06%\n",
+ "Renault 12 (sw): 55.79%\n",
+ "Ford Pinto (sw): 47.21%\n",
+ "Datsun 510 (sw): 60.09%\n",
+ "Toyota Corolla Mark II (sw): 49.36%\n",
+ "Dodge Colt (sw): 60.09%\n",
+ "Toyota Corolla 1600 (sw): 57.94%\n",
+ "Buick Century 350: 27.90%\n",
+ "AMC Matador: 30.04%\n",
+ "Chevrolet Malibu: 27.90%\n",
+ "Ford Gran Torino: 30.04%\n",
+ "Dodge Coronet Custom: 32.19%\n",
+ "Mercury Marquis Brougham: 25.75%\n",
+ "Chevrolet Caprice Classic: 27.90%\n",
+ "Ford LTD: 27.90%\n",
+ "Plymouth Fury Gran Sedan: 30.04%\n",
+ "Chrysler New Yorker Brougham: 27.90%\n",
+ "Buick Electra 225 Custom: 25.75%\n",
+ "AMC Ambassador Brougham: 27.90%\n",
+ "Plymouth Valiant: 38.63%\n",
+ "Chevrolet Nova Custom: 34.33%\n",
+ "AMC Hornet: 38.63%\n",
+ "Ford Maverick: 38.63%\n",
+ "Plymouth Duster: 49.36%\n",
+ "Volkswagen Super Beetle: 55.79%\n",
+ "Chevrolet Impala: 23.61%\n",
+ "Ford Country: 25.75%\n",
+ "Plymouth Custom Suburb: 27.90%\n",
+ "Oldsmobile Vista Cruiser: 25.75%\n",
+ "AMC Gremlin: 38.63%\n",
+ "Toyota Camry: 42.92%\n",
+ "Chevrolet Vega: 45.06%\n",
+ "Datsun 610: 47.21%\n",
+ "Mazda RX3: 38.63%\n",
+ "Ford Pinto: 40.77%\n",
+ "Mercury Capri v6: 45.06%\n",
+ "Fiat 124 Sport Coupe: 55.79%\n",
+ "Chevrolet Monte Carlo S: 32.19%\n",
+ "Pontiac Grand Prix: 34.33%\n",
+ "Fiat 128: 62.23%\n",
+ "Opel Manta: 51.50%\n",
+ "Audi 100LS: 42.92%\n",
+ "Volvo 144ea: 40.77%\n",
+ "Dodge Dart Custom: 32.19%\n",
+ "Saab 99le: 51.50%\n",
+ "Toyota Mark II: 42.92%\n",
+ "Oldsmobile Omega: 23.61%\n",
+ "Plymouth Duster: 42.92%\n",
+ "Ford Maverick: 45.06%\n",
+ "AMC Hornet: 40.77%\n",
+ "Chevrolet Nova: 32.19%\n",
+ "Datsun B210: 66.52%\n",
+ "Ford Pinto: 55.79%\n",
+ "Toyota Corolla 1200: 68.67%\n",
+ "Chevrolet Vega: 53.65%\n",
+ "Chevrolet Chevelle Malibu Classic: 34.33%\n",
+ "AMC Matador: 34.33%\n",
+ "Plymouth Satellite Sebring: 38.63%\n",
+ "Ford Gran Torino: 34.33%\n",
+ "Buick Century Luxus (sw): 27.90%\n",
+ "Dodge Coronet Custom (sw): 30.04%\n",
+ "Ford Gran Torino (sw): 30.04%\n",
+ "AMC Matador (sw): 30.04%\n",
+ "Audi Fox: 62.23%\n",
+ "Volkswagen Dasher: 55.79%\n",
+ "Opel Manta: 55.79%\n",
+ "Toyota Corolla: 66.52%\n",
+ "Datsun 710: 68.67%\n",
+ "Dodge Colt: 60.09%\n",
+ "Fiat 128: 51.50%\n",
+ "Fiat 124 TC: 55.79%\n",
+ "Honda Civic: 51.50%\n",
+ "Subaru: 55.79%\n",
+ "Fiat x1.9: 66.52%\n",
+ "Plymouth Valiant Custom: 40.77%\n",
+ "Chevrolet Nova: 38.63%\n",
+ "Mercury Monarch: 32.19%\n",
+ "Ford Maverick: 32.19%\n",
+ "Pontiac Catalina: 34.33%\n",
+ "Chevrolet Bel Air: 32.19%\n",
+ "Plymouth Grand Fury: 34.33%\n",
+ "Ford LTD: 30.04%\n",
+ "Buick Century: 36.48%\n",
+ "Chevrolete Chevelle Malibu: 34.33%\n",
+ "AMC Matador: 32.19%\n",
+ "Plymouth Fury: 38.63%\n",
+ "Buick Skyhawk: 45.06%\n",
+ "Chevrolet Monza 2+2: 42.92%\n",
+ "Ford Mustang II: 27.90%\n",
+ "Toyota Corolla: 62.23%\n",
+ "Ford Pinto: 49.36%\n",
+ "AMC Gremlin: 42.92%\n",
+ "Pontiac Astro: 49.36%\n",
+ "Toyota Corolla: 51.50%\n",
+ "Volkswagen Dasher: 53.65%\n",
+ "Datsun 710: 51.50%\n",
+ "Ford Pinto: 38.63%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "AMC Pacer: 40.77%\n",
+ "Audi 100LS: 49.36%\n",
+ "Peugeot 504: 49.36%\n",
+ "Volvo 244DL: 47.21%\n",
+ "Saab 99LE: 53.65%\n",
+ "Honda Civic CVCC: 70.82%\n",
+ "Fiat 131: 60.09%\n",
+ "Opel 1900: 53.65%\n",
+ "Capri ii: 53.65%\n",
+ "Dodge Colt: 55.79%\n",
+ "Renault 12tl: 57.94%\n",
+ "Chevrolet Chevelle Malibu Classic: 37.55%\n",
+ "Dodge Coronet Brougham: 34.33%\n",
+ "AMC Matador: 33.26%\n",
+ "Ford Gran Torino: 31.12%\n",
+ "Plymouth Valiant: 47.21%\n",
+ "Chevrolet Nova: 47.21%\n",
+ "Ford Maverick: 51.50%\n",
+ "AMC Hornet: 48.28%\n",
+ "Chevrolet Chevette: 62.23%\n",
+ "Chevrolet Woody: 52.58%\n",
+ "Volkswagen Rabbit: 62.23%\n",
+ "Honda Civic: 70.82%\n",
+ "Dodge Aspen SE: 42.92%\n",
+ "Ford Grenada ghia: 38.63%\n",
+ "Pontiac Ventura SJ: 39.70%\n",
+ "AMC Pacer d/l: 37.55%\n",
+ "Volkswagen Rabbit: 63.30%\n",
+ "Datsun B-210: 68.67%\n",
+ "Toyota Corolla: 60.09%\n",
+ "Ford Pinto: 56.87%\n",
+ "Volvo 245: 42.92%\n",
+ "Plymouth Volare Premier v8: 27.90%\n",
+ "Peugeot 504: 40.77%\n",
+ "Toyota Mark II: 40.77%\n",
+ "Mercedes-Benz 280s: 35.41%\n",
+ "Cadillac Seville: 35.41%\n",
+ "Chevrolet C10: 27.90%\n",
+ "Ford F108: 27.90%\n",
+ "Dodge D100: 27.90%\n",
+ "Honda Accord CVCC: 67.60%\n",
+ "Buick Opel Isuzu Deluxe: 64.38%\n",
+ "Renault 5 GTL: 77.25%\n",
+ "Plymouth Arrow GS: 54.72%\n",
+ "Datsun F-10 Hatchback: 71.89%\n",
+ "Chevrolet Caprice Classic: 37.55%\n",
+ "Oldsmobile Cutlass Supreme: 36.48%\n",
+ "Dodge Monaco Brougham: 33.26%\n",
+ "Mercury Cougar Brougham: 32.19%\n",
+ "Chevrolet Concours: 37.55%\n",
+ "Buick Skylark: 43.99%\n",
+ "Plymouth Volare Custom: 40.77%\n",
+ "Ford Grenada: 39.70%\n",
+ "Pontiac Grand Prix LJ: 34.33%\n",
+ "Chevrolet Monte Carlo Landau: 33.26%\n",
+ "Chrysler Cordoba: 33.26%\n",
+ "Ford Thunderbird: 34.33%\n",
+ "Volkswagen Rabbit Custom: 62.23%\n",
+ "Pontiac Sunbird Coupe: 52.58%\n",
+ "Toyota Corolla Liftback: 55.79%\n",
+ "Ford Mustang II 2+2: 54.72%\n",
+ "Chevrolet Chevette: 65.45%\n",
+ "Dodge Colt m/m: 71.89%\n",
+ "Subaru DL: 64.38%\n",
+ "Volkswagen Dasher: 65.45%\n",
+ "Datsun 810: 47.21%\n",
+ "BMW 320i: 46.14%\n",
+ "Mazda RX-4: 46.14%\n",
+ "Volkswagen Rabbit Custom Diesel: 92.49%\n",
+ "Ford Fiesta: 77.47%\n",
+ "Mazda GLC Deluxe: 70.39%\n",
+ "Datsun B210 GX: 84.55%\n",
+ "Honda Civic CVCC: 77.47%\n",
+ "Oldsmobile Cutlass Salon Brougham: 42.70%\n",
+ "Dodge Diplomat: 41.63%\n",
+ "Mercury Monarch ghia: 43.35%\n",
+ "Pontiac Phoenix LJ: 41.20%\n",
+ "Chevrolet Malibu: 43.99%\n",
+ "Ford Fairmont (auto): 43.35%\n",
+ "Ford Fairmont (man): 53.86%\n",
+ "Plymouth Volare: 43.99%\n",
+ "AMC Concord: 41.63%\n",
+ "Buick Century Special: 44.21%\n",
+ "Mercury Zephyr: 44.64%\n",
+ "Dodge Aspen: 39.91%\n",
+ "AMC Concord d/l: 38.84%\n",
+ "Chevrolet Monte Carlo Landau: 41.20%\n",
+ "Buick Regal Sport Coupe (turbo): 37.98%\n",
+ "Ford Futura: 38.84%\n",
+ "Dodge Magnum XE: 37.55%\n",
+ "Chevrolet Chevette: 64.38%\n",
+ "Toyota Corolla: 59.01%\n",
+ "Datsun 510: 58.37%\n",
+ "Dodge Omni: 66.31%\n",
+ "Toyota Celica GT Liftback: 45.28%\n",
+ "Plymouth Sapporo: 49.79%\n",
+ "Oldsmobile Starfire SX: 51.07%\n",
+ "Datsun 200-SX: 51.29%\n",
+ "Audi 5000: 43.56%\n",
+ "Volvo 264gl: 36.48%\n",
+ "Saab 99gle: 46.35%\n",
+ "Peugeot 604sl: 34.76%\n",
+ "Volkswagen Scirocco: 67.60%\n",
+ "Honda Accord LX: 63.30%\n",
+ "Pontiac Lemans V6: 46.14%\n",
+ "Mercury Zephyr 6: 42.49%\n",
+ "Ford Fairmont 4: 47.85%\n",
+ "AMC Concord DL 6: 43.35%\n",
+ "Dodge Aspen 6: 44.21%\n",
+ "Chevrolet Caprice Classic: 36.48%\n",
+ "Ford LTD Landau: 37.77%\n",
+ "Mercury Grand Marquis: 35.41%\n",
+ "Dodge St. Regis: 39.06%\n",
+ "Buick Estate Wagon (sw): 36.27%\n",
+ "Ford Country Squire (sw): 33.26%\n",
+ "Chevrolet Malibu Classic (sw): 41.20%\n",
+ "Chrysler Lebaron Town @ Country (sw): 39.70%\n",
+ "Volkswagen Rabbit Custom: 68.45%\n",
+ "Mazda GLC Deluxe: 73.18%\n",
+ "Dodge Colt Hatchback Custom: 76.61%\n",
+ "AMC Spirit DL: 58.80%\n",
+ "Mercedes Benz 300d: 54.51%\n",
+ "Cadillac Eldorado: 49.36%\n",
+ "Peugeot 504: 58.37%\n",
+ "Oldsmobile Cutlass Salon Brougham: 51.29%\n",
+ "Plymouth Horizon: 73.39%\n",
+ "Plymouth Horizon TC3: 74.03%\n",
+ "Datsun 210: 68.24%\n",
+ "Fiat Strada Custom: 80.04%\n",
+ "Buick Skylark Limited: 60.94%\n",
+ "Chevrolet Citation: 61.80%\n",
+ "Oldsmobile Omega Brougham: 57.51%\n",
+ "Pontiac Phoenix: 71.89%\n",
+ "Volkswagen Rabbit: 89.06%\n",
+ "Toyota Corolla Tercel: 81.76%\n",
+ "Chevrolet Chevette: 68.88%\n",
+ "Datsun 310: 79.83%\n",
+ "Chevrolet Citation: 60.09%\n",
+ "Ford Fairmont: 56.65%\n",
+ "AMC Concord: 52.15%\n",
+ "Dodge Aspen: 40.99%\n",
+ "Audi 4000: 73.61%\n",
+ "Toyota Corolla Liftback: 63.95%\n",
+ "Mazda 626: 67.17%\n",
+ "Datsun 510 Hatchback: 79.40%\n",
+ "Toyota Corolla: 69.10%\n",
+ "Mazda GLC: 100.00%\n",
+ "Dodge Colt: 59.87%\n",
+ "Datsun 210: 87.55%\n",
+ "Volkswagen Rabbit C (Diesel): 95.06%\n",
+ "Volkswagen Dasher (diesel): 93.13%\n",
+ "Audi 5000s (diesel): 78.11%\n",
+ "Mercedes-Benz 240d: 64.38%\n",
+ "Honda Civic 1500 gl: 95.71%\n",
+ "Renault Lecar Deluxe: 87.77%\n",
+ "Subaru DL: 72.53%\n",
+ "Volkswagen Rabbit: 63.95%\n",
+ "Datsun 280-ZX: 70.17%\n",
+ "Mazda RX-7 GS: 50.86%\n",
+ "Triumph TR7 Coupe: 75.11%\n",
+ "Ford Mustang Cobra: 50.64%\n",
+ "Honda Accord: 69.53%\n",
+ "Plymouth Reliant: 58.37%\n",
+ "Buick Skylark: 57.08%\n",
+ "Dodge Aries Wagon (sw): 55.36%\n",
+ "Chevrolet Citation: 50.43%\n",
+ "Plymouth Reliant: 64.38%\n",
+ "Toyota Starlet: 83.91%\n",
+ "Plymouth Champ: 83.69%\n",
+ "Honda Civic 1300: 75.32%\n",
+ "Subaru: 69.31%\n",
+ "Datsun 210 MPG: 79.40%\n",
+ "Toyota Tercel: 80.90%\n",
+ "Mazda GLC 4: 73.18%\n",
+ "Plymouth Horizon 4: 74.46%\n",
+ "Ford Escort 4W: 73.82%\n",
+ "Ford Escort 2H: 64.16%\n",
+ "Volkswagen Jetta: 70.82%\n",
+ "Renault 18i: 74.03%\n",
+ "Honda Prelude: 72.32%\n",
+ "Toyota Corolla: 69.53%\n",
+ "Datsun 200SX: 70.60%\n",
+ "Mazda 626: 67.81%\n",
+ "Peugeot 505s Turbo Diesel: 60.30%\n",
+ "Saab 900s: 0.00%\n",
+ "Volvo Diesel: 65.88%\n",
+ "Toyota Cressida: 54.51%\n",
+ "Datsun 810 Maxima: 51.93%\n",
+ "Buick Century: 48.07%\n",
+ "Oldsmobile Cutlass LS: 57.08%\n",
+ "Ford Grenada gl: 43.35%\n",
+ "Chrysler Lebaron Salon: 37.77%\n",
+ "Chevrolet Cavalier: 60.09%\n",
+ "Chevrolet Cavalier Wagon: 57.94%\n",
+ "Chevrolet Cavalier 2-door: 72.96%\n",
+ "Pontiac J2000 SE Hatchback: 66.52%\n",
+ "Dodge Aries SE: 62.23%\n",
+ "Pontiac Phoenix: 57.94%\n",
+ "Ford Fairmont Futura: 51.50%\n",
+ "AMC Concord DL: 49.36%\n",
+ "Volkswagen Rabbit l: 77.25%\n",
+ "Mazda GLC Custom l: 79.40%\n",
+ "Mazda GLC Custom: 66.52%\n",
+ "Plymouth Horizon Miser: 81.55%\n",
+ "Mercury Lynx l: 77.25%\n",
+ "Nissan Stanza XE: 77.25%\n",
+ "Honda Accord: 77.25%\n",
+ "Toyota Corolla: 72.96%\n",
+ "Honda Civic: 81.55%\n",
+ "Honda Civic (auto): 68.67%\n",
+ "Datsun 310 GX: 81.55%\n",
+ "Buick Century Limited: 53.65%\n",
+ "Oldsmobile Cutlass Ciera (diesel): 81.55%\n",
+ "Chrysler Lebaron Medallion: 55.79%\n",
+ "Ford Grenada l: 47.21%\n",
+ "Toyota Celica GT: 68.67%\n",
+ "Dodge Charger 2.2: 77.25%\n",
+ "Chevrolet Camaro: 57.94%\n",
+ "Ford Mustang GL: 57.94%\n",
+ "Volkswagen Pickup: 94.42%\n",
+ "Dodge Rampage: 68.67%\n",
+ "Ford Ranger: 60.09%\n",
+ "Chevy S-10: 66.52%\n"
+ ]
+ }
+ ],
+ "source": [
+ "with open('cars.csv') as f:\n",
+ " next(f)\n",
+ " next(f)\n",
+ " list_data(f)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators for Function Arguments.tscproj b/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators for Function Arguments.tscproj
deleted file mode 100644
index 77021f73..00000000
--- a/Part 2/Section 04 - Iterables and Iterators/13 - Caveat Using Iterators for Function Arguments.tscproj
+++ /dev/null
@@ -1,206 +0,0 @@
-{
- "title" : "",
- "description" : "",
- "author" : "",
- "width" : 1920.0,
- "height" : 1080.0,
- "version" : "0.5",
- "editRate" : 30,
- "authoringClientName" : {
- "name" : "Camtasia Studio",
- "platform" : "Windows",
- "version" : "9.0"
- },
- "sourceBin" : [
- {
- "id" : 1,
- "src" : "D:\\fbapt\\Dropbox\\Python Deep Dive\\Part 2\\Section 03 - Iterables\\23 - An Important Caveat Using Iterators as Arguments\\Caveat using Iterators and Function Arguments Rec 05-05-18.trec",
- "rect" : [0, 0, 1920, 1080],
- "lastMod" : "20180505T233644",
- "sourceTracks" : [
- {
- "range" : [0, 58946],
- "type" : 0,
- "editRate" : 30,
- "trackRect" : [0, 0, 1920, 1080],
- "sampleRate" : 27,
- "bitDepth" : 0,
- "numChannels" : 0,
- "metaData" : "Caveat using Iterators and Function Arguments Rec 05-05-18.trec;"
- },
- {
- "range" : [0, 86635520],
- "type" : 2,
- "editRate" : 44100,
- "trackRect" : [0, 0, 0, 0],
- "sampleRate" : 44100,
- "bitDepth" : 16,
- "numChannels" : 2,
- "metaData" : ""
- }
- ]
- }
- ],
- "timeline" : {
- "id" : 2,
- "sceneTrack" : {
- "scenes" : [
- {
- "duration" : 1963.93333333333,
- "title" : "",
- "type" : "",
- "csml" : {
- "tracks" : [
- {
- "trackIndex" : 0,
- "medias" : [
- {
- "id" : 3,
- "_type" : "UnifiedMedia",
- "video" :
- {
- "id" : 4,
- "_type" : "ScreenVMFile",
- "src" : 1,
- "trackNumber" : 0,
- "attributes" : {
- "ident" : "Caveat using Iterators and Function Arguments Rec 05-05-18"
- },
- "parameters" : {
- "cursorScale" : {
- "type" : "double",
- "defaultValue" : 1.0,
- "interp" : "linr"
- },
- "cursorOpacity" : {
- "type" : "double",
- "defaultValue" : 1.0,
- "interp" : "linr"
- }
- },
- "effects" : [
-
- ],
- "start" : 0,
- "duration" : 58918,
- "mediaStart" : 18,
- "mediaDuration" : 58918,
- "scalar" : 1,
- "animationTracks" : {
-
- }
- },
- "audio" :
- {
- "id" : 5,
- "_type" : "AMFile",
- "src" : 1,
- "trackNumber" : 1,
- "attributes" : {
- "ident" : "",
- "sampleRate" : 44100,
- "bitDepth" : 16,
- "gain" : 1.0,
- "mixToMono" : false
- },
- "channelNumber" : "0,1",
- "effects" : [
- {
- "effectName" : "NoiseReduction",
- "category" : "categoryAudioEffects",
- "parameters" : {
- "denoiserAmount" : 20.0,
- "denoiserThreshold" : 0.0,
- "noiseProfile" : "cX0sQk3YgEJ0wBtBJ2XSQA33aUCVQ75AymfGQGxquT9h/DVBGMKqQPHAhD9pKhc/BZyHPyOxkz5c\r\noDM+oCNxPrLwKD6GGso9W8i/PhGtiz+fYxQ/VHksP1lsHz+CdjQ+FEjCPs9zMT7qWhs+ZPknPnoK\r\nWz14DkU9VpEGPtR/KD0Sn8099SiRPVN0yj2wb8U9lJ8rPlhPnz3SkjI9xjGAPbk7Xj1CkcA9b0Tr\r\nPVYLzD0rzBw+cf6fPaZ55Twy1N08II4xPDdtTzynrqg8ukaTPFO+KTwEh/U7Mk9YPLaAXD06aeQ8\r\nrB73PDE0YT2k2mI9DUACPSqkAD18swk95zozPfDP8TyPpug9VYqkPHBPVj0qxxc9/MkMPZetAz1r\r\nHYs9iHA2PTv/gz0qs9s8/DfRPeF+9Dy0OTk918AMPeOu9T3CCtA9GxbtPQPAgj0Re18+Bic6PnKj\r\nDD+dwPg+2X28Pt8L6D7wXDg+MCe7PR+TIj1Pcys9wcd5PDD5rT1+u549W5WfPCT2nz2sCEA+9JP7\r\nPMsiJj0Oduk8zmWzPkeIYz194Q49l3iTPRDBhj2X1ro8oNW0PISttjyjvkQ8hpKQPGQpqTw+6qY8\r\nsR9aPK/flDvAe2k8SFUPPf4iaTxNN0E8rvLdO7p3zz2T3yQ9QE90PblzpDyjAwo9kYHDPUJhMD0R\r\nDZI9LQvhPKkt6jz5ua87dwOBPARwsDskH0s9r2IWPKx1Mjz8ifg7Q6HOPNrMnjxneTQ9BdqKPc98\r\nBT0jAUQ9qBF4PTEDgD1lhfk89YVGPCyBCT3j3I88+sNYPByGrzzs5qA8hcBmPcAVuTx5e7M9pLme\r\nPeH0vz34wrk90L2fPZD+OD7gA9g9BvsbPhsYqD1DPxo+R+KZPfBcJz4/rZs9w7mwPZqeuD0JBLg9\r\n87xiPUOUdj06hIs925vDPPoaRT1iWZY9TPmrPaN04D1mBj4+oONfPh5iUD5g1Zs+CIMcPgwrXD4L\r\nqCU+VijyPQe6ID76nlA9opK9PSfzDj4yGm49qlCiPfVrHz1yays9C6L2PLxKYD1Q34A9T8n7Pd06\r\n5D1qWBE+wjIBPvZQBz6X6/k9iWMxPQu4+D2gDOo95tuVPQaPkj0yot88YHjaPSSmMT3VD1U9YO4f\r\nPHaISzy8kQY8c4zWPNgD2Dwpdfo8sCV4PagjTD3XfJ891muGPZw2yz22gt88D+IzPb5AGD15Hcc8\r\nPdjZPIgroDxv7Pg8lb+mPJpqijxczfE8w/rpPCohHj04+sI8GJKUPMzY/Dx/aNI8MBvWPFxEVTzA\r\nTxA9aiYAPbysezwxVMA8MX7iPCLOXTwldic8d9pXPPYZMzzSffw7TkslPES+zDsX+Wc8CkL4O2N5\r\nwjsyqyk7yoRHO0IiyzsKdVM7FE4LPLyWWzyxZ647CS/PO2dafju130s72OGyOnXHkTsxXDE8sQob\r\nPLRI4DtfhRo7BmrjOr7HzzouBTI7p6J7OtUnCDtvdpY6my2tOlSDszr0cb86In8CO0TbRDvO9jE7\r\nxJ6nOiqc5TqZdCo7TxCQO10OqTrk8h87OHf5OuzMqzoMF6Q7pyL0OoGVVzq5bKU620tUO9xMBjuC\r\nq1g6DVYCO8RuCjsUnQU79yqEO/h6YDsvz/Q7/h9/OzbX/DsOolM78abxO0g9XTuBh3s7sQecO4zj\r\nQDuC7TY6LT8KOxD0Mjuj56U6l8bYOg6oeTvSNFs7KJ4kOwa28TtLHI07qTajOzpnHzuvrp47V5na\r\nOoapyjquEAU7RPi6OsJ7MjuzRHw6qimHOsbWxDp8wPY6vKj8Op4t3zp2lA47/LO2O1maYjul3eI6\r\nOHB/OvznCDsBwgA7+EG+OsZghDrZwzc7kWF5Oyx54DpTQ846zoJCOwQ/ATtwVFg7juebO2jSDTxo\r\n3hQ8vBdoO8/zmTsP4J07fDOrO8PWFzyT2/U6VtTVO+nqJzuM5G47ZFabOqtG2zoiGYk6OKuUO3Vt\r\nqjoLvM46odIzO1mPizqYRZQ6jhfOOugvsToWfd07xysfO/h+WTuR6yQ7hkrDOpVItDonmHk6exq2\r\nOx0STDsEDMc7cjtZO8gL8jo4pkM83/jrO4P7aDx5/gU8oHhdO03wMzv3c006GhhgOqUc1jqeb606\r\nXroIO3W+DjpVbRI6baTVOqTCxToAr5Q65ewsOgpx1jpnSa07nvIEO/+xJjscBKs6pN+DO60hDDtx\r\nLo47hSgQO2wZHjt80hE7yBs+Osf5azombEM6yOXdOrvA4TpzYJc65evjOj6u7zo2gyA7ACmHO17a\r\nxTu0iUA8s+aIO7f+xDviwOo7UNAjO646/zqjLqg6OVmMOmqBjTpjnUk7EIGROyK39TpQxcA69g18\r\nOjg4xTtdCco7OxG6O08RvDsxkso6WDj9Ov5yKTtEb/M73Xq+OyQjljrkd6c7UkgfO6AtuToY8pE6\r\n9aE2OwQ6djtQEtA7JaJoO1yAjTqcvyY7cAveOtLpgDvgtyQ87jhQPJKDZzycXnA8pXqtPOyz+TvU\r\nr1s8leAzPKodCDyuijQ7VVavO1yNpjvv9ys64eIpOiLggTot3407yqaOO3f1NzpCL7A677K0O1rS\r\n/Tqje6o6FD+wO/GqGjxIhv47FfvqO4ZXBTypPhc7K38TPNBLajsh4g48XKyOO9y52DqhQMI6evWE\r\nOxaikjpUdHQ7DmWXO4eKgzv4fRE8vArXO64ltTujr0A8YZtQO7FQiTtoiqY7YfKcO6zgXjtCtg08\r\nCti6OpuLPDvWxSc7ZGqJOtxejTqcozQ6jcxhOtPhhDq47286PmCAOkP9RDuDmBg7iMrHOnh5KjvQ\r\nF4k7FA4fOoIbDzsOzd46H14UO0pYjjq7lIs6BfqzOrZI7Dr4B2U7ExROOw4OmDpuY3Y66bRXOuf+\r\nYTo8P8M6zQMHO90hODtKhoQ6cTCEOvSEkTpBZk86AG20Oj9WRTq91+A6v6OIOg02uToHnvU54FYr\r\nOon9bzoI9ag6hY+TOqGApjpQ5A07OJ6wOyXaQjrOGFI6YRcBO06XPTpy1z06vW4IO8JRTTqR3oQ6\r\nQKg6OiE6gzrMq3U64l5POicXCzr7vww7DyADOmB0WToC1Pg6nMhgOpMmcTo66pI6orvoOSZo6znd\r\nC306BrbTOZ6wNjovW6I65lp+OhipZjp4MbI6RSKEOlvLwjo6Peo6/x/ROsGGWzo7MJg6gseLOrFe\r\nczoUreg6fzWPOlFKzTpUw0M6KkWVOtEIHjowXmg6rj2tOgSWQzoPUpY6LjtrOvqIYTpmeXY6G+dI\r\nOpUQlTqZOQM6NP+1OeG9jTqMRmU6KEmgOnQ1PDp/gvE69IlROk+iAjroCxw7eAObOhTJNzqWSss5\r\nsSLmOWHXXjqMuk86avAPOiyczjm6YQs6CmFJOnJLBDobSUA6l6ZxOoxbPzqgwso5YnRhOgbFMTq8\r\nfyg6+MBROr6DvDoUF4s6jpB7OtcfeDpUCK46g9NUOlqOVTr4+Ds6OZMnOrtbJjr5Lf45cqnNOQrP\r\nkzrCxIo645pbOvQaHToCtpM6Y1pbOqJ7LDqC2zc6p6SGOrVOeDqwMDU6Gsm7OXBuDToJgzY6QbUb\r\nOrQJMzpDvAI6lEd2OuZsBzoXlJk6NNAlOqSHjDpYebI6AmWCOnflJTpGFgk6cLiuOlzgDzoiVWA6\r\nnKhdOtuLXjqF2W86ioQvOkS0hTqEZsg6S1qDOmrbizraYbI66JGoOu77jjqNlaY6ahYsOh86hzpT\r\nMnE67nJcOuYTvTrsnAc78bJqOksdOzplrYQ6erXFOpLrbzrTw3E66OIvOtC+FDqk0Dk6wgFNOmIe\r\n4TqyszQ7vj/OOi4XnjpUoW86qMXBOf0LkDoC1wM6tqMdO4AuFTuKwCk6qioGOi6tiDrwRPU6ZWLN\r\nOgw6CTvgCKQ6FyEFOz7YtzpN2Mo6dlspOy41szrRhD86zA6EOvaFUDt7Clg7JFOQOi0oUTthkIo6\r\ngkOoOhhsbDqlCI86ULX3OUQBBDrXZcc5UMYUOnw8IDoO0fE59fl3OWQUfzlk2zo6meoyOyfOeDoz\r\ngEU6yn+9OhOKkzuihao7rrUoOzY/9TpuKds6It25Ovm9mDqJT1Y7kCc4OpyV6DlTC086JIXiOV7e\r\nDDoaw3Q65M50OpSl8DkrKwU6WttPOndzSjtGxjY7Rb7zOuWiJDu4LKU6lc3tOhZBBDvxZCI7Ypeh\r\nO6xjxzq6RSU7tFnSOrSHgDrPRgQ6ek2tOoQ3WjrdCUA6Wi8AOvoa5TnPvbU6sIE2O/K8HTtZFWA6\r\nQvUYOnjVYjs4lj47uS28OeYRADtjQwI6nmRmOl6egTpSbKs62/KSOh2IRTrU6EE6pI3nOZDRDDop\r\nZx06vHc9OkdvTzpF2To6DGyIOuHnSzoeaik6tcCDOmPbKDu7JJA6EjPQOpIPTjqkFp06stdOOiUx\r\nsjrK7is6nViXOizwbDqjvJk59dniOfCN2TlQ8PY5TSFUOvZsXDnclug5C/u/Omvqjzqo+Us6Efic\r\nOjj22zpcRm86AUN8OoFhojqgNXc6Ae6mOtkHozqRYlY6/YZ7OiR5zzmpVwo7ej0AOnGSDzpzapw6\r\nCmk2OgfwHDqbXQM65NlbOtt5gjoPk4M6poKWOrqQ8zoftwk7QTGvOlp2oDrrQCA62bbgOfWr0Dn0\r\nnBM6897+Oe/HrDqSRek5vG5DOnSqhTq03s46vay9OgL8tTpW9Ts6AsS5Ol61bzpLNoM6EN0EO+Tc\r\nsTrHBAc7sA+WOmkbLTofgI86Y9qFOoR7gTpeD8U6jF8MOuX7XDoG3iw6quK3Or0ekzq3l8I5Pxlp\r\nOpdjdTo1RYM69D4IOkkgjjrWYC46VEx6OXZQUTlWeTE6bxItOjL7YTogqwo6fuKROm3iHjrHQMA5\r\nGuU0OkZRpjp4DZE6jZZ+OjuIJjpSyGU6xI6EOtTdWzpkbl06rw2GObl6/zkcCwY6fMLyOY6AUTqv\r\nXcc5GyaVOVWP+DjRM3U4JngTOI56GThM4x44RG4WOHO8BjibfRM43+z+NzCnBzhT+wg4e+oaOK/R\r\nDDjpXg84Lb0OOIHfAjhTnw44GyAGOLN73TdA6gs4dJ8POJNmAjhU+BA4sLAsOMOQADjGYBc4r0gM\r\nOJhyDTgOQRQ4YrQTONcHEziRlRc6bxwQOn0dCzjoCQ04X1MIOJ68CzhAiAs4+DL7NwoqCDjX4Ag4\r\n26wjOGcqCjiRMOQ3IagLONSXDzjVzgQ4YVn5N/xQAjiLxOU3pNIOOBjsDDjCIO0346ECONAmBzh9\r\n6N03yN3yN09tAzi+RRY4vQv4N8/MEjhENAE4m3D+N/VwGDhUtPo3qUgEOHssAjiEzwI4BO0DOGC7\r\nCzjete43cewIOIbY/Tds9AE4jEACOCch6jdD9fU3KQIAOP1w2DdBSP43hKcNOLwb+jd68QI4Anf9\r\nN0B0CDi0qAk4Phr4N37PAzjeCQ04aF0BOEKgEThAHgA4QQUFOBhODDgBeAs4eGYlOACy1DeVczpC\r\nwNCAQtrrGkGH5eNAHwNkQLzvvkDoOclA69y5P9qdNEFZ0KhAvrKFPzTBDj88cIg/qXCTPpDDLz4F\r\n4XQ+iQUlPoco7j2SN78+m+qLP3JzFj9mPCo/5gEdP7G4IT7ekss+mewiPlWAHj6QBC8+inlYPWmX\r\nCD042gU+LEJBPUQpiD3cx449IRKsPToAzT0ANiQ+xhOYPaAlOj2qJV49VMI0PfCosD1Dde09GAHH\r\nPcne/z3zqak9WCUFPchcAz1htkw8EHckPPId4Txgi1k8j1mTPKUgFzz66yA8N99qPWJzAD33K/08\r\nuAQvPRV7Rj2kxCQ9rLEPPbqZAz3oYE49recEPaHT3T0DoY085FUiPYB9ET0oCvc8zw4RPQM9mz1p\r\nXhQ9TmplPdcAwjykfLA9y4oDPW4ODT2jrCs9JtjVPUYj0j0WZfI97AeDPRB1Sz5UNDo+sXMJP3qW\r\n+D4E/bY+1rnhPk83MT6Ve7c9XyoSPemUNj1ycpQ8svTHPdnYmT0afoA852WdPckEVz77GNI8cuMQ\r\nPXvO9TxaN7A+gMFgPfkQHj1Z5I89Z0luPeLTnzzclag8OMWwPOE1PDz4ioc8JQDOPHhGljznB0Y8\r\nkoajO4gARzwN1ec8EtwZPB6JZjwT9ws8+EPWPbVmGT2ViSg9Yy9fPBxPBD2Ihtg9oMFBPW6Mcj1o\r\n/ZU8O93SPJwSpTs9xnc8mwZMPKYKET2Kx887nv4rPAjD1zsJP648fYx1PAcNCj3mr4I9ilnVPPPJ\r\nNT3thok9JwV6Pd0s/jxoSGk8jYMZPc84zDwnrmI8A3O9PFebrTzYdmw99FXvPJi2pz3iALg9lNSq\r\nPUEs1z0PBK49uXdHPgGA7j22nhg+v2qGPS2qEz6b2KE9wvIePoICpj3XX909Yym6PWABvT0hjWU9\r\nZ9lXPcn4ez2d5LY8JbQ2PfsvlT2dwZI9D1IBPvsNNj7Z+lA+/olUPohEjz51EiY+HLZjPhMVFj6S\r\nNc49pO0fPpPFMz3NEKc9JbwLPtIDRD2lN509PhkYPctTJT3DAf08tuNQPTiDbD0vKec91rvgPQ2v\r\nGT71j/09LKQBPkOf8z3WfyY9Oz7mPWC36z3Ov6Q9enmpPT0r/jydaNg9pVjxPDngTj0tEpY8Vp1R\r\nPKU9UTxiHM48//XvPECs4TxIdk49/mMsPWlLnz3UYIQ9gonaPV4Z+jxnfVQ9OukVPXk5ED1VieY8\r\n7OyoPGN/8jwDz2w8qaOOPEhwAz0qbNA8/BAPPeTCozwJIoQ8ZwXbPM4xtTz2l9U8eR9JPP0xDj16\r\nOgI9DF1oPDC4xTyfALA8FB76O99UcDxcWiY8vxIRPI2vrjttNTE8vSe8O40/jzxSLJ87L0/YO0b2\r\nADstzJs6qvfvO6/D3jspB9Q7Pf8XPLDorDupP6E769ErO0TqFDuUu2c7UH1KO3uUSzxhA7A7wBVN\r\nO+GmRjtmIFw7CnNnOjB1MTshPug65NlGOyDwljr8osE6jWsFO8KlaDrfm8I65HhOO4A0ajv+mgs7\r\nSH0cO+hGBDvcPpE7wz24Otp50TrVhLw6MEeDOkCxpjq4Rqw6umaiOvnODztz69A6dkiqOkxBxjo0\r\nPAM7RtCIOlJdyzqEWfQ76ul2OzjOBDy8uMc7yNoKPF/hhDtkVPA7BPVhO5dFijucZVE7lkyfOzZ1\r\n1DpYaWg6wngpO/ZoxTr3GzY7FR4rO16GsDspJe06mYnJOwdGrjtOhB87BDeGO7yJ2TvDRx47xF2I\r\nOvR/DTt2Drc6qlmIOjidvjp0Lbo6pHvLOvDwvjpfPJA6yNIJO+LIbDqUH886XtWZO3gbkTrpgcA6\r\nUSZOO6IyoTr6CGE6G2enOsChBjt4/uI6P8IBOx87BjuMQ7A7N/0uO/J/0TsKNFM7emeqO54LpDvg\r\nawE8w9aJOz0FozsZKBY8sTfEO+G5/DqGArA7E6loO9yflDsw5ww7Fp3WOhCWhjo1s4w7VD6oOr69\r\n6DoJQA07QFVlOiy17Dr4X1U6LV1mO3wAPjvhe4E72pAnOyGgKTv+NN06tAeWOvhXBjujvpY7Esg5\r\nO0+DiDurReE73Q0iO0JzHTwT574705IwPCqJrDsKHFs7pCUoOzh0tzoeL5g6Ah4MOu2zljpAP7I6\r\nePA3OkSe8TpThtY6DdsiO4e2MDr+Vvc6CBvZOnCxZjt/r6U7xCstO8OVzzqz4Z47HloLOwZRHzuQ\r\nhfE6oZsiO6wXPjs14Q86Xjl2OkBVhTo3Ww06xFIrOwGBozqsMhA7BrBWO2MXTTsOR/87Xvw8OycQ\r\nKjxdw4Q7ULu7O3/m2DuMxzU7zDPuOkrHYTohzJ06/5mrOpsoWjuseKM7iObNOvmZ1zqfMoc6mDjQ\r\nOwif1DtCV7A7hM3dO20GqDrg2UM7yDvdOpDRBDzzsok7cvReOi7JhDtYCOg6WkNMOxKByzp675E7\r\nCuxBO3XkwTsNe047dNzbOtJY1josTC86FjC0O/A3Gjym0kc8XECVPC4wSjwwtWU8G47vOx4qgDzH\r\nbAU8XdAMPEZhhTt2OlE7c6yWO7YdoTrEtk06zcILO+0JejsA25E7yIIIOsUQQzvWnP07+cVMOwya\r\nOzpK9Lc7L3yyO6cQBDx1aps7Pp3UOynHjjuMV5E7OO6LOnXrYDud0w87JAzKOhBhSjsI1Ic7LsTN\r\nOjLzFjsI1pI7Pv2AO2zqvTuTri47Tni1O9tDxzvhOus65pSuO/dfsDulSpM7yqqUO9Ck1ztGitQ6\r\naMbtOtL0oDqbDpg6fDY6O3//QTpyJCA7Eb2YOgfrsDrBb5w6yPPBOiRRTzokgjo6Yw0oOyTSgju0\r\nfus60Dv8OtwjEDvzlQM7mpS4OrB3pDpTA9o6+D7xOgrFITuyGAA7s46ZOkUDkjoQglg6fldGOvvU\r\nQzqvn8E6be8vOvupizpcIiw6ihiQOtj4jzphdhE74JsRO1S+bjq4FlI6Tk2FOs7EVzqoHZg6dm6B\r\nOoTM5DqZ0VA6/uX/OuW5jzoe8xw7ZiIbOp55rjqgmZ46BIAEOnWxWTrhya06OMCHOtyHJjuuUXg6\r\nwLiBOuDg4TqxIMA69s85Ol5z9zp3ns862h6cOhcyqDp7Jg46lMKROnAO3zooMFk6DDpIOn+IWjoU\r\nATk6h6oBOmlAWjrukww6JPYTOjTdqTrTxyE7eemOOjGf7TrJMww76yYUO+8+gzrAk2c6la5sOnZ+\r\nCjvO0oU6dtK/OosRsTpP6oM6CbM6OqKbBTocNJs69XTiOZctlzrqYxE6nnN0Oltj9jndvGM68XWI\r\nOsoyfTpnRrU5Q6o8Oq8N4jooW60660EBOrrO8jo+xIM65w2QOsPLVTpVH3Q65FB0OhTFfjo162A6\r\nvWoCOxtCpDolc0w6BRkGOhy/2DodTS463MRFOgGlmjoxJRw6lGmhOmFxUjoUpAM6Vs1wOlhoPTr9\r\n0sE60lOeOjH1NTqKaFI6IVwZOis7kjpuWpg5EouROow/bzpJCnU6afCCOoq/NzrSHcY5t1kEOvlm\r\npzoFd6Y6ftSYOibstToMu6c6Lc+SOkZPojmDCMo6Kv0zOpdPqzrpokI6VoMwOn0ZJzoVxIk6dU02\r\nOlscXTrEgMU5msMAOpnEljkjLUQ6Vy5hOqcNdzo6SpQ6GqQ2OrLB0Tnqpy06/RlaOoSWHzpsENU5\r\nPD5ZOiQAATqQ+TU6hdllOuzpazrfOxM7tJFlOnz1SDrl0G46ue5kOlwalzoMimc6ZmeCOjAuWzpb\r\nmHA6CqYWO0T0lTqOZIY6nhIWOlokijqnQrM6vWJkOmo/ijoncSY6fcLzOdU+NDraqCg6wMriOoAS\r\nLztSR746l2+mOuHxdjqcTdU5d4OFOvGXHjomORI7/ycWO82pLzoEQQI6eQGNOhV/yzqvBc46Kz0H\r\nO1irszpir/s6YsmtOlbtxToEaBs7HFCqOt2DIzr1DYg6ipJDO0F10zoC5Q07yql5O7BjHTr5ZwU7\r\nq7HJOV+GjzovETY6vho4OnOhszkFego6qLczOoOQ/zkIf5U540GHOZ/ZEDr+ej46MPAEO4tO0jqg\r\nV4s6O3GjO9HYuTv5kBM76kMcO6fYlzo8ry47zMgsOxbH+jqXWjk64PToOVAQTTq5Nfg5+fMPOvOY\r\ndzrs92o6bQTfObJvCDqK2FU6MINSO75tMTs+jvU66O4cO9YGqzoOIPA6J6gEO8ixKztKv5s7VJHN\r\nOuDHJDsYL846wCB2Otcj/zkmT6Q6OPZkOtlWPjp4huk5IQvXOahDuDrCMjc7e2ofO3KcUjqFlA46\r\nsdVlO3u8RDtW0b85Xr73OtK9ATquRXU6+pGAOlDCqDr+SpY6bqtPOhtuPDrhAP05f54QOlb3FDos\r\nQTE6BhxbOndxMDpJQIw6wixQOtA3KDoV7YY6kjMpOwbghjrEG9E6+O9JOlXulDpiBD06gqCtOpw3\r\nLjpE+JU6Gm+AOqCBqzmCX9s5cajLOSAW5TmrBm86ISNXOQgi9DnH07U6A4ynOnPvZzpuOJw64P0D\r\nO7LyojovdHE6PAyeOi5LcjpF+aE64t+fOqHQVTpmBHA6zqjTOaZVCTuqePg5JZcMOoawFzqqPKE6\r\nEb4bOiJE5DlD/1A6P5OGOiZkLTop5ZI6HmKgOj/+tjoPIbc6WICeOslfETqluiM69lTZOZcSETrC\r\nW/U5nNerOl5/4TkurV868lPiOa74zzpIGNA6Hp7FOmDlVzo+G786lQ8zOl5vfzqb6AU7XHqwOhTK\r\nBzu90ZU6enIvOpUJkDqK5YY6h8BLOh5P1Dr+xAc69AZfOpHmLzp0Mq06B9WIOpOjwTkusG86CHRr\r\nOsCnijrIkwI619aGOh6ANjpstIg5aNJlOYRGKjpJfC46me9aOjIbBDrJNpI68Y0fOt6JtDlHWTU6\r\nEi+iOqCmkTrmkng6QKEWOmkHVzo+cYk62A5aOgKTWzpqzoo5+jgIOtguCzoGiQM6y6dYOqNczDmP\r\niZM5BJPQOJyNcTiGAg44RI7xN64YCjhwFQY4FcgMOPjJDDgbwAo41RYWOOKzBzhzVyY4KD4POJmV\r\nHDhi9Pc3WmwIODDWHTjizBw4QPn9N6+hDDj/dB04JZPmN2HR+DfVshE4sgL4NzwZCTh9du83Z28J\r\nOFv8Hzj2UQU42Ev+N84LIzpouRI6rTMAOMwTFjhShgk4b4X+N9G2GjiahAw4PS8EOM9N/jf9UA04\r\n5ej4N78XBzi24A448y8ROPvWDjhuxQQ4LNAfOM//Ezjl3u83emIjODPMBDiU4xI4G8QKOFknFDjo\r\nTQg4dpT6N7kxBThAFfs3O34EOLuHCzhWK/w3ZgUHOKiS9je7OAM4HM7rN01jFThtsuI32GcLOP+o\r\nAjgh+AM41IIKONiACDhPYQQ4FsAHOKrKEjh2efo3Me7/N+idBjhpyf830wD8N3CE8zf/aec3vPH+\r\nN3jfAThDJAI4JcXKNzL77jcXMBA4KPPVN1P1AziMrts3IaX5N9r8DjigZ+o3AEAEOA==",
- "noiseTrainingType" : "default"
- },
- "metadata" : {
- "effectIndex" : "0"
- }
- }
- ],
- "start" : 0,
- "duration" : 58918,
- "mediaStart" : 18,
- "mediaDuration" : 58918,
- "scalar" : 1,
- "animationTracks" : {
-
- }
- }
-,
- "start" : 0,
- "duration" : 58918,
- "mediaStart" : 0,
- "mediaDuration" : 58936,
- "scalar" : 1,
- "metadata" : {
- "AutoAppliedSmartFocus" : "False",
- "WinSubProjectDisplayName" : "",
- "clipSpeedAttribute" : false
- }
- }
- ]
- },
- {
- "trackIndex" : 1,
- "medias" : [
- ]
- }
- ]
- }
- }
- ]
- },
- "trackAttributes" : [
- {
- "ident" : "",
- "audioMuted" : false,
- "videoHidden" : false,
- "metadata" : {
- "IsLocked" : "False",
- "WinTrackHeight" : "56"
- }
- },
- {
- "ident" : "",
- "audioMuted" : false,
- "videoHidden" : false,
- "metadata" : {
- "IsLocked" : "False",
- "WinTrackHeight" : "56"
- }
- }
- ],
- "captionAttributes" : {
- "enabled" : true,
- "fontName" : "Arial",
- "fontSize" : 64,
- "backgroundColor" : [ 0, 0, 0, 191],
- "foregroundColor" : [ 255, 255, 255, 255],
- "lang" : "en",
- "alignment" : 0,
- "defaultFontSize" : true,
- "opacity" : 0.5,
- "backgroundEnabled" : true,
- "backgroundOnlyAroundText" : true
- },
- "backgroundColor" : [ 0, 0, 0, 255]
- },
- "metadata" : {
- "AutoSaveFile" : "C:\\Users\\fbapt\\AppData\\Local\\TechSmith\\Camtasia Studio\\9.0\\Auto-Saves\\Untitled Project68af9d3b.autosave.tscproj",
- "CanvasZoom" : 83,
- "Date" : "2018-05-05 04:37:12 PM",
- "IsAutoSave" : "0",
- "Language" : "ENU",
- "ProfileName" : "",
- "ProjectDimensionsChanged" : "1",
- "audioNarrationNotes" : "",
- "calloutStyle" : "Basic",
- "canvasDetached" : "False",
- "canvasPositionHeight" : "0",
- "canvasPositionLeft" : "0",
- "canvasPositionTop" : "0",
- "canvasPositionWidth" : "0"
- }
-}
diff --git a/Part 2/Section 07 - Project 3/nyc_parking_tickets_extract.csv b/Part 2/Section 07 - Project 3/nyc_parking_tickets_extract.csv
index 589d9c27..85f55732 100644
--- a/Part 2/Section 07 - Project 3/nyc_parking_tickets_extract.csv
+++ b/Part 2/Section 07 - Project 3/nyc_parking_tickets_extract.csv
@@ -888,7 +888,7 @@ Summons Number,Plate ID,Registration State,Plate Type,Issue Date,Violation Code,
7007488663,VFP7291,VA,PAS,3/2/2017,53,4DSD,ME/BE,53-Safety Zone
1402409825,869ZR9,MA,999,10/15/2016,53,SUBN,SATUR,
8506603031,2383103,IN,PAS,2/1/2017,53,TRAC,VOLVO,53-Safety Zone
-8480309064,51771JW,NY,COM,1/26/2017,64,VAN,INTER,"64-No STD Ex Con/DPL, D/S Dec"
+8480309064,51771JW,NY,COM,1/26/2017,64,VAN,INTER,64-No STD Ex Con/DPL
8162054819,EW866X,NJ,PAS,1/29/2017,68,4DSD,NISSA,68-Not Pkg. Comp. w Psted Sign
8343032536,4CMH482,CA,PAS,10/3/2016,68,SUBN,SUBAR,68-Not Pkg. Comp. w Psted Sign
8084034959,ASW2109,NY,PAS,12/20/2016,68,4DSD,TOYOT,68-Not Pkg. Comp. w Psted Sign
diff --git a/Part 2/Section 08 - Iteration Tools/01 - Aggregators/car-brands.txt b/Part 2/Section 08 - Iteration Tools/01 - Aggregators/car-brands.txt
index 4dfc3050..12abc7e4 100644
--- a/Part 2/Section 08 - Iteration Tools/01 - Aggregators/car-brands.txt
+++ b/Part 2/Section 08 - Iteration Tools/01 - Aggregators/car-brands.txt
@@ -8,7 +8,7 @@ Bugatti
Cadillac
Chevrolet
Chrysler
-Citro�n
+Citroen
Corvette
DAF
Dacia
diff --git a/Part 2/Section 09 - Project 4/project_4_description/Project - Description.ipynb b/Part 2/Section 09 - Project 4/project_4_description/Project - Description.ipynb
index 1f8e4da0..506d2e9a 100644
--- a/Part 2/Section 09 - Project 4/project_4_description/Project - Description.ipynb
+++ b/Part 2/Section 09 - Project 4/project_4_description/Project - Description.ipynb
@@ -48,11 +48,10 @@
"Create a single iterable that combines all the columns from all the iterators.\n",
"\n",
"The iterable should yield named tuples containing all the columns.\n",
- "Make sure that the SSN's across the files match!\n",
"\n",
- "All the files are guaranteed to be in SSN sort order, and every SSN is unique, and every SSN appears in every file.\n",
+ "Normally you should ensure that the SSN's match across all the files (i.e. identical row numbers in each file refer to the same SSN). However, in this case you do not need to do so as the data is already \"aligned\" - all the files are guaranteed to be in SSN sort order, every SSN is unique, and every SSN appears in every file.\n",
"\n",
- "Make sure the SSN is not repeated 4 times - one time per row is enough!"
+ "Just make sure that in your iterable the SSN is not repeated 4 times - one time per row is enough!"
]
},
{
@@ -154,7 +153,7 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
@@ -168,7 +167,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.6.2"
+ "version": "3.9.10"
}
},
"nbformat": 4,
diff --git a/Part 2/Section 11 - Project 5/01 - Description/Project 5 - Description.ipynb b/Part 2/Section 11 - Project 5/01 - Description/Project 5 - Description.ipynb
index 680d9825..f89d4ca4 100644
--- a/Part 2/Section 11 - Project 5/01 - Description/Project 5 - Description.ipynb
+++ b/Part 2/Section 11 - Project 5/01 - Description/Project 5 - Description.ipynb
@@ -169,11 +169,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The dialect of a CSV file refers to some of the specifics used to define data in a CSV file. The separators can be different (for example some failes use a comma, some use a semi-colon, some use a tab, etc).\n",
+ "The dialect of a CSV file refers to some of the specifics used to define data in a CSV file. The separators can be different (for example some files use a comma, some use a semi-colon, some use a tab, etc).\n",
"\n",
"Also, as we have seen before, a field is also sometimes delimited using quotes, or double quotes, or maybe some entirely different character.\n",
"\n",
- "When we have to deal with files that may be encoded using different dialects it can require quite a bit of work to determine what those specifics are. This is were the `Sniffer` class from the `csv` module can be useful. By providing it a sample fo the CSV file, it can analyze it and determine a best guess as to the specific dialect that was used. We can then use that dialect when we use the `csv.reader` function.\n",
+ "When we have to deal with files that may be encoded using different dialects it can require quite a bit of work to determine what those specifics are. This is where the `Sniffer` class from the `csv` module can be useful. By providing it a sample of the CSV file, it can analyze it and determine a best guess as to the specific dialect that was used. We can then use that dialect when we use the `csv.reader` function.\n",
"\n",
"Let's see how to use it with one of our files: `personal_info.csv`:"
]
diff --git a/Part 2/Section 14 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb b/Part 2/Section 14 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb
new file mode 100644
index 00000000..1e7fa9b4
--- /dev/null
+++ b/Part 2/Section 14 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb
@@ -0,0 +1,991 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c4d4fc49",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.10 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb1495a9",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.10 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.10.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "98c3ae0d",
+ "metadata": {},
+ "source": [
+ "Python 3.10 has improved it's error messages for syntax errors - the messages are more helpful and hopefully give you a better understanding of what may be syntactically wrong with your code."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ae4aa37",
+ "metadata": {},
+ "source": [
+ "#### Structural Pattern Matching"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d18177a2",
+ "metadata": {},
+ "source": [
+ "One thing I often hear people ask, is, what's the Python equivalent of a `switch` statement."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36a77514",
+ "metadata": {},
+ "source": [
+ "Until now, the answer has alwasy been - there isn't one. Use `if...elif` constructs."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "56fdb138",
+ "metadata": {},
+ "source": [
+ "Python 3.10 introduces a new language element (`match`) to implement something called **pattern matching**, that can be used to replicate this `switch` behavior you might be used to in other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e1cf8b9d",
+ "metadata": {},
+ "source": [
+ "I'll cover some of the basics here, but you should refer to the Python [docs](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement) for more information, as well as the [pep](https://peps.python.org/pep-0634/) for this feature and a [tutorial pep](https://peps.python.org/pep-0636/)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1417630a",
+ "metadata": {},
+ "source": [
+ "Let's start with a simple `match` statement:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "bbecc554",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\":\n",
+ " return \"Hmm, coffee!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm not scared of snakes!\"\n",
+ " case \"Rust\":\n",
+ " return \"Don't drink too much water!\"\n",
+ " case \"Go\":\n",
+ " return \"Collect $200\"\n",
+ " case _:\n",
+ " return \"I'm sorry...\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d5669e92",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm not scared of snakes!\""
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "90cecc86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Collect $200'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Go\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "f9feb023",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm sorry...\""
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"COBOL\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ee7c21fb",
+ "metadata": {},
+ "source": [
+ "Here we were able to define a \"default\" match pattern by using the underscore (`_`) as our pattern - this `_` is called a **wildcard**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b76575de",
+ "metadata": {},
+ "source": [
+ "So this is very much like the \"plain\" switch statement found in some other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e55dd9f",
+ "metadata": {},
+ "source": [
+ "But, this is where things get ineteresting, pattern matching can do much more than the simple example we just saw."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f8d495f2",
+ "metadata": {},
+ "source": [
+ "For example, you can have multiple pattern matching:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "6d5fcc0c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\" | \"Javascript\":\n",
+ " return \"Love those braces!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm a lumberjack and I don't need no braces\"\n",
+ " case _:\n",
+ " return \"I have no clue!\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "02cf21af",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Java\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "853368f3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Javascript\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "066f985e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm a lumberjack and I don't need no braces\""
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7fc43e7f",
+ "metadata": {},
+ "source": [
+ "We could match against one or more literals by using the OR pattern (`|`)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36064a9c",
+ "metadata": {},
+ "source": [
+ "Let's look at one more example, this time matching **multiple values**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "31978910",
+ "metadata": {},
+ "source": [
+ "Suppose we have some kind of command language for driving a remote controlled robot in a maze, picking up and dropping items as it moves around. Our robot is very simple, it can move in only a few directions, and one step at a time. So to move forward three spaces, we would issue three `move forward` commands.\n",
+ "\n",
+ "Additional commands are `move backward`, `move left`, `move right`. We also have a few other commands our robot understands: `pick` and `drop` for picking up and dropping objects it might find."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63944ea5",
+ "metadata": {},
+ "source": [
+ "We might write a command interpreter this way:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f9077f13",
+ "metadata": {},
+ "source": [
+ "Let's start by using some symbols to represent the robot's actions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "2dde5d86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'F': '→', 'B': '←', 'L': '↑', 'R': '↓', 'pick': '⤣', 'drop': '⤥'}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "symbols = {\n",
+ " \"F\": \"\\u2192\", \n",
+ " \"B\": \"\\u2190\", \n",
+ " \"L\": \"\\u2191\", \n",
+ " \"R\": \"\\u2193\", \n",
+ " \"pick\": \"\\u2923\", \n",
+ " \"drop\": \"\\u2925\"\n",
+ "}\n",
+ "\n",
+ "symbols"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "faab4c09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case \"move F\":\n",
+ " return symbols[\"F\"]\n",
+ " case \"move B\":\n",
+ " return symbols[\"B\"]\n",
+ " case \"move L\":\n",
+ " return symbols[\"L\"]\n",
+ " case \"move R\":\n",
+ " return symbols[\"R\"]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24555fab",
+ "metadata": {},
+ "source": [
+ "Then we could issue commands such as:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b673a044",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"move L\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b411438f",
+ "metadata": {},
+ "source": [
+ "Or multiple sequences by maybe using a list of such commands, effectively creating a sequential program for our robot:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "cf94014f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['→', '→', '↑', '⤣', '↓', '↑', '→', '⤥']"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op(\"move F\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"pick\"),\n",
+ " op(\"move R\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c520053b",
+ "metadata": {},
+ "source": [
+ "We could use something called **capturing** matched sub-patterns to simply our code somewhat:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "e7da20cf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case [\"move\", (\"F\" | \"B\" | \"L\" |\"R\") as direction]:\n",
+ " return symbols[direction]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symvols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "c2a1c617",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op([\"move\", \"L\"])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4edeb3dc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'⤣'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"pick\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "b13504aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "fly does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op(\"fly\")\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6769c228",
+ "metadata": {},
+ "source": [
+ "This is kind of tedious, it would be nicer to write commands such as `move F F L` and `move R L F` instead."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "055d2c60",
+ "metadata": {},
+ "source": [
+ "There are many ways we could solve this, but pattern matching on multiple values can be really useful here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "372bdb17",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions]:\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c77bec44",
+ "metadata": {},
+ "source": [
+ "What happens here is that the pattern matcher will recognize the first word `move` and then interpret the remaining words collection them in the `directions` variable (so this syntax is very similar to unpacking)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ef78058",
+ "metadata": {},
+ "source": [
+ "We can now rewrite our program this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "88c0c024",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('→', '→', '↑'), '⤣', ('↓', '↑', '→'), '⤥']"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op([\"move\", \"F\", \"F\", \"L\"]),\n",
+ " op(\"pick\"),\n",
+ " op([\"move\", \"R\", \"L\", \"F\"]),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ddc0f2e",
+ "metadata": {},
+ "source": [
+ "But now we have a slight problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "ed30a762",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " 'up'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f6bbbd53",
+ "metadata": {},
+ "source": [
+ "We would rather just get our custom `ValueError`. To do this we can place a **guard** on our `case` for the `move` command, that will not only do the match but also test an additional condition:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8d441175",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions] if set(directions) < symbols.keys():\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "441a53f6",
+ "metadata": {},
+ "source": [
+ "That `if ` statement (the **guard**) will only let the case block execute if the match is true **and** that `if` expression evaludates to `True`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "708c5d16",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " ['move', 'up'] does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ecf5f83",
+ "metadata": {},
+ "source": [
+ "There are many other ways we could have done this - probably better than this, but this was to illustrate how the multiple value matching can work!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84bec678",
+ "metadata": {},
+ "source": [
+ "I urge you to read at least this [tutorial (pep 636)](https://peps.python.org/pep-0636/) on pattern matching."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5b6a7b09",
+ "metadata": {},
+ "source": [
+ "#### The `zip` Function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1294e5f6",
+ "metadata": {},
+ "source": [
+ "We use the built-in `zip` function all the time. As we know, the `zip` will stop iterating after the first of the iterables provided in the arguments is exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "e33aa60d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30)]"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = ['a', 'b', 'c']\n",
+ "l2 = [10, 20, 30, 40]\n",
+ "\n",
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7d310af8",
+ "metadata": {},
+ "source": [
+ "As you can see the last element of `l2` is not included in the result since `l1` only had three elements."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9cf9570",
+ "metadata": {},
+ "source": [
+ "We can also use the `zip_longest` function in the `itertools` module to iterate over the longest iterable, providing some default value for any other iterable that has been exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "aefa3055",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from itertools import zip_longest"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "ce4779c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30), ('???', 40)]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip_longest(l1, l2, fillvalue='???'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0eb2f702",
+ "metadata": {},
+ "source": [
+ "But what if we want to only zip iterables that have the **same** length? We would need to test the length of each iterable first - but if those were iterators instead of iterables, we will have exhausted the iterator, and `zip` would come back \"empty\":"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "3b704410",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da0d866f",
+ "metadata": {},
+ "source": [
+ "We could test to see if `l1` and `l2` are the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "bc7d34c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "len(list(l1)) == len(list(l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0a4a1974",
+ "metadata": {},
+ "source": [
+ "But, if we now try to `zip` them:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "1c3928b9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[]"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ee310e9",
+ "metadata": {},
+ "source": [
+ "In Python 3.10, the `zip` function now has a keyword-only parameter called `strict` that will just do the zip, but throw an exception if one of the arguments get exhausted before the others:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "54722489",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "zip() argument 2 is shorter than argument 1\n"
+ ]
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))\n",
+ "\n",
+ "try:\n",
+ " list(zip(l1, l2, strict=True))\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2635211a",
+ "metadata": {},
+ "source": [
+ "And works just fine if the arguments all have the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "7fb672cb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[(0, 0, 0), (1, 1, 1), (4, 8, 16), (9, 27, 81)]"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(4))\n",
+ "l3 = (i ** 4 for i in range(4))\n",
+ "\n",
+ "list(zip(l1, l2, l3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "501fec3b",
+ "metadata": {},
+ "source": [
+ "So why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dab4260e",
+ "metadata": {},
+ "source": [
+ "In **many** cases, our code zips iterables that we expect to be of the same length. To avoid bugs in our program, we should check that this condition is true, otherwise zip will silently just zip based on the shortest one. But as we saw with iterators, that can be difficult to do without exhausting the very iterators we are trying to zip. (it can be done, it's just more code)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c73e5ad1",
+ "metadata": {},
+ "source": [
+ "So, if you are one of the lucky devs that gets to write Python 3.10 (or higher :-) ) code, you can just use `strict` whenever you zip things together and expect that they are all of the same length. Much easier to do it this way (and, as we discuss in Exception handling, falls into the category of \"ask forgiveness later\" which we saw was the preferred way (in general) to handle exceptions in our apps, as opposed to the \"look before you leap\" approach we would have to use to test the argument lengths."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "400a56c1",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 2/Section 14 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb b/Part 2/Section 14 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb
new file mode 100644
index 00000000..698dadce
--- /dev/null
+++ b/Part 2/Section 14 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb
@@ -0,0 +1,2343 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c45f0998",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.9 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2e965eba",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.9 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.9.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "39255227",
+ "metadata": {},
+ "source": [
+ "#### Time Zones"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "26750adb",
+ "metadata": {},
+ "source": [
+ "We don't cover 3rd party libraries in this course, but if you've worked with Python in a production environment, you will likely have come across the dreaded timezone and Daylight Savings issues that plague datetimes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7cdfe8a5",
+ "metadata": {},
+ "source": [
+ "Most likely you will have resorted to using the `pytz` and `python-dateutil` libraries to help with that."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bc000883",
+ "metadata": {},
+ "source": [
+ "Now, Python 3.9 is proud to introduce the `zoneinfo` module to deal with timezones properly. About time too!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c2d652dd",
+ "metadata": {},
+ "source": [
+ "For full info on this, refer to [PEP 615](https://peps.python.org/pep-0615/).\n",
+ "\n",
+ "And the Python [docs](https://docs.python.org/3.9/library/zoneinfo.html#module-zoneinfo).\n",
+ "\n",
+ "**Windows Users**: you will likely need to add a dependency on the `tzdata` [library](https://pypi.org/project/tzdata/) for the IANA time zone database. See [this note](https://docs.python.org/3.9/library/zoneinfo.html#data-sources)\n",
+ "\n",
+ "You should also take a look at this [presentation](https://pganssle-talks.github.io/chipy-nov-2020-zoneinfo/#/) by Paul Ganssle who wrote that module - very interesting read!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "80255944",
+ "metadata": {},
+ "source": [
+ "Let's look at how we might have handled timezone and DST using `pytz` and `dateutil`, and contrast that to how we can use the new `zoneinfo` module instead."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "ec129288",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import zoneinfo\n",
+ "from datetime import datetime, timezone\n",
+ "from zoneinfo import ZoneInfo\n",
+ "\n",
+ "import dateutil\n",
+ "import pytz"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "beadc4e2",
+ "metadata": {},
+ "source": [
+ "Let's list out all the defined time zones:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d0058e73",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in pytz.all_timezones:\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f18fa2c9",
+ "metadata": {},
+ "source": [
+ "With the `zoneinfo` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "9d2cf9d1",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "Factory\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in sorted(zoneinfo.available_timezones()):\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a1887cf",
+ "metadata": {},
+ "source": [
+ "Are the time zones defined by `pytz` and `zoneinfo` the same? Yes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8f8df276",
+ "metadata": {},
+ "source": [
+ "In this example, let's take our current time in UTC, and convert it to some other time zone, say `Australia/Melbourne`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77f1b8d9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "now_utc_naive = datetime.utcnow()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "f8586215",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_naive"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a452220a",
+ "metadata": {},
+ "source": [
+ "The problem here is that we have a _naive_ datetime (i.e. one without an attached timezone)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d1d10809",
+ "metadata": {},
+ "source": [
+ "We can make this naive datetime time zone aware by tacking on the timezone (since we know it is UTC):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "db60736b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware = now_utc_naive.replace(tzinfo=timezone.utc)\n",
+ "now_utc_aware"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8282b097",
+ "metadata": {},
+ "source": [
+ "Or, we could use the `pytz` library to do the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "0d7434f7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 377626, tzinfo=)"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pytz.utc.localize(datetime.utcnow())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e613c2e1",
+ "metadata": {},
+ "source": [
+ "Now that we have a time zone aware datetime, we can convert it to another timezone using `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "94b0b5c9",
+ "metadata": {},
+ "source": [
+ "First, let's pick a time zone from `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "833b5ff9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_melbourne = pytz.timezone('Australia/Melbourne')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ce4323c1",
+ "metadata": {},
+ "source": [
+ "And now we localize our aware datetime to this time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "d23fd3c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_melbourne)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "260bd7ff",
+ "metadata": {},
+ "source": [
+ "We could do both these steps in a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "6559daf7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(pytz.timezone('Australia/Melbourne'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6be99718",
+ "metadata": {},
+ "source": [
+ "Now, let's do the same thing using the `zoneinfo` module."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8c9b22bb",
+ "metadata": {},
+ "source": [
+ "Let's pick the same target time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "30c58db3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_zi_dublin = ZoneInfo(\"Europe/Dublin\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f77b5b0",
+ "metadata": {},
+ "source": [
+ "And the let's convert our aware datetime to that time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "1623322d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_zi_dublin)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4536470f",
+ "metadata": {},
+ "source": [
+ "Or, we can also write this as a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "337c3955",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(ZoneInfo(\"Europe/Dublin\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4076195d",
+ "metadata": {},
+ "source": [
+ "#### The `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "41d86e28",
+ "metadata": {},
+ "source": [
+ "Several enhancements or additions have been to the math library."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bd3de95f",
+ "metadata": {},
+ "source": [
+ "The `math` module already had the `gcd` function to calculate the great common divisor of two numbers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "911df27e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4154629e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "9"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85abe1fa",
+ "metadata": {},
+ "source": [
+ "But now `gcd` can take multiple arguments, not just two:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "d64ea0d9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45, 18, 15)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0503d78a",
+ "metadata": {},
+ "source": [
+ "The `lcm` (least common multiple) function has been added:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "b4c25fef",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "12"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.lcm(2, 3, 4)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "58a4c3cd",
+ "metadata": {},
+ "source": [
+ "#### Dictionary Unions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2c05f130",
+ "metadata": {},
+ "source": [
+ "When we discussed dictionaries in this course, we saw that we could combine two dictionaries using unpacking:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "136c8836",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'a': 1, 'b': 2, 'c': 3}\n",
+ "d2 = {'c': 30, 'd': 40}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "81331802",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "{**d1, **d2}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "97ca030f",
+ "metadata": {},
+ "source": [
+ "As we saw the second dictionary's key/value pair \"overwrote\" the key/value pair from the first dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b361771e",
+ "metadata": {},
+ "source": [
+ "We could also use the `ChainMap` function in the `collections` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "d633f16c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import ChainMap"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "ad250dfd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "merged = ChainMap(d1, d2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "1deeb8f2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 3, 40)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "merged['a'], merged['c'], merged['d']"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1751d47a",
+ "metadata": {},
+ "source": [
+ "As you can see, in the `ChainMap`, the firest occurrence of the key is used - so in this case `c` comes from `d1`, not `d2`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1c63e893",
+ "metadata": {},
+ "source": [
+ "Both of these ways of \"combining\" dictionaries work well - but they are not very intuitive, and need a little attention to what happens when you have common keys in the dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aca5787b",
+ "metadata": {},
+ "source": [
+ "Think of concatenating lists where we can simply use the `+` operator - this is very intuitive:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "de850747",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69429bab",
+ "metadata": {},
+ "source": [
+ "Now dictionaries are not like lists, but they are closely related to **sets**. With sets, we have the **union** operator (`|`):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "dcb8a7b5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a', 'b', 'c', 'd'}"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "s1 = {'a', 'b', 'c'}\n",
+ "s2 = {'c', 'd'}\n",
+ "\n",
+ "s1 | s2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "32c20dfb",
+ "metadata": {},
+ "source": [
+ "Python 3.9 introduces support for the **union** (`|`) operation between dictionaries as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "af3fcc01",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "851ffadc",
+ "metadata": {},
+ "source": [
+ "Just like with the `{**d1, **d2}` approach, the value for `c` came from the second dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb6fc060",
+ "metadata": {},
+ "source": [
+ "And just like with that technique we can control this by switching the order of the dictionaries in the union:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "05555100",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 3, 'd': 40, 'a': 1, 'b': 2}"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d2 | d1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "739e210f",
+ "metadata": {},
+ "source": [
+ "One question we should have, is what happens to the insertion order that Python dictionaries now guarantee?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "f8759da5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'c': 3, 'a': 1, 'b': 2}\n",
+ "d2 = {'d': 40, 'c': 30}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "e06e3966",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 30, 'a': 1, 'b': 2, 'd': 40}"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8e0e1c2e",
+ "metadata": {},
+ "source": [
+ "As you can see, even though the **value** for `c` came from the **second** dictionary, the original inertion order of the **keys** is maintained, so `c` is still in first position in the union of the two dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e12dee6a",
+ "metadata": {},
+ "source": [
+ "#### String Methods"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f69f79e4",
+ "metadata": {},
+ "source": [
+ "Often we need to remove some prefix or suffix in a string."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "67496793",
+ "metadata": {},
+ "source": [
+ "For example, we may have this list of string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "9da4cabe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data = [\n",
+ " \"(log) [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "30de1de8",
+ "metadata": {},
+ "source": [
+ "And we want to clean these up and remove the `(log) ` prefix (including the space)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84a6c502",
+ "metadata": {},
+ "source": [
+ "We can certainly do it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "8a60ecdc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "45fa082e",
+ "metadata": {},
+ "source": [
+ "You might be tempted to use the `lstrip` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "74e60a43",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5e045ebc",
+ "metadata": {},
+ "source": [
+ "This appears to work, but `lstrip` (and `rstrip`) does not interpet `\"(log )\"` as a string, but rather a **sequence** of characters, and each one will be removed - so you might end up with this problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "ddc6e3a8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data2 = [\n",
+ " \"(log) log: [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) log: [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) log: [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) log: [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "d87cd3c5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[': [2022-03-01T13:30:01] Log record 1',\n",
+ " ': [2022-03-01T13:30:02] Log record 2',\n",
+ " ': [2022-03-01T13:30:03] Log record 3',\n",
+ " ': [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f73aac3",
+ "metadata": {},
+ "source": [
+ "Now that removed a lot more than expected everything from those strings, unlike the replace, which will replace only the first occurrence by default:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "eaf8792b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 34,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0aca0211",
+ "metadata": {},
+ "source": [
+ "Python 3,9 introduces two new string methods to do this without having to use `replace`, namely the `removeprefix()` and `removesuffix()` methods:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "b320eb46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "d4ebaf46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data2\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f7a2ffd4",
+ "metadata": {},
+ "source": [
+ "Note that if the prefix (or suffix) is not found, nothing happens, the new string will be the same as the original (i.e. no exception is raised):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "829cb63b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Python rocks!'"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'Python rocks!'.removeprefix('Java')"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 2/Section 14 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb b/Part 2/Section 14 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb
new file mode 100644
index 00000000..53e8b672
--- /dev/null
+++ b/Part 2/Section 14 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb
@@ -0,0 +1,1082 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "17ad44da",
+ "metadata": {},
+ "source": [
+ "### Python 3.8 - Assignment Expressions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "40b0045a",
+ "metadata": {},
+ "source": [
+ "Another enhancement to the Python core language that was introduced in Python 3.8 is **assignment expressions**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cad52d44",
+ "metadata": {},
+ "source": [
+ "You can see the pep for it here: [pep 572](https://peps.python.org/pep-0572/)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "285f5b11",
+ "metadata": {},
+ "source": [
+ "Remember that an expression is simply a snippet of code that is evaluated.\n",
+ "\n",
+ "The following are all examples of expressions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "357659ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "c7b05302",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "a68603b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'PYTHON'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "201b3156",
+ "metadata": {},
+ "source": [
+ "And an assignment is simply when we assign an expression result to a variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "b08e7b15",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2\n",
+ "b = [1, 2, 3] + [4, 5, 6]\n",
+ "c = \" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "54232d7a",
+ "metadata": {},
+ "source": [
+ "As you can see, we have to different steps here.\n",
+ "\n",
+ "We assign the result of an expression (the right hand side) to a variable (the left hand side) using the equals (`=`) sign."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e0ca1920",
+ "metadata": {},
+ "source": [
+ "So we have two **distinct** (totally separate) aspects here - the expression, and the assignment."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "90b2d0ab",
+ "metadata": {},
+ "source": [
+ "So what are **expression assignments**?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2065f05",
+ "metadata": {},
+ "source": [
+ "Expression assignments allows us to assign expressions to a variable **inside** an expression, using the `:=` operator (the so-called *walrus* operator)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0c400c75",
+ "metadata": {},
+ "source": [
+ "Confusing? :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "084caec6",
+ "metadata": {},
+ "source": [
+ "Let's take a look at a very simple example first:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "985d592b",
+ "metadata": {},
+ "source": [
+ "Starting with an expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "c9b56fb0",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b89a8762",
+ "metadata": {},
+ "source": [
+ "We could assign the result of that expression to some variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "225ca5f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1513437a",
+ "metadata": {},
+ "source": [
+ "But, we could also write the expression and assignment this way (not the parentheses that enclose the expression):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "572aaf6a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8d0e2885",
+ "metadata": {},
+ "source": [
+ "With the expression assignment operator, we could actually assign the result of that expression inside the expression itself:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "0fa9c199",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(x := 1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1eafbee8",
+ "metadata": {},
+ "source": [
+ "As you can see, the expression returned a result (`3`), but it also assigned that result to the variable `x`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "915d5b48",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e35a8501",
+ "metadata": {},
+ "source": [
+ "Note that the parentheses in this case are **necessary** - simply writing this would not work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "890070de",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "SyntaxError",
+ "evalue": "invalid syntax (746607632.py, line 1)",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;36m Input \u001b[0;32mIn [10]\u001b[0;36m\u001b[0m\n\u001b[0;31m x := 1 + 2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
+ ]
+ }
+ ],
+ "source": [
+ "x := 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d0b5f281",
+ "metadata": {},
+ "source": [
+ "This is because the `:=` operator must be used inside an **expression**, so we can force it by using the parentheses."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3195a0a8",
+ "metadata": {},
+ "source": [
+ "We could even do this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "6d1e232c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (x := 10 + 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "35a7ed36",
+ "metadata": {},
+ "source": [
+ "Then, `a`, and `x` are:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "96bf1532",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(30, 30)"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a, x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "638c195a",
+ "metadata": {},
+ "source": [
+ "Yeah, even more confusing! But in a minute I'll show you why this can be very useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a625536",
+ "metadata": {},
+ "source": [
+ "Before we move on to that, let's see how this assignment expression works when we deal with mutable objects such as lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "a2ee53ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (l2 := [1, 2] + [3, 4])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e58d69f",
+ "metadata": {},
+ "source": [
+ "Here, `l1` was the result of the concatenation of the two lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "2d3ae1a4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1, id(l1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "88aee44a",
+ "metadata": {},
+ "source": [
+ "But what about `l2`? It should be a list with the same values, but is it the same object reference as `l1`?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "fc8fe138",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l2, id(l2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "243f0d28",
+ "metadata": {},
+ "source": [
+ "And indeed, they are not only the same values, but the same object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e7268ec5",
+ "metadata": {},
+ "source": [
+ "Usually this is not an issue, but keep it in mind because you end up with shared references that you may not realize exist."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e27c849e",
+ "metadata": {},
+ "source": [
+ "So now, why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a57d9679",
+ "metadata": {},
+ "source": [
+ "Often, we end up writing expressions in terms of other sub expressions, not just for clarity, but sometimes to **avoid repeating** function calls or expression evaluations."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9a686538",
+ "metadata": {},
+ "source": [
+ "#### Example 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3131d1f1",
+ "metadata": {},
+ "source": [
+ "Suppose we have some long running function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "f66dd3b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import time\n",
+ "import math\n",
+ "\n",
+ "def slow_function(x, y):\n",
+ " time.sleep(0.5)\n",
+ " return round(math.sqrt(x**2 + y**2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ddce261",
+ "metadata": {},
+ "source": [
+ "Now executing this function will take about 2 seconds to run every time it is called, even when calling it with the same values (we could of course use some LRU caching, but only if the function is **deterministic** - if the function is reading data from a web site, or a database, the result for the same arguments may not be the same and so LRU caching is not even a viable option in this case).\n",
+ "\n",
+ "> A **deterministic** function is a function that for the **same** inputs, always returns the **same** result:\n",
+ ">\n",
+ "> Obviously the function we have above is deterministic, but this one would not be:\n",
+ ">```\n",
+ ">def get_price(symbol):\n",
+ "> # query an API for latest price for symbol\n",
+ "> price = ...\n",
+ "> return price\n",
+ ">``` \n",
+ "> A function that returns the current date or time, or a random number, etc are all non-deterministic functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e503d9b",
+ "metadata": {},
+ "source": [
+ "So, LRU caching is not always an option."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "05027bcc",
+ "metadata": {},
+ "source": [
+ "Let's see an example of why we would want to assign the result of our long running function to a variable, instead of just using it directly."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "a9babf8f",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "from time import perf_counter\n",
+ "\n",
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " if slow_function(i, i) % 2 == 0:\n",
+ " even_results.append(slow_function(i, i))\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3bdd4e15",
+ "metadata": {},
+ "source": [
+ "Well that was painfully slow!\n",
+ "\n",
+ "But notice that we are calling the same function, with the same arguments twice - we can eliminate that!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "19453896",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " result = slow_function(i, i)\n",
+ " if result % 2 == 0:\n",
+ " even_results.append(result)\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b6091cb",
+ "metadata": {},
+ "source": [
+ "So we are able to speed this code up, by using that interim `result` variable - also note how `result` is basically a throw away variable (we typically would not use such a variable outside the loop itself - exceptions happen of course)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8acf631f",
+ "metadata": {},
+ "source": [
+ "But notice something about that code? It's ugly looking - we are building up a list by running through a loop and adding to an initially empty list, one element at a time."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6293f28c",
+ "metadata": {},
+ "source": [
+ "We can do better! List comprehensions of course."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9cdff5a7",
+ "metadata": {},
+ "source": [
+ "But... we can't write that `result = slow_function(i, i)` in our list comprehension - so we would be back to the original (and slower) may of doing it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0d89b92d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " slow_function(i, i)\n",
+ " for i in range(10)\n",
+ " if slow_function(i, i) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8db81b84",
+ "metadata": {},
+ "source": [
+ ":-("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6c42d90a",
+ "metadata": {},
+ "source": [
+ "And this is where the assignment expression operator comes in very handy:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "eefb7ce7",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " result\n",
+ " for i in range(10)\n",
+ " if (result := slow_function(i, i)) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c1c77b0c",
+ "metadata": {},
+ "source": [
+ "Notice how using the `:=` operator, we assign the result of `slow_function(i, i)` to `result` as part of the expression itself, and then re-use that computed value for the elements of the list."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9e3744d",
+ "metadata": {},
+ "source": [
+ "You may be asking yourself, why not write it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "db2bc22b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "cd112bb8",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'result' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m result \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mresult\u001b[49m \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "\u001b[0;31mNameError\u001b[0m: name 'result' is not defined"
+ ]
+ }
+ ],
+ "source": [
+ "even_results = [\n",
+ " (result := slow_function(i, i))\n",
+ " for i in range(10)\n",
+ " if result % 2 == 0\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5c0229a0",
+ "metadata": {},
+ "source": [
+ "This happens because in a list comprehension, the loop starts running, then the `if` clause (if any) is evaluated, and then the element expression is evaluated - hence why we place the assignment expression in the `if`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cc652ad3",
+ "metadata": {},
+ "source": [
+ "**Example 2**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "093978ca",
+ "metadata": {},
+ "source": [
+ "Here's another scenario where this new operator could be quite useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "edbdc1b7",
+ "metadata": {},
+ "source": [
+ "You want to return the result of an expression but only if it satisfies some criteria.\n",
+ "\n",
+ "For example, let's say we write a generator function to produce n even random integers between 1 and 10:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "a75a9138",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import random\n",
+ "\n",
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while cnt <= n:\n",
+ " cnt += 1\n",
+ " number = random.randint(0, 10)\n",
+ " if number % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9f19d723",
+ "metadata": {},
+ "source": [
+ "We can then call the generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "53f19b5e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76ac9cf0",
+ "metadata": {},
+ "source": [
+ "We can make our code a little more concise without losing readability by using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "b849d145",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while (cnt := cnt + 1) <= n:\n",
+ " if (number := random.randint(0, 10)) % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "b847739e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5621f621",
+ "metadata": {},
+ "source": [
+ "#### Example 3"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e1719fd",
+ "metadata": {},
+ "source": [
+ "Here's another example where we are consuming some generator, until some condition is met."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9822e4d5",
+ "metadata": {},
+ "source": [
+ "Let's write a generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "623069a1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def gen():\n",
+ " while True:\n",
+ " yield list(range(random.randint(0, 10)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da617a93",
+ "metadata": {},
+ "source": [
+ "And let's print out a frew values from this generator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "56b83447",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[]\n",
+ "[0]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4, 5, 6, 7]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "for _ in range(10):\n",
+ " print(next(my_gen))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ad1bb10e",
+ "metadata": {},
+ "source": [
+ "You'll notice that the fourth element is a list with 2 values.\n",
+ "\n",
+ "What we want to do now, is process the lists yielded by the generator, until we hit a list with two values, at which point we want to stop processing it."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "25d4dab3",
+ "metadata": {},
+ "source": [
+ "We could do it this way with a `while` loop:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "f5a068ab",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while True:\n",
+ " l = next(my_gen)\n",
+ " if len(l) <= 2:\n",
+ " break\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fcf1f1a2",
+ "metadata": {},
+ "source": [
+ "Instead, we could re-write this way using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "7568cf9c",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while len(l := next(my_gen)) > 2:\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d9f1b587",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 2/Section 14 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb b/Part 2/Section 14 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
new file mode 100644
index 00000000..699f8626
--- /dev/null
+++ b/Part 2/Section 14 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
@@ -0,0 +1,1476 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c314393b",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.8 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cbe45497",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.8 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.8.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7089277d",
+ "metadata": {},
+ "source": [
+ "#### Positional Only Parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "61154c87",
+ "metadata": {},
+ "source": [
+ "It is now possible to define **positional-only** parameters for Python functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63037bda",
+ "metadata": {},
+ "source": [
+ "As we saw earlier in this course, when you define positional parameters in a function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "13c1ba59",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4928079",
+ "metadata": {},
+ "source": [
+ "the user is free to pass arguments either positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "0bb6fea5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "be1cfa90",
+ "metadata": {},
+ "source": [
+ "or, as named arguments:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "cb04e54f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(b=2, a=1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "617077dd",
+ "metadata": {},
+ "source": [
+ "Some functions in Python's built-ins ared defined in such a way that certain parameters can **only** be passed positionally, for example the `print` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77c6fa8a",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on built-in function print in module builtins:\n",
+ "\n",
+ "print(...)\n",
+ " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
+ " \n",
+ " Prints the values to a stream, or to sys.stdout by default.\n",
+ " Optional keyword arguments:\n",
+ " file: a file-like object (stream); defaults to the current sys.stdout.\n",
+ " sep: string inserted between values, default a space.\n",
+ " end: string appended after the last value, default a newline.\n",
+ " flush: whether to forcibly flush the stream.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(print)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "248c2581",
+ "metadata": {},
+ "source": [
+ "That `value` cannot be passed by name:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "529c5dac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "'value' is an invalid keyword argument for print()\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(value=\"hello\")\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f4baed67",
+ "metadata": {},
+ "source": [
+ "Instead, the parameter **must** be passed positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "8c147557",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2840374",
+ "metadata": {},
+ "source": [
+ "Until Python 3.8, it was not possible to reproduce such behavior with user-defined functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "158674a9",
+ "metadata": {},
+ "source": [
+ "Now you can, by using the slash character(`/`). Parameters defined **before** the `/` become **positional-only** parameters:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "aeebd0f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "858727b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "4f73c741",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "my_func() got some positional-only arguments passed as keyword arguments: 'a, b'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " my_func(a=1, b=2)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f5967700",
+ "metadata": {},
+ "source": [
+ "You can of course mix this along with the special parameters `*` and `**`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "d17254b3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /, *, c):\n",
+ " print(a + b + c)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b35d884e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "13\n"
+ ]
+ }
+ ],
+ "source": [
+ "my_func(1, 2, c=10)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "573aca30",
+ "metadata": {},
+ "source": [
+ "#### f-string Enhancements"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "89ee51f9",
+ "metadata": {},
+ "source": [
+ "Often we use f-strings to interpolate the name of a variable and it's value:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "f79a630b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "a, b = \"hello\", \"world\"\n",
+ "print(f\"a={a}, b={b}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24747607",
+ "metadata": {},
+ "source": [
+ "Python 3.8 provides a shortcut way of doing the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "3ae5c0c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a='hello', b='world'\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=}, {b=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "141558b4",
+ "metadata": {},
+ "source": [
+ "You can even use [format specifiers](https://docs.python.org/3/library/string.html#formatspec)\n",
+ "to further customize the output:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "e75716ac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=:s}, {b=:s}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4dcdc5d0",
+ "metadata": {},
+ "source": [
+ "Or when dealing with other types:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "362bf6b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime\n",
+ "from math import pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "c91b7536",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = datetime.utcnow()\n",
+ "e = pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "545c77a2",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=datetime.datetime(2022, 3, 20, 6, 1, 13, 990493), e=3.141592653589793\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=}, {e=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4637ecd5",
+ "metadata": {},
+ "source": [
+ "And applying some format specifiers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "75c4052b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=2022-03-20 06:01:13, e=3.142\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=:%Y-%m-%d %H:%M:%S}, {e=:.3f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "076773ed",
+ "metadata": {},
+ "source": [
+ "It will even display the text of an expression if you use one in your f-string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0ce46ace",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1 + 2=3, ' '.join(sentence)='Python rocks!'\n"
+ ]
+ }
+ ],
+ "source": [
+ "sentence = [\"Python\", \"rocks!\"]\n",
+ "print(f\"{1 + 2=}, {' '.join(sentence)=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e3783ea",
+ "metadata": {},
+ "source": [
+ "#### The `as_integer_ratio()` Method"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "15ccd5ad",
+ "metadata": {},
+ "source": [
+ "The types `bool`, `int` and `Fraction` now all implement an `as_integer_ratio()` method which returns a tuple consisting of the numerator and denominator. Remember that `Decimal` and `float` already implement the same method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8313fc80",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from fractions import Fraction"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "7a1ae84a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "f = Fraction(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "a94fc3ed",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(2, 3)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "f.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "f32942ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(12, 1)"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 12\n",
+ "a.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "06980a8c",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 1)"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "flag = True\n",
+ "flag.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a3091e0e",
+ "metadata": {},
+ "source": [
+ "The advantage of this is mainly for polymorphism (or duck-typing), where you can now use `as_integer_ratio` irrespective of whether the variable is a `bool`, an `int`, a `float`, a `Decimal` or a `Fraction`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "8a362bf8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from decimal import Decimal"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "ab4a78aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(33, 100)"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Decimal(\"0.33\").as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "5ee29a47",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(7070651414971679, 2251799813685248)"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(3.14).as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "df1e85de",
+ "metadata": {},
+ "source": [
+ "#### The `lru_cache` decorator"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "226efb47",
+ "metadata": {},
+ "source": [
+ "As we saw in this course, we can use the `lru_cache` decorator to appky an LRU cache to our functions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "20501526",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import lru_cache"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "07d699f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache(maxsize=3)\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "45a0cd5a",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fea747d4",
+ "metadata": {},
+ "source": [
+ "If we don't specify `maxsize`, it will default to `128`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "447be276",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache()\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "53fee4fd",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5cf8e33a",
+ "metadata": {},
+ "source": [
+ "The change made to this decorator in Python 3.8 allows us not to use those empty parentheses:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "4185658b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76a9aed5",
+ "metadata": {},
+ "source": [
+ "#### `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0af410c0",
+ "metadata": {},
+ "source": [
+ "Many examples I use throughout this course calculate the Euclidean distance between two points:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "b511addc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "0b66c006",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1.4142135623730951\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = (0, 0)\n",
+ "b = (1, 1)\n",
+ "\n",
+ "dist = math.sqrt((b[0] - a[1]) ** 2 + (b[1] - a[1]) ** 2)\n",
+ "print(dist)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d276589d",
+ "metadata": {},
+ "source": [
+ "Now, it's much easier using the `dist()` function the `math` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "1f774757",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1.4142135623730951"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.dist(a, b)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "13afb1f1",
+ "metadata": {},
+ "source": [
+ "#### The `namedtuple` Implementation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a22a839e",
+ "metadata": {},
+ "source": [
+ "Actually these changes were added to Python 3.7, but since I don't have a separate lecture for Python 3.7 changes (most did not apply to this course), here it is."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1a579fbb",
+ "metadata": {},
+ "source": [
+ "The `_source` attribute was **removed**. There quite a discussion on this, and the the core dev who implemented and supported this essentially gave up trying to keep this in - it was deemed to cause too much \"overhead\". So, sadly (wearing my teacher's hat), it is gone. It is no more. It's not pining, it's just dead. :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d5e3bfd0",
+ "metadata": {},
+ "source": [
+ "The method I showed you for defining defaults for named tuples still works, and could still be used, but Python 3.7 added the `defaults` parameter to the named tuple definition."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "3538a2c2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import namedtuple"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "id": "024bcc51",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults=(10, 20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "id": "9dd8a877",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "id": "db7f47e7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 40,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fb0bc811",
+ "metadata": {},
+ "source": [
+ "You don't have to specify defaults for everything, but if you do not, be aware that defaults will be applied from **right** to **left**. Which makes sense given that in Python non-defaulted parameters must be defined **before** defaulted parameters."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "id": "8f6ad2ca",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = (20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "id": "bc9d5345",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "id": "eceeaec2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "64188b1c",
+ "metadata": {},
+ "source": [
+ "Note that with this way of specifying defaults you can easily define the same default for all items in the named tuple using the `*` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "id": "8b36d7c3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c d e f\", defaults=(\"xyz\",) * 6)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "id": "1d448806",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "id": "b16758de",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a='xyz', b='xyz', c='xyz', d='xyz', e='xyz', f='xyz')"
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bbcbaf53",
+ "metadata": {},
+ "source": [
+ "Just be careful if you use a **mutable** type to do this!!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "id": "91b28470",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = ([],) * 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "id": "cad11f5c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "id": "0cb7ceac",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[], b=[], c=[])"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "id": "466d9520",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt.a.append(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "id": "74826099",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[10]"
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt.a"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6d00b122",
+ "metadata": {},
+ "source": [
+ "But watch this!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "id": "4759e6f4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[10], b=[10], c=[10])"
+ ]
+ },
+ "execution_count": 52,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "972c666e",
+ "metadata": {},
+ "source": [
+ "I hope you understand what happened here without me telling you!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6590d73a",
+ "metadata": {},
+ "source": [
+ "The **same** list object was re-used 3 times in the defaults."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "720e13bb",
+ "metadata": {},
+ "source": [
+ "You can easily recover your defaults using the `_field_defaults` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "id": "586498ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a, b, c\", defaults=(1, 2, 3))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "id": "20f4012e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 3}"
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "NT._field_defaults"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70c3a717",
+ "metadata": {},
+ "source": [
+ "One change of note in Python 3.8, the `_as_dict()` method now returns a standard dictionary (key ordered in the same way as the named tuple). Prior to this version, it would return an `OrderedDict` since standard Python dictionaries did not guarantee any specific key order, but since they now do, there's no need to use the `DefaultDict` anymore."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ecb5b3a0",
+ "metadata": {},
+ "source": [
+ "#### Other Things"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9d8ec24b",
+ "metadata": {},
+ "source": [
+ "These are few other odds and ends that you might find of interest:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3602bbab",
+ "metadata": {},
+ "source": [
+ "The built-in `reversed` function now works with dictionary views:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "id": "4f68e46b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = {'a': 1, 'b': 2}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "id": "83fc356d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['a', 'b']"
+ ]
+ },
+ "execution_count": 56,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(d.keys())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "id": "10648abb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['b', 'a']"
+ ]
+ },
+ "execution_count": 57,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.keys()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "id": "4a4885c3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[2, 1]"
+ ]
+ },
+ "execution_count": 58,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.values()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 59,
+ "id": "13785eb9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('b', 2), ('a', 1)]"
+ ]
+ },
+ "execution_count": 59,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.items()))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e14d5c14",
+ "metadata": {},
+ "source": [
+ "The `continue` statement was not permitted in the `finally` clause of a loop, but is now supported."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fe507127",
+ "metadata": {},
+ "source": [
+ "Earlier in Part 1, we discussed string interning, as well as how a small selection of integers are essentially \"cached\" by Python and re-used whenever the literal is encountered. This meant we could use `is` instead of `==` in some cases, and that helped us get a clearer understanding of what's going on. **BUT**, as we also discussed, you should **not**, in practice, use `is` for comparing objects such as integers, strings, etc (usually we are more interested in whether is the same value, rather than the identical object) - the fact that this works is an implementation detail and not guaranteed to work the same way from one Python version to another.\n",
+ "\n",
+ "Although linters will usually catch those kinds of issues, not everyone uses a Python linter - so Python 3.8 will now emit a **warning** if you compare variables of certain types with literal constants!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 60,
+ "id": "e659956e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/3780910533.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 1\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 60,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 1\n",
+ "a is 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 61,
+ "id": "d970904d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/4272392880.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 'hello'\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 61,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 'hello'\n",
+ "a is 'hello'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "01c01a49",
+ "metadata": {},
+ "source": [
+ "But we do not get a warning in a situation such as this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 62,
+ "id": "c0d535bc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 62,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = [1, 2, 3]\n",
+ "\n",
+ "a is [1, 2, 3]"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 3/Section 11 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb b/Part 3/Section 11 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb
new file mode 100644
index 00000000..1e7fa9b4
--- /dev/null
+++ b/Part 3/Section 11 - Python Updates/01 - Relevant Python 3.10 Changes.ipynb
@@ -0,0 +1,991 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c4d4fc49",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.10 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb1495a9",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.10 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.10.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "98c3ae0d",
+ "metadata": {},
+ "source": [
+ "Python 3.10 has improved it's error messages for syntax errors - the messages are more helpful and hopefully give you a better understanding of what may be syntactically wrong with your code."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ae4aa37",
+ "metadata": {},
+ "source": [
+ "#### Structural Pattern Matching"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d18177a2",
+ "metadata": {},
+ "source": [
+ "One thing I often hear people ask, is, what's the Python equivalent of a `switch` statement."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36a77514",
+ "metadata": {},
+ "source": [
+ "Until now, the answer has alwasy been - there isn't one. Use `if...elif` constructs."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "56fdb138",
+ "metadata": {},
+ "source": [
+ "Python 3.10 introduces a new language element (`match`) to implement something called **pattern matching**, that can be used to replicate this `switch` behavior you might be used to in other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e1cf8b9d",
+ "metadata": {},
+ "source": [
+ "I'll cover some of the basics here, but you should refer to the Python [docs](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement) for more information, as well as the [pep](https://peps.python.org/pep-0634/) for this feature and a [tutorial pep](https://peps.python.org/pep-0636/)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1417630a",
+ "metadata": {},
+ "source": [
+ "Let's start with a simple `match` statement:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "bbecc554",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\":\n",
+ " return \"Hmm, coffee!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm not scared of snakes!\"\n",
+ " case \"Rust\":\n",
+ " return \"Don't drink too much water!\"\n",
+ " case \"Go\":\n",
+ " return \"Collect $200\"\n",
+ " case _:\n",
+ " return \"I'm sorry...\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d5669e92",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm not scared of snakes!\""
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "90cecc86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Collect $200'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Go\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "f9feb023",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm sorry...\""
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"COBOL\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ee7c21fb",
+ "metadata": {},
+ "source": [
+ "Here we were able to define a \"default\" match pattern by using the underscore (`_`) as our pattern - this `_` is called a **wildcard**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b76575de",
+ "metadata": {},
+ "source": [
+ "So this is very much like the \"plain\" switch statement found in some other languages."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e55dd9f",
+ "metadata": {},
+ "source": [
+ "But, this is where things get ineteresting, pattern matching can do much more than the simple example we just saw."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f8d495f2",
+ "metadata": {},
+ "source": [
+ "For example, you can have multiple pattern matching:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "6d5fcc0c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def respond(language):\n",
+ " match language:\n",
+ " case \"Java\" | \"Javascript\":\n",
+ " return \"Love those braces!\"\n",
+ " case \"Python\":\n",
+ " return \"I'm a lumberjack and I don't need no braces\"\n",
+ " case _:\n",
+ " return \"I have no clue!\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "02cf21af",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Java\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "853368f3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Love those braces!'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Javascript\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "066f985e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "\"I'm a lumberjack and I don't need no braces\""
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "respond(\"Python\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7fc43e7f",
+ "metadata": {},
+ "source": [
+ "We could match against one or more literals by using the OR pattern (`|`)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "36064a9c",
+ "metadata": {},
+ "source": [
+ "Let's look at one more example, this time matching **multiple values**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "31978910",
+ "metadata": {},
+ "source": [
+ "Suppose we have some kind of command language for driving a remote controlled robot in a maze, picking up and dropping items as it moves around. Our robot is very simple, it can move in only a few directions, and one step at a time. So to move forward three spaces, we would issue three `move forward` commands.\n",
+ "\n",
+ "Additional commands are `move backward`, `move left`, `move right`. We also have a few other commands our robot understands: `pick` and `drop` for picking up and dropping objects it might find."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63944ea5",
+ "metadata": {},
+ "source": [
+ "We might write a command interpreter this way:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f9077f13",
+ "metadata": {},
+ "source": [
+ "Let's start by using some symbols to represent the robot's actions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "2dde5d86",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'F': '→', 'B': '←', 'L': '↑', 'R': '↓', 'pick': '⤣', 'drop': '⤥'}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "symbols = {\n",
+ " \"F\": \"\\u2192\", \n",
+ " \"B\": \"\\u2190\", \n",
+ " \"L\": \"\\u2191\", \n",
+ " \"R\": \"\\u2193\", \n",
+ " \"pick\": \"\\u2923\", \n",
+ " \"drop\": \"\\u2925\"\n",
+ "}\n",
+ "\n",
+ "symbols"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "faab4c09",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case \"move F\":\n",
+ " return symbols[\"F\"]\n",
+ " case \"move B\":\n",
+ " return symbols[\"B\"]\n",
+ " case \"move L\":\n",
+ " return symbols[\"L\"]\n",
+ " case \"move R\":\n",
+ " return symbols[\"R\"]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24555fab",
+ "metadata": {},
+ "source": [
+ "Then we could issue commands such as:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b673a044",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"move L\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b411438f",
+ "metadata": {},
+ "source": [
+ "Or multiple sequences by maybe using a list of such commands, effectively creating a sequential program for our robot:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "cf94014f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['→', '→', '↑', '⤣', '↓', '↑', '→', '⤥']"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op(\"move F\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"pick\"),\n",
+ " op(\"move R\"),\n",
+ " op(\"move L\"),\n",
+ " op(\"move F\"),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c520053b",
+ "metadata": {},
+ "source": [
+ "We could use something called **capturing** matched sub-patterns to simply our code somewhat:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "e7da20cf",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case [\"move\", (\"F\" | \"B\" | \"L\" |\"R\") as direction]:\n",
+ " return symbols[direction]\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symvols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "c2a1c617",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'↑'"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op([\"move\", \"L\"])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4edeb3dc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'⤣'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "op(\"pick\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "b13504aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "fly does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op(\"fly\")\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6769c228",
+ "metadata": {},
+ "source": [
+ "This is kind of tedious, it would be nicer to write commands such as `move F F L` and `move R L F` instead."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "055d2c60",
+ "metadata": {},
+ "source": [
+ "There are many ways we could solve this, but pattern matching on multiple values can be really useful here."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "372bdb17",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "\n",
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions]:\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c77bec44",
+ "metadata": {},
+ "source": [
+ "What happens here is that the pattern matcher will recognize the first word `move` and then interpret the remaining words collection them in the `directions` variable (so this syntax is very similar to unpacking)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4ef78058",
+ "metadata": {},
+ "source": [
+ "We can now rewrite our program this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "88c0c024",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('→', '→', '↑'), '⤣', ('↓', '↑', '→'), '⤥']"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " op([\"move\", \"F\", \"F\", \"L\"]),\n",
+ " op(\"pick\"),\n",
+ " op([\"move\", \"R\", \"L\", \"F\"]),\n",
+ " op(\"drop\"),\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ddc0f2e",
+ "metadata": {},
+ "source": [
+ "But now we have a slight problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "ed30a762",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " 'up'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f6bbbd53",
+ "metadata": {},
+ "source": [
+ "We would rather just get our custom `ValueError`. To do this we can place a **guard** on our `case` for the `move` command, that will not only do the match but also test an additional condition:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8d441175",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def op(command):\n",
+ " match command:\n",
+ " case ['move', *directions] if set(directions) < symbols.keys():\n",
+ " return tuple(symbols[direction] for direction in directions)\n",
+ " case \"pick\":\n",
+ " return symbols[\"pick\"]\n",
+ " case \"drop\":\n",
+ " return symbols[\"drop\"]\n",
+ " case _:\n",
+ " raise ValueError(f\"{command} does not compute!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "441a53f6",
+ "metadata": {},
+ "source": [
+ "That `if ` statement (the **guard**) will only let the case block execute if the match is true **and** that `if` expression evaludates to `True`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "708c5d16",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " ['move', 'up'] does not compute!\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " op([\"move\", \"up\"])\n",
+ "except Exception as ex:\n",
+ " print(type(ex), ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1ecf5f83",
+ "metadata": {},
+ "source": [
+ "There are many other ways we could have done this - probably better than this, but this was to illustrate how the multiple value matching can work!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84bec678",
+ "metadata": {},
+ "source": [
+ "I urge you to read at least this [tutorial (pep 636)](https://peps.python.org/pep-0636/) on pattern matching."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5b6a7b09",
+ "metadata": {},
+ "source": [
+ "#### The `zip` Function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1294e5f6",
+ "metadata": {},
+ "source": [
+ "We use the built-in `zip` function all the time. As we know, the `zip` will stop iterating after the first of the iterables provided in the arguments is exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "e33aa60d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30)]"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = ['a', 'b', 'c']\n",
+ "l2 = [10, 20, 30, 40]\n",
+ "\n",
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7d310af8",
+ "metadata": {},
+ "source": [
+ "As you can see the last element of `l2` is not included in the result since `l1` only had three elements."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9cf9570",
+ "metadata": {},
+ "source": [
+ "We can also use the `zip_longest` function in the `itertools` module to iterate over the longest iterable, providing some default value for any other iterable that has been exhausted:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "aefa3055",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from itertools import zip_longest"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "ce4779c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 10), ('b', 20), ('c', 30), ('???', 40)]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip_longest(l1, l2, fillvalue='???'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0eb2f702",
+ "metadata": {},
+ "source": [
+ "But what if we want to only zip iterables that have the **same** length? We would need to test the length of each iterable first - but if those were iterators instead of iterables, we will have exhausted the iterator, and `zip` would come back \"empty\":"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "3b704410",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da0d866f",
+ "metadata": {},
+ "source": [
+ "We could test to see if `l1` and `l2` are the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "bc7d34c9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "len(list(l1)) == len(list(l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0a4a1974",
+ "metadata": {},
+ "source": [
+ "But, if we now try to `zip` them:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "1c3928b9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[]"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(zip(l1, l2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ee310e9",
+ "metadata": {},
+ "source": [
+ "In Python 3.10, the `zip` function now has a keyword-only parameter called `strict` that will just do the zip, but throw an exception if one of the arguments get exhausted before the others:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "54722489",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "zip() argument 2 is shorter than argument 1\n"
+ ]
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(3))\n",
+ "\n",
+ "try:\n",
+ " list(zip(l1, l2, strict=True))\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2635211a",
+ "metadata": {},
+ "source": [
+ "And works just fine if the arguments all have the same length:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "7fb672cb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[(0, 0, 0), (1, 1, 1), (4, 8, 16), (9, 27, 81)]"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1 = (i ** 2 for i in range(4))\n",
+ "l2 = (i ** 3 for i in range(4))\n",
+ "l3 = (i ** 4 for i in range(4))\n",
+ "\n",
+ "list(zip(l1, l2, l3))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "501fec3b",
+ "metadata": {},
+ "source": [
+ "So why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dab4260e",
+ "metadata": {},
+ "source": [
+ "In **many** cases, our code zips iterables that we expect to be of the same length. To avoid bugs in our program, we should check that this condition is true, otherwise zip will silently just zip based on the shortest one. But as we saw with iterators, that can be difficult to do without exhausting the very iterators we are trying to zip. (it can be done, it's just more code)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c73e5ad1",
+ "metadata": {},
+ "source": [
+ "So, if you are one of the lucky devs that gets to write Python 3.10 (or higher :-) ) code, you can just use `strict` whenever you zip things together and expect that they are all of the same length. Much easier to do it this way (and, as we discuss in Exception handling, falls into the category of \"ask forgiveness later\" which we saw was the preferred way (in general) to handle exceptions in our apps, as opposed to the \"look before you leap\" approach we would have to use to test the argument lengths."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "400a56c1",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 3/Section 11 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb b/Part 3/Section 11 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb
new file mode 100644
index 00000000..698dadce
--- /dev/null
+++ b/Part 3/Section 11 - Python Updates/02 - Relevant Python 3.9 Changes.ipynb
@@ -0,0 +1,2343 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c45f0998",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.9 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2e965eba",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.9 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.9.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "39255227",
+ "metadata": {},
+ "source": [
+ "#### Time Zones"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "26750adb",
+ "metadata": {},
+ "source": [
+ "We don't cover 3rd party libraries in this course, but if you've worked with Python in a production environment, you will likely have come across the dreaded timezone and Daylight Savings issues that plague datetimes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7cdfe8a5",
+ "metadata": {},
+ "source": [
+ "Most likely you will have resorted to using the `pytz` and `python-dateutil` libraries to help with that."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bc000883",
+ "metadata": {},
+ "source": [
+ "Now, Python 3.9 is proud to introduce the `zoneinfo` module to deal with timezones properly. About time too!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c2d652dd",
+ "metadata": {},
+ "source": [
+ "For full info on this, refer to [PEP 615](https://peps.python.org/pep-0615/).\n",
+ "\n",
+ "And the Python [docs](https://docs.python.org/3.9/library/zoneinfo.html#module-zoneinfo).\n",
+ "\n",
+ "**Windows Users**: you will likely need to add a dependency on the `tzdata` [library](https://pypi.org/project/tzdata/) for the IANA time zone database. See [this note](https://docs.python.org/3.9/library/zoneinfo.html#data-sources)\n",
+ "\n",
+ "You should also take a look at this [presentation](https://pganssle-talks.github.io/chipy-nov-2020-zoneinfo/#/) by Paul Ganssle who wrote that module - very interesting read!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "80255944",
+ "metadata": {},
+ "source": [
+ "Let's look at how we might have handled timezone and DST using `pytz` and `dateutil`, and contrast that to how we can use the new `zoneinfo` module instead."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "ec129288",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import zoneinfo\n",
+ "from datetime import datetime, timezone\n",
+ "from zoneinfo import ZoneInfo\n",
+ "\n",
+ "import dateutil\n",
+ "import pytz"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "beadc4e2",
+ "metadata": {},
+ "source": [
+ "Let's list out all the defined time zones:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "d0058e73",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in pytz.all_timezones:\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f18fa2c9",
+ "metadata": {},
+ "source": [
+ "With the `zoneinfo` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "9d2cf9d1",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Africa/Abidjan\n",
+ "Africa/Accra\n",
+ "Africa/Addis_Ababa\n",
+ "Africa/Algiers\n",
+ "Africa/Asmara\n",
+ "Africa/Asmera\n",
+ "Africa/Bamako\n",
+ "Africa/Bangui\n",
+ "Africa/Banjul\n",
+ "Africa/Bissau\n",
+ "Africa/Blantyre\n",
+ "Africa/Brazzaville\n",
+ "Africa/Bujumbura\n",
+ "Africa/Cairo\n",
+ "Africa/Casablanca\n",
+ "Africa/Ceuta\n",
+ "Africa/Conakry\n",
+ "Africa/Dakar\n",
+ "Africa/Dar_es_Salaam\n",
+ "Africa/Djibouti\n",
+ "Africa/Douala\n",
+ "Africa/El_Aaiun\n",
+ "Africa/Freetown\n",
+ "Africa/Gaborone\n",
+ "Africa/Harare\n",
+ "Africa/Johannesburg\n",
+ "Africa/Juba\n",
+ "Africa/Kampala\n",
+ "Africa/Khartoum\n",
+ "Africa/Kigali\n",
+ "Africa/Kinshasa\n",
+ "Africa/Lagos\n",
+ "Africa/Libreville\n",
+ "Africa/Lome\n",
+ "Africa/Luanda\n",
+ "Africa/Lubumbashi\n",
+ "Africa/Lusaka\n",
+ "Africa/Malabo\n",
+ "Africa/Maputo\n",
+ "Africa/Maseru\n",
+ "Africa/Mbabane\n",
+ "Africa/Mogadishu\n",
+ "Africa/Monrovia\n",
+ "Africa/Nairobi\n",
+ "Africa/Ndjamena\n",
+ "Africa/Niamey\n",
+ "Africa/Nouakchott\n",
+ "Africa/Ouagadougou\n",
+ "Africa/Porto-Novo\n",
+ "Africa/Sao_Tome\n",
+ "Africa/Timbuktu\n",
+ "Africa/Tripoli\n",
+ "Africa/Tunis\n",
+ "Africa/Windhoek\n",
+ "America/Adak\n",
+ "America/Anchorage\n",
+ "America/Anguilla\n",
+ "America/Antigua\n",
+ "America/Araguaina\n",
+ "America/Argentina/Buenos_Aires\n",
+ "America/Argentina/Catamarca\n",
+ "America/Argentina/ComodRivadavia\n",
+ "America/Argentina/Cordoba\n",
+ "America/Argentina/Jujuy\n",
+ "America/Argentina/La_Rioja\n",
+ "America/Argentina/Mendoza\n",
+ "America/Argentina/Rio_Gallegos\n",
+ "America/Argentina/Salta\n",
+ "America/Argentina/San_Juan\n",
+ "America/Argentina/San_Luis\n",
+ "America/Argentina/Tucuman\n",
+ "America/Argentina/Ushuaia\n",
+ "America/Aruba\n",
+ "America/Asuncion\n",
+ "America/Atikokan\n",
+ "America/Atka\n",
+ "America/Bahia\n",
+ "America/Bahia_Banderas\n",
+ "America/Barbados\n",
+ "America/Belem\n",
+ "America/Belize\n",
+ "America/Blanc-Sablon\n",
+ "America/Boa_Vista\n",
+ "America/Bogota\n",
+ "America/Boise\n",
+ "America/Buenos_Aires\n",
+ "America/Cambridge_Bay\n",
+ "America/Campo_Grande\n",
+ "America/Cancun\n",
+ "America/Caracas\n",
+ "America/Catamarca\n",
+ "America/Cayenne\n",
+ "America/Cayman\n",
+ "America/Chicago\n",
+ "America/Chihuahua\n",
+ "America/Coral_Harbour\n",
+ "America/Cordoba\n",
+ "America/Costa_Rica\n",
+ "America/Creston\n",
+ "America/Cuiaba\n",
+ "America/Curacao\n",
+ "America/Danmarkshavn\n",
+ "America/Dawson\n",
+ "America/Dawson_Creek\n",
+ "America/Denver\n",
+ "America/Detroit\n",
+ "America/Dominica\n",
+ "America/Edmonton\n",
+ "America/Eirunepe\n",
+ "America/El_Salvador\n",
+ "America/Ensenada\n",
+ "America/Fort_Nelson\n",
+ "America/Fort_Wayne\n",
+ "America/Fortaleza\n",
+ "America/Glace_Bay\n",
+ "America/Godthab\n",
+ "America/Goose_Bay\n",
+ "America/Grand_Turk\n",
+ "America/Grenada\n",
+ "America/Guadeloupe\n",
+ "America/Guatemala\n",
+ "America/Guayaquil\n",
+ "America/Guyana\n",
+ "America/Halifax\n",
+ "America/Havana\n",
+ "America/Hermosillo\n",
+ "America/Indiana/Indianapolis\n",
+ "America/Indiana/Knox\n",
+ "America/Indiana/Marengo\n",
+ "America/Indiana/Petersburg\n",
+ "America/Indiana/Tell_City\n",
+ "America/Indiana/Vevay\n",
+ "America/Indiana/Vincennes\n",
+ "America/Indiana/Winamac\n",
+ "America/Indianapolis\n",
+ "America/Inuvik\n",
+ "America/Iqaluit\n",
+ "America/Jamaica\n",
+ "America/Jujuy\n",
+ "America/Juneau\n",
+ "America/Kentucky/Louisville\n",
+ "America/Kentucky/Monticello\n",
+ "America/Knox_IN\n",
+ "America/Kralendijk\n",
+ "America/La_Paz\n",
+ "America/Lima\n",
+ "America/Los_Angeles\n",
+ "America/Louisville\n",
+ "America/Lower_Princes\n",
+ "America/Maceio\n",
+ "America/Managua\n",
+ "America/Manaus\n",
+ "America/Marigot\n",
+ "America/Martinique\n",
+ "America/Matamoros\n",
+ "America/Mazatlan\n",
+ "America/Mendoza\n",
+ "America/Menominee\n",
+ "America/Merida\n",
+ "America/Metlakatla\n",
+ "America/Mexico_City\n",
+ "America/Miquelon\n",
+ "America/Moncton\n",
+ "America/Monterrey\n",
+ "America/Montevideo\n",
+ "America/Montreal\n",
+ "America/Montserrat\n",
+ "America/Nassau\n",
+ "America/New_York\n",
+ "America/Nipigon\n",
+ "America/Nome\n",
+ "America/Noronha\n",
+ "America/North_Dakota/Beulah\n",
+ "America/North_Dakota/Center\n",
+ "America/North_Dakota/New_Salem\n",
+ "America/Nuuk\n",
+ "America/Ojinaga\n",
+ "America/Panama\n",
+ "America/Pangnirtung\n",
+ "America/Paramaribo\n",
+ "America/Phoenix\n",
+ "America/Port-au-Prince\n",
+ "America/Port_of_Spain\n",
+ "America/Porto_Acre\n",
+ "America/Porto_Velho\n",
+ "America/Puerto_Rico\n",
+ "America/Punta_Arenas\n",
+ "America/Rainy_River\n",
+ "America/Rankin_Inlet\n",
+ "America/Recife\n",
+ "America/Regina\n",
+ "America/Resolute\n",
+ "America/Rio_Branco\n",
+ "America/Rosario\n",
+ "America/Santa_Isabel\n",
+ "America/Santarem\n",
+ "America/Santiago\n",
+ "America/Santo_Domingo\n",
+ "America/Sao_Paulo\n",
+ "America/Scoresbysund\n",
+ "America/Shiprock\n",
+ "America/Sitka\n",
+ "America/St_Barthelemy\n",
+ "America/St_Johns\n",
+ "America/St_Kitts\n",
+ "America/St_Lucia\n",
+ "America/St_Thomas\n",
+ "America/St_Vincent\n",
+ "America/Swift_Current\n",
+ "America/Tegucigalpa\n",
+ "America/Thule\n",
+ "America/Thunder_Bay\n",
+ "America/Tijuana\n",
+ "America/Toronto\n",
+ "America/Tortola\n",
+ "America/Vancouver\n",
+ "America/Virgin\n",
+ "America/Whitehorse\n",
+ "America/Winnipeg\n",
+ "America/Yakutat\n",
+ "America/Yellowknife\n",
+ "Antarctica/Casey\n",
+ "Antarctica/Davis\n",
+ "Antarctica/DumontDUrville\n",
+ "Antarctica/Macquarie\n",
+ "Antarctica/Mawson\n",
+ "Antarctica/McMurdo\n",
+ "Antarctica/Palmer\n",
+ "Antarctica/Rothera\n",
+ "Antarctica/South_Pole\n",
+ "Antarctica/Syowa\n",
+ "Antarctica/Troll\n",
+ "Antarctica/Vostok\n",
+ "Arctic/Longyearbyen\n",
+ "Asia/Aden\n",
+ "Asia/Almaty\n",
+ "Asia/Amman\n",
+ "Asia/Anadyr\n",
+ "Asia/Aqtau\n",
+ "Asia/Aqtobe\n",
+ "Asia/Ashgabat\n",
+ "Asia/Ashkhabad\n",
+ "Asia/Atyrau\n",
+ "Asia/Baghdad\n",
+ "Asia/Bahrain\n",
+ "Asia/Baku\n",
+ "Asia/Bangkok\n",
+ "Asia/Barnaul\n",
+ "Asia/Beirut\n",
+ "Asia/Bishkek\n",
+ "Asia/Brunei\n",
+ "Asia/Calcutta\n",
+ "Asia/Chita\n",
+ "Asia/Choibalsan\n",
+ "Asia/Chongqing\n",
+ "Asia/Chungking\n",
+ "Asia/Colombo\n",
+ "Asia/Dacca\n",
+ "Asia/Damascus\n",
+ "Asia/Dhaka\n",
+ "Asia/Dili\n",
+ "Asia/Dubai\n",
+ "Asia/Dushanbe\n",
+ "Asia/Famagusta\n",
+ "Asia/Gaza\n",
+ "Asia/Harbin\n",
+ "Asia/Hebron\n",
+ "Asia/Ho_Chi_Minh\n",
+ "Asia/Hong_Kong\n",
+ "Asia/Hovd\n",
+ "Asia/Irkutsk\n",
+ "Asia/Istanbul\n",
+ "Asia/Jakarta\n",
+ "Asia/Jayapura\n",
+ "Asia/Jerusalem\n",
+ "Asia/Kabul\n",
+ "Asia/Kamchatka\n",
+ "Asia/Karachi\n",
+ "Asia/Kashgar\n",
+ "Asia/Kathmandu\n",
+ "Asia/Katmandu\n",
+ "Asia/Khandyga\n",
+ "Asia/Kolkata\n",
+ "Asia/Krasnoyarsk\n",
+ "Asia/Kuala_Lumpur\n",
+ "Asia/Kuching\n",
+ "Asia/Kuwait\n",
+ "Asia/Macao\n",
+ "Asia/Macau\n",
+ "Asia/Magadan\n",
+ "Asia/Makassar\n",
+ "Asia/Manila\n",
+ "Asia/Muscat\n",
+ "Asia/Nicosia\n",
+ "Asia/Novokuznetsk\n",
+ "Asia/Novosibirsk\n",
+ "Asia/Omsk\n",
+ "Asia/Oral\n",
+ "Asia/Phnom_Penh\n",
+ "Asia/Pontianak\n",
+ "Asia/Pyongyang\n",
+ "Asia/Qatar\n",
+ "Asia/Qostanay\n",
+ "Asia/Qyzylorda\n",
+ "Asia/Rangoon\n",
+ "Asia/Riyadh\n",
+ "Asia/Saigon\n",
+ "Asia/Sakhalin\n",
+ "Asia/Samarkand\n",
+ "Asia/Seoul\n",
+ "Asia/Shanghai\n",
+ "Asia/Singapore\n",
+ "Asia/Srednekolymsk\n",
+ "Asia/Taipei\n",
+ "Asia/Tashkent\n",
+ "Asia/Tbilisi\n",
+ "Asia/Tehran\n",
+ "Asia/Tel_Aviv\n",
+ "Asia/Thimbu\n",
+ "Asia/Thimphu\n",
+ "Asia/Tokyo\n",
+ "Asia/Tomsk\n",
+ "Asia/Ujung_Pandang\n",
+ "Asia/Ulaanbaatar\n",
+ "Asia/Ulan_Bator\n",
+ "Asia/Urumqi\n",
+ "Asia/Ust-Nera\n",
+ "Asia/Vientiane\n",
+ "Asia/Vladivostok\n",
+ "Asia/Yakutsk\n",
+ "Asia/Yangon\n",
+ "Asia/Yekaterinburg\n",
+ "Asia/Yerevan\n",
+ "Atlantic/Azores\n",
+ "Atlantic/Bermuda\n",
+ "Atlantic/Canary\n",
+ "Atlantic/Cape_Verde\n",
+ "Atlantic/Faeroe\n",
+ "Atlantic/Faroe\n",
+ "Atlantic/Jan_Mayen\n",
+ "Atlantic/Madeira\n",
+ "Atlantic/Reykjavik\n",
+ "Atlantic/South_Georgia\n",
+ "Atlantic/St_Helena\n",
+ "Atlantic/Stanley\n",
+ "Australia/ACT\n",
+ "Australia/Adelaide\n",
+ "Australia/Brisbane\n",
+ "Australia/Broken_Hill\n",
+ "Australia/Canberra\n",
+ "Australia/Currie\n",
+ "Australia/Darwin\n",
+ "Australia/Eucla\n",
+ "Australia/Hobart\n",
+ "Australia/LHI\n",
+ "Australia/Lindeman\n",
+ "Australia/Lord_Howe\n",
+ "Australia/Melbourne\n",
+ "Australia/NSW\n",
+ "Australia/North\n",
+ "Australia/Perth\n",
+ "Australia/Queensland\n",
+ "Australia/South\n",
+ "Australia/Sydney\n",
+ "Australia/Tasmania\n",
+ "Australia/Victoria\n",
+ "Australia/West\n",
+ "Australia/Yancowinna\n",
+ "Brazil/Acre\n",
+ "Brazil/DeNoronha\n",
+ "Brazil/East\n",
+ "Brazil/West\n",
+ "CET\n",
+ "CST6CDT\n",
+ "Canada/Atlantic\n",
+ "Canada/Central\n",
+ "Canada/Eastern\n",
+ "Canada/Mountain\n",
+ "Canada/Newfoundland\n",
+ "Canada/Pacific\n",
+ "Canada/Saskatchewan\n",
+ "Canada/Yukon\n",
+ "Chile/Continental\n",
+ "Chile/EasterIsland\n",
+ "Cuba\n",
+ "EET\n",
+ "EST\n",
+ "EST5EDT\n",
+ "Egypt\n",
+ "Eire\n",
+ "Etc/GMT\n",
+ "Etc/GMT+0\n",
+ "Etc/GMT+1\n",
+ "Etc/GMT+10\n",
+ "Etc/GMT+11\n",
+ "Etc/GMT+12\n",
+ "Etc/GMT+2\n",
+ "Etc/GMT+3\n",
+ "Etc/GMT+4\n",
+ "Etc/GMT+5\n",
+ "Etc/GMT+6\n",
+ "Etc/GMT+7\n",
+ "Etc/GMT+8\n",
+ "Etc/GMT+9\n",
+ "Etc/GMT-0\n",
+ "Etc/GMT-1\n",
+ "Etc/GMT-10\n",
+ "Etc/GMT-11\n",
+ "Etc/GMT-12\n",
+ "Etc/GMT-13\n",
+ "Etc/GMT-14\n",
+ "Etc/GMT-2\n",
+ "Etc/GMT-3\n",
+ "Etc/GMT-4\n",
+ "Etc/GMT-5\n",
+ "Etc/GMT-6\n",
+ "Etc/GMT-7\n",
+ "Etc/GMT-8\n",
+ "Etc/GMT-9\n",
+ "Etc/GMT0\n",
+ "Etc/Greenwich\n",
+ "Etc/UCT\n",
+ "Etc/UTC\n",
+ "Etc/Universal\n",
+ "Etc/Zulu\n",
+ "Europe/Amsterdam\n",
+ "Europe/Andorra\n",
+ "Europe/Astrakhan\n",
+ "Europe/Athens\n",
+ "Europe/Belfast\n",
+ "Europe/Belgrade\n",
+ "Europe/Berlin\n",
+ "Europe/Bratislava\n",
+ "Europe/Brussels\n",
+ "Europe/Bucharest\n",
+ "Europe/Budapest\n",
+ "Europe/Busingen\n",
+ "Europe/Chisinau\n",
+ "Europe/Copenhagen\n",
+ "Europe/Dublin\n",
+ "Europe/Gibraltar\n",
+ "Europe/Guernsey\n",
+ "Europe/Helsinki\n",
+ "Europe/Isle_of_Man\n",
+ "Europe/Istanbul\n",
+ "Europe/Jersey\n",
+ "Europe/Kaliningrad\n",
+ "Europe/Kiev\n",
+ "Europe/Kirov\n",
+ "Europe/Lisbon\n",
+ "Europe/Ljubljana\n",
+ "Europe/London\n",
+ "Europe/Luxembourg\n",
+ "Europe/Madrid\n",
+ "Europe/Malta\n",
+ "Europe/Mariehamn\n",
+ "Europe/Minsk\n",
+ "Europe/Monaco\n",
+ "Europe/Moscow\n",
+ "Europe/Nicosia\n",
+ "Europe/Oslo\n",
+ "Europe/Paris\n",
+ "Europe/Podgorica\n",
+ "Europe/Prague\n",
+ "Europe/Riga\n",
+ "Europe/Rome\n",
+ "Europe/Samara\n",
+ "Europe/San_Marino\n",
+ "Europe/Sarajevo\n",
+ "Europe/Saratov\n",
+ "Europe/Simferopol\n",
+ "Europe/Skopje\n",
+ "Europe/Sofia\n",
+ "Europe/Stockholm\n",
+ "Europe/Tallinn\n",
+ "Europe/Tirane\n",
+ "Europe/Tiraspol\n",
+ "Europe/Ulyanovsk\n",
+ "Europe/Uzhgorod\n",
+ "Europe/Vaduz\n",
+ "Europe/Vatican\n",
+ "Europe/Vienna\n",
+ "Europe/Vilnius\n",
+ "Europe/Volgograd\n",
+ "Europe/Warsaw\n",
+ "Europe/Zagreb\n",
+ "Europe/Zaporozhye\n",
+ "Europe/Zurich\n",
+ "Factory\n",
+ "GB\n",
+ "GB-Eire\n",
+ "GMT\n",
+ "GMT+0\n",
+ "GMT-0\n",
+ "GMT0\n",
+ "Greenwich\n",
+ "HST\n",
+ "Hongkong\n",
+ "Iceland\n",
+ "Indian/Antananarivo\n",
+ "Indian/Chagos\n",
+ "Indian/Christmas\n",
+ "Indian/Cocos\n",
+ "Indian/Comoro\n",
+ "Indian/Kerguelen\n",
+ "Indian/Mahe\n",
+ "Indian/Maldives\n",
+ "Indian/Mauritius\n",
+ "Indian/Mayotte\n",
+ "Indian/Reunion\n",
+ "Iran\n",
+ "Israel\n",
+ "Jamaica\n",
+ "Japan\n",
+ "Kwajalein\n",
+ "Libya\n",
+ "MET\n",
+ "MST\n",
+ "MST7MDT\n",
+ "Mexico/BajaNorte\n",
+ "Mexico/BajaSur\n",
+ "Mexico/General\n",
+ "NZ\n",
+ "NZ-CHAT\n",
+ "Navajo\n",
+ "PRC\n",
+ "PST8PDT\n",
+ "Pacific/Apia\n",
+ "Pacific/Auckland\n",
+ "Pacific/Bougainville\n",
+ "Pacific/Chatham\n",
+ "Pacific/Chuuk\n",
+ "Pacific/Easter\n",
+ "Pacific/Efate\n",
+ "Pacific/Enderbury\n",
+ "Pacific/Fakaofo\n",
+ "Pacific/Fiji\n",
+ "Pacific/Funafuti\n",
+ "Pacific/Galapagos\n",
+ "Pacific/Gambier\n",
+ "Pacific/Guadalcanal\n",
+ "Pacific/Guam\n",
+ "Pacific/Honolulu\n",
+ "Pacific/Johnston\n",
+ "Pacific/Kanton\n",
+ "Pacific/Kiritimati\n",
+ "Pacific/Kosrae\n",
+ "Pacific/Kwajalein\n",
+ "Pacific/Majuro\n",
+ "Pacific/Marquesas\n",
+ "Pacific/Midway\n",
+ "Pacific/Nauru\n",
+ "Pacific/Niue\n",
+ "Pacific/Norfolk\n",
+ "Pacific/Noumea\n",
+ "Pacific/Pago_Pago\n",
+ "Pacific/Palau\n",
+ "Pacific/Pitcairn\n",
+ "Pacific/Pohnpei\n",
+ "Pacific/Ponape\n",
+ "Pacific/Port_Moresby\n",
+ "Pacific/Rarotonga\n",
+ "Pacific/Saipan\n",
+ "Pacific/Samoa\n",
+ "Pacific/Tahiti\n",
+ "Pacific/Tarawa\n",
+ "Pacific/Tongatapu\n",
+ "Pacific/Truk\n",
+ "Pacific/Wake\n",
+ "Pacific/Wallis\n",
+ "Pacific/Yap\n",
+ "Poland\n",
+ "Portugal\n",
+ "ROC\n",
+ "ROK\n",
+ "Singapore\n",
+ "Turkey\n",
+ "UCT\n",
+ "US/Alaska\n",
+ "US/Aleutian\n",
+ "US/Arizona\n",
+ "US/Central\n",
+ "US/East-Indiana\n",
+ "US/Eastern\n",
+ "US/Hawaii\n",
+ "US/Indiana-Starke\n",
+ "US/Michigan\n",
+ "US/Mountain\n",
+ "US/Pacific\n",
+ "US/Samoa\n",
+ "UTC\n",
+ "Universal\n",
+ "W-SU\n",
+ "WET\n",
+ "Zulu\n"
+ ]
+ }
+ ],
+ "source": [
+ "for tz in sorted(zoneinfo.available_timezones()):\n",
+ " print(tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6a1887cf",
+ "metadata": {},
+ "source": [
+ "Are the time zones defined by `pytz` and `zoneinfo` the same? Yes!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8f8df276",
+ "metadata": {},
+ "source": [
+ "In this example, let's take our current time in UTC, and convert it to some other time zone, say `Australia/Melbourne`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77f1b8d9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "now_utc_naive = datetime.utcnow()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "f8586215",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_naive"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a452220a",
+ "metadata": {},
+ "source": [
+ "The problem here is that we have a _naive_ datetime (i.e. one without an attached timezone)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d1d10809",
+ "metadata": {},
+ "source": [
+ "We can make this naive datetime time zone aware by tacking on the timezone (since we know it is UTC):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "db60736b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware = now_utc_naive.replace(tzinfo=timezone.utc)\n",
+ "now_utc_aware"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8282b097",
+ "metadata": {},
+ "source": [
+ "Or, we could use the `pytz` library to do the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "0d7434f7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 377626, tzinfo=)"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pytz.utc.localize(datetime.utcnow())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e613c2e1",
+ "metadata": {},
+ "source": [
+ "Now that we have a time zone aware datetime, we can convert it to another timezone using `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "94b0b5c9",
+ "metadata": {},
+ "source": [
+ "First, let's pick a time zone from `pytz`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "833b5ff9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_melbourne = pytz.timezone('Australia/Melbourne')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ce4323c1",
+ "metadata": {},
+ "source": [
+ "And now we localize our aware datetime to this time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "d23fd3c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_melbourne)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "260bd7ff",
+ "metadata": {},
+ "source": [
+ "We could do both these steps in a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "6559daf7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 17, 1, 3, 368403, tzinfo=)"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(pytz.timezone('Australia/Melbourne'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6be99718",
+ "metadata": {},
+ "source": [
+ "Now, let's do the same thing using the `zoneinfo` module."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8c9b22bb",
+ "metadata": {},
+ "source": [
+ "Let's pick the same target time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "30c58db3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz_zi_dublin = ZoneInfo(\"Europe/Dublin\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f77b5b0",
+ "metadata": {},
+ "source": [
+ "And the let's convert our aware datetime to that time zone:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "1623322d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(tz_zi_dublin)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4536470f",
+ "metadata": {},
+ "source": [
+ "Or, we can also write this as a single expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "337c3955",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2022, 3, 20, 6, 1, 3, 368403, tzinfo=zoneinfo.ZoneInfo(key='Europe/Dublin'))"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now_utc_aware.astimezone(ZoneInfo(\"Europe/Dublin\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4076195d",
+ "metadata": {},
+ "source": [
+ "#### The `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "41d86e28",
+ "metadata": {},
+ "source": [
+ "Several enhancements or additions have been to the math library."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bd3de95f",
+ "metadata": {},
+ "source": [
+ "The `math` module already had the `gcd` function to calculate the great common divisor of two numbers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "911df27e",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "4154629e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "9"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "85abe1fa",
+ "metadata": {},
+ "source": [
+ "But now `gcd` can take multiple arguments, not just two:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "d64ea0d9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.gcd(27, 45, 18, 15)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0503d78a",
+ "metadata": {},
+ "source": [
+ "The `lcm` (least common multiple) function has been added:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "b4c25fef",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "12"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.lcm(2, 3, 4)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "58a4c3cd",
+ "metadata": {},
+ "source": [
+ "#### Dictionary Unions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2c05f130",
+ "metadata": {},
+ "source": [
+ "When we discussed dictionaries in this course, we saw that we could combine two dictionaries using unpacking:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "136c8836",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'a': 1, 'b': 2, 'c': 3}\n",
+ "d2 = {'c': 30, 'd': 40}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "81331802",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "{**d1, **d2}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "97ca030f",
+ "metadata": {},
+ "source": [
+ "As we saw the second dictionary's key/value pair \"overwrote\" the key/value pair from the first dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b361771e",
+ "metadata": {},
+ "source": [
+ "We could also use the `ChainMap` function in the `collections` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "d633f16c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import ChainMap"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "ad250dfd",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "merged = ChainMap(d1, d2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "1deeb8f2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 3, 40)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "merged['a'], merged['c'], merged['d']"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1751d47a",
+ "metadata": {},
+ "source": [
+ "As you can see, in the `ChainMap`, the firest occurrence of the key is used - so in this case `c` comes from `d1`, not `d2`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1c63e893",
+ "metadata": {},
+ "source": [
+ "Both of these ways of \"combining\" dictionaries work well - but they are not very intuitive, and need a little attention to what happens when you have common keys in the dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "aca5787b",
+ "metadata": {},
+ "source": [
+ "Think of concatenating lists where we can simply use the `+` operator - this is very intuitive:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "de850747",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69429bab",
+ "metadata": {},
+ "source": [
+ "Now dictionaries are not like lists, but they are closely related to **sets**. With sets, we have the **union** operator (`|`):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "dcb8a7b5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a', 'b', 'c', 'd'}"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "s1 = {'a', 'b', 'c'}\n",
+ "s2 = {'c', 'd'}\n",
+ "\n",
+ "s1 | s2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "32c20dfb",
+ "metadata": {},
+ "source": [
+ "Python 3.9 introduces support for the **union** (`|`) operation between dictionaries as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "af3fcc01",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 30, 'd': 40}"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "851ffadc",
+ "metadata": {},
+ "source": [
+ "Just like with the `{**d1, **d2}` approach, the value for `c` came from the second dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cb6fc060",
+ "metadata": {},
+ "source": [
+ "And just like with that technique we can control this by switching the order of the dictionaries in the union:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "05555100",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 3, 'd': 40, 'a': 1, 'b': 2}"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d2 | d1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "739e210f",
+ "metadata": {},
+ "source": [
+ "One question we should have, is what happens to the insertion order that Python dictionaries now guarantee?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "f8759da5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d1 = {'c': 3, 'a': 1, 'b': 2}\n",
+ "d2 = {'d': 40, 'c': 30}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "e06e3966",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'c': 30, 'a': 1, 'b': 2, 'd': 40}"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d1 | d2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8e0e1c2e",
+ "metadata": {},
+ "source": [
+ "As you can see, even though the **value** for `c` came from the **second** dictionary, the original inertion order of the **keys** is maintained, so `c` is still in first position in the union of the two dictionaries."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e12dee6a",
+ "metadata": {},
+ "source": [
+ "#### String Methods"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f69f79e4",
+ "metadata": {},
+ "source": [
+ "Often we need to remove some prefix or suffix in a string."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "67496793",
+ "metadata": {},
+ "source": [
+ "For example, we may have this list of string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "9da4cabe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data = [\n",
+ " \"(log) [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "30de1de8",
+ "metadata": {},
+ "source": [
+ "And we want to clean these up and remove the `(log) ` prefix (including the space)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "84a6c502",
+ "metadata": {},
+ "source": [
+ "We can certainly do it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "8a60ecdc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "45fa082e",
+ "metadata": {},
+ "source": [
+ "You might be tempted to use the `lstrip` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "74e60a43",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5e045ebc",
+ "metadata": {},
+ "source": [
+ "This appears to work, but `lstrip` (and `rstrip`) does not interpet `\"(log )\"` as a string, but rather a **sequence** of characters, and each one will be removed - so you might end up with this problem:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "ddc6e3a8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "data2 = [\n",
+ " \"(log) log: [2022-03-01T13:30:01] Log record 1\",\n",
+ " \"(log) log: [2022-03-01T13:30:02] Log record 2\",\n",
+ " \"(log) log: [2022-03-01T13:30:03] Log record 3\",\n",
+ " \"(log) log: [2022-03-01T13:30:04] Log record 4\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "d87cd3c5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[': [2022-03-01T13:30:01] Log record 1',\n",
+ " ': [2022-03-01T13:30:02] Log record 2',\n",
+ " ': [2022-03-01T13:30:03] Log record 3',\n",
+ " ': [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.lstrip(\"(log) \")\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f73aac3",
+ "metadata": {},
+ "source": [
+ "Now that removed a lot more than expected everything from those strings, unlike the replace, which will replace only the first occurrence by default:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "eaf8792b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 34,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "clean = [\n",
+ " s.replace(\"(log) \", '')\n",
+ " for s in data2\n",
+ "]\n",
+ "clean"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0aca0211",
+ "metadata": {},
+ "source": [
+ "Python 3,9 introduces two new string methods to do this without having to use `replace`, namely the `removeprefix()` and `removesuffix()` methods:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "b320eb46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['[2022-03-01T13:30:01] Log record 1',\n",
+ " '[2022-03-01T13:30:02] Log record 2',\n",
+ " '[2022-03-01T13:30:03] Log record 3',\n",
+ " '[2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "d4ebaf46",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['log: [2022-03-01T13:30:01] Log record 1',\n",
+ " 'log: [2022-03-01T13:30:02] Log record 2',\n",
+ " 'log: [2022-03-01T13:30:03] Log record 3',\n",
+ " 'log: [2022-03-01T13:30:04] Log record 4']"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[\n",
+ " s.removeprefix(\"(log) \")\n",
+ " for s in data2\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f7a2ffd4",
+ "metadata": {},
+ "source": [
+ "Note that if the prefix (or suffix) is not found, nothing happens, the new string will be the same as the original (i.e. no exception is raised):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "829cb63b",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Python rocks!'"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'Python rocks!'.removeprefix('Java')"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 3/Section 11 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb b/Part 3/Section 11 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb
new file mode 100644
index 00000000..53e8b672
--- /dev/null
+++ b/Part 3/Section 11 - Python Updates/03 - Python 3.8 - Assignment Expressions.ipynb
@@ -0,0 +1,1082 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "17ad44da",
+ "metadata": {},
+ "source": [
+ "### Python 3.8 - Assignment Expressions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "40b0045a",
+ "metadata": {},
+ "source": [
+ "Another enhancement to the Python core language that was introduced in Python 3.8 is **assignment expressions**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cad52d44",
+ "metadata": {},
+ "source": [
+ "You can see the pep for it here: [pep 572](https://peps.python.org/pep-0572/)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "285f5b11",
+ "metadata": {},
+ "source": [
+ "Remember that an expression is simply a snippet of code that is evaluated.\n",
+ "\n",
+ "The following are all examples of expressions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "357659ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "c7b05302",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2, 3, 4, 5, 6]"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "[1, 2, 3] + [4, 5, 6]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "a68603b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'PYTHON'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "201b3156",
+ "metadata": {},
+ "source": [
+ "And an assignment is simply when we assign an expression result to a variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "b08e7b15",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2\n",
+ "b = [1, 2, 3] + [4, 5, 6]\n",
+ "c = \" python \".lstrip().rstrip().upper()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "54232d7a",
+ "metadata": {},
+ "source": [
+ "As you can see, we have to different steps here.\n",
+ "\n",
+ "We assign the result of an expression (the right hand side) to a variable (the left hand side) using the equals (`=`) sign."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e0ca1920",
+ "metadata": {},
+ "source": [
+ "So we have two **distinct** (totally separate) aspects here - the expression, and the assignment."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "90b2d0ab",
+ "metadata": {},
+ "source": [
+ "So what are **expression assignments**?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2065f05",
+ "metadata": {},
+ "source": [
+ "Expression assignments allows us to assign expressions to a variable **inside** an expression, using the `:=` operator (the so-called *walrus* operator)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0c400c75",
+ "metadata": {},
+ "source": [
+ "Confusing? :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "084caec6",
+ "metadata": {},
+ "source": [
+ "Let's take a look at a very simple example first:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "985d592b",
+ "metadata": {},
+ "source": [
+ "Starting with an expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "c9b56fb0",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b89a8762",
+ "metadata": {},
+ "source": [
+ "We could assign the result of that expression to some variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "225ca5f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1513437a",
+ "metadata": {},
+ "source": [
+ "But, we could also write the expression and assignment this way (not the parentheses that enclose the expression):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "572aaf6a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8d0e2885",
+ "metadata": {},
+ "source": [
+ "With the expression assignment operator, we could actually assign the result of that expression inside the expression itself:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "0fa9c199",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(x := 1 + 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1eafbee8",
+ "metadata": {},
+ "source": [
+ "As you can see, the expression returned a result (`3`), but it also assigned that result to the variable `x`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "915d5b48",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e35a8501",
+ "metadata": {},
+ "source": [
+ "Note that the parentheses in this case are **necessary** - simply writing this would not work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "890070de",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "SyntaxError",
+ "evalue": "invalid syntax (746607632.py, line 1)",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;36m Input \u001b[0;32mIn [10]\u001b[0;36m\u001b[0m\n\u001b[0;31m x := 1 + 2\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
+ ]
+ }
+ ],
+ "source": [
+ "x := 1 + 2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d0b5f281",
+ "metadata": {},
+ "source": [
+ "This is because the `:=` operator must be used inside an **expression**, so we can force it by using the parentheses."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3195a0a8",
+ "metadata": {},
+ "source": [
+ "We could even do this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "6d1e232c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = (x := 10 + 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "35a7ed36",
+ "metadata": {},
+ "source": [
+ "Then, `a`, and `x` are:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "96bf1532",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(30, 30)"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a, x"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "638c195a",
+ "metadata": {},
+ "source": [
+ "Yeah, even more confusing! But in a minute I'll show you why this can be very useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a625536",
+ "metadata": {},
+ "source": [
+ "Before we move on to that, let's see how this assignment expression works when we deal with mutable objects such as lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "a2ee53ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = (l2 := [1, 2] + [3, 4])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e58d69f",
+ "metadata": {},
+ "source": [
+ "Here, `l1` was the result of the concatenation of the two lists:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "2d3ae1a4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l1, id(l1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "88aee44a",
+ "metadata": {},
+ "source": [
+ "But what about `l2`? It should be a list with the same values, but is it the same object reference as `l1`?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "fc8fe138",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "([1, 2, 3, 4], 4393044992)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l2, id(l2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "243f0d28",
+ "metadata": {},
+ "source": [
+ "And indeed, they are not only the same values, but the same object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e7268ec5",
+ "metadata": {},
+ "source": [
+ "Usually this is not an issue, but keep it in mind because you end up with shared references that you may not realize exist."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e27c849e",
+ "metadata": {},
+ "source": [
+ "So now, why is this useful?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a57d9679",
+ "metadata": {},
+ "source": [
+ "Often, we end up writing expressions in terms of other sub expressions, not just for clarity, but sometimes to **avoid repeating** function calls or expression evaluations."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9a686538",
+ "metadata": {},
+ "source": [
+ "#### Example 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3131d1f1",
+ "metadata": {},
+ "source": [
+ "Suppose we have some long running function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "f66dd3b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import time\n",
+ "import math\n",
+ "\n",
+ "def slow_function(x, y):\n",
+ " time.sleep(0.5)\n",
+ " return round(math.sqrt(x**2 + y**2))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9ddce261",
+ "metadata": {},
+ "source": [
+ "Now executing this function will take about 2 seconds to run every time it is called, even when calling it with the same values (we could of course use some LRU caching, but only if the function is **deterministic** - if the function is reading data from a web site, or a database, the result for the same arguments may not be the same and so LRU caching is not even a viable option in this case).\n",
+ "\n",
+ "> A **deterministic** function is a function that for the **same** inputs, always returns the **same** result:\n",
+ ">\n",
+ "> Obviously the function we have above is deterministic, but this one would not be:\n",
+ ">```\n",
+ ">def get_price(symbol):\n",
+ "> # query an API for latest price for symbol\n",
+ "> price = ...\n",
+ "> return price\n",
+ ">``` \n",
+ "> A function that returns the current date or time, or a random number, etc are all non-deterministic functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6e503d9b",
+ "metadata": {},
+ "source": [
+ "So, LRU caching is not always an option."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "05027bcc",
+ "metadata": {},
+ "source": [
+ "Let's see an example of why we would want to assign the result of our long running function to a variable, instead of just using it directly."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "a9babf8f",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "from time import perf_counter\n",
+ "\n",
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " if slow_function(i, i) % 2 == 0:\n",
+ " even_results.append(slow_function(i, i))\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3bdd4e15",
+ "metadata": {},
+ "source": [
+ "Well that was painfully slow!\n",
+ "\n",
+ "But notice that we are calling the same function, with the same arguments twice - we can eliminate that!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "19453896",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = []\n",
+ "for i in range(10):\n",
+ " result = slow_function(i, i)\n",
+ " if result % 2 == 0:\n",
+ " even_results.append(result)\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b6091cb",
+ "metadata": {},
+ "source": [
+ "So we are able to speed this code up, by using that interim `result` variable - also note how `result` is basically a throw away variable (we typically would not use such a variable outside the loop itself - exceptions happen of course)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8acf631f",
+ "metadata": {},
+ "source": [
+ "But notice something about that code? It's ugly looking - we are building up a list by running through a loop and adding to an initially empty list, one element at a time."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6293f28c",
+ "metadata": {},
+ "source": [
+ "We can do better! List comprehensions of course."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9cdff5a7",
+ "metadata": {},
+ "source": [
+ "But... we can't write that `result = slow_function(i, i)` in our list comprehension - so we would be back to the original (and slower) may of doing it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0d89b92d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 7.6 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " slow_function(i, i)\n",
+ " for i in range(10)\n",
+ " if slow_function(i, i) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8db81b84",
+ "metadata": {},
+ "source": [
+ ":-("
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6c42d90a",
+ "metadata": {},
+ "source": [
+ "And this is where the assignment expression operator comes in very handy:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "eefb7ce7",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 4, 6, 8, 10]\n",
+ "Elapsed: 5.0 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "start = perf_counter()\n",
+ "even_results = [\n",
+ " result\n",
+ " for i in range(10)\n",
+ " if (result := slow_function(i, i)) % 2 == 0\n",
+ "]\n",
+ "end = perf_counter()\n",
+ "print(even_results)\n",
+ "print(f'Elapsed: {end - start:.1f} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c1c77b0c",
+ "metadata": {},
+ "source": [
+ "Notice how using the `:=` operator, we assign the result of `slow_function(i, i)` to `result` as part of the expression itself, and then re-use that computed value for the elements of the list."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a9e3744d",
+ "metadata": {},
+ "source": [
+ "You may be asking yourself, why not write it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "db2bc22b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del result"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "cd112bb8",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'result' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m| \u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[1;32m 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m result \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "Input \u001b[0;32mIn [22]\u001b[0m, in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m 1\u001b[0m even_results \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m (result \u001b[38;5;241m:=\u001b[39m slow_function(i, i))\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(\u001b[38;5;241m10\u001b[39m)\n\u001b[0;32m----> 4\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mresult\u001b[49m \u001b[38;5;241m%\u001b[39m \u001b[38;5;241m2\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m\n\u001b[1;32m 5\u001b[0m ]\n",
+ "\u001b[0;31mNameError\u001b[0m: name 'result' is not defined"
+ ]
+ }
+ ],
+ "source": [
+ "even_results = [\n",
+ " (result := slow_function(i, i))\n",
+ " for i in range(10)\n",
+ " if result % 2 == 0\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5c0229a0",
+ "metadata": {},
+ "source": [
+ "This happens because in a list comprehension, the loop starts running, then the `if` clause (if any) is evaluated, and then the element expression is evaluated - hence why we place the assignment expression in the `if`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cc652ad3",
+ "metadata": {},
+ "source": [
+ "**Example 2**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "093978ca",
+ "metadata": {},
+ "source": [
+ "Here's another scenario where this new operator could be quite useful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "edbdc1b7",
+ "metadata": {},
+ "source": [
+ "You want to return the result of an expression but only if it satisfies some criteria.\n",
+ "\n",
+ "For example, let's say we write a generator function to produce n even random integers between 1 and 10:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "a75a9138",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import random\n",
+ "\n",
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while cnt <= n:\n",
+ " cnt += 1\n",
+ " number = random.randint(0, 10)\n",
+ " if number % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9f19d723",
+ "metadata": {},
+ "source": [
+ "We can then call the generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "53f19b5e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76ac9cf0",
+ "metadata": {},
+ "source": [
+ "We can make our code a little more concise without losing readability by using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "b849d145",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "random.seed(0)\n",
+ "def even_random(n):\n",
+ " cnt = 0\n",
+ " while (cnt := cnt + 1) <= n:\n",
+ " if (number := random.randint(0, 10)) % 2 == 0:\n",
+ " yield number"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "b847739e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[6, 6, 0, 4, 8]"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(even_random(5))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5621f621",
+ "metadata": {},
+ "source": [
+ "#### Example 3"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e1719fd",
+ "metadata": {},
+ "source": [
+ "Here's another example where we are consuming some generator, until some condition is met."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9822e4d5",
+ "metadata": {},
+ "source": [
+ "Let's write a generator function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "623069a1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def gen():\n",
+ " while True:\n",
+ " yield list(range(random.randint(0, 10)))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "da617a93",
+ "metadata": {},
+ "source": [
+ "And let's print out a frew values from this generator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "56b83447",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[]\n",
+ "[0]\n",
+ "[0, 1]\n",
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4, 5, 6, 7]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "for _ in range(10):\n",
+ " print(next(my_gen))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ad1bb10e",
+ "metadata": {},
+ "source": [
+ "You'll notice that the fourth element is a list with 2 values.\n",
+ "\n",
+ "What we want to do now, is process the lists yielded by the generator, until we hit a list with two values, at which point we want to stop processing it."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "25d4dab3",
+ "metadata": {},
+ "source": [
+ "We could do it this way with a `while` loop:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "f5a068ab",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while True:\n",
+ " l = next(my_gen)\n",
+ " if len(l) <= 2:\n",
+ " break\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fcf1f1a2",
+ "metadata": {},
+ "source": [
+ "Instead, we could re-write this way using the `:=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "7568cf9c",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[0, 1, 2]\n",
+ "[0, 1, 2, 3, 4]\n",
+ "[0, 1, 2, 3, 4, 5]\n"
+ ]
+ }
+ ],
+ "source": [
+ "random.seed(8)\n",
+ "my_gen = gen()\n",
+ "while len(l := next(my_gen)) > 2:\n",
+ " print(l)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d9f1b587",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 3/Section 11 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb b/Part 3/Section 11 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
new file mode 100644
index 00000000..699f8626
--- /dev/null
+++ b/Part 3/Section 11 - Python Updates/04 - Relevant Python 3.8_3.7 Changes.ipynb
@@ -0,0 +1,1476 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "c314393b",
+ "metadata": {},
+ "source": [
+ "### Relevant Python 3.8 Changes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cbe45497",
+ "metadata": {},
+ "source": [
+ "The release of Python 3.8 has brought some new features.\n",
+ "\n",
+ "This is a summary of the ones _I_ deemed relevant to this course, and does **not** include all the changes!\n",
+ "\n",
+ "For full release details, see [here](https://docs.python.org/3/whatsnew/3.8.html)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7089277d",
+ "metadata": {},
+ "source": [
+ "#### Positional Only Parameters"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "61154c87",
+ "metadata": {},
+ "source": [
+ "It is now possible to define **positional-only** parameters for Python functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "63037bda",
+ "metadata": {},
+ "source": [
+ "As we saw earlier in this course, when you define positional parameters in a function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "13c1ba59",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a4928079",
+ "metadata": {},
+ "source": [
+ "the user is free to pass arguments either positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "0bb6fea5",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "be1cfa90",
+ "metadata": {},
+ "source": [
+ "or, as named arguments:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "cb04e54f",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(b=2, a=1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "617077dd",
+ "metadata": {},
+ "source": [
+ "Some functions in Python's built-ins ared defined in such a way that certain parameters can **only** be passed positionally, for example the `print` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "77c6fa8a",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on built-in function print in module builtins:\n",
+ "\n",
+ "print(...)\n",
+ " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n",
+ " \n",
+ " Prints the values to a stream, or to sys.stdout by default.\n",
+ " Optional keyword arguments:\n",
+ " file: a file-like object (stream); defaults to the current sys.stdout.\n",
+ " sep: string inserted between values, default a space.\n",
+ " end: string appended after the last value, default a newline.\n",
+ " flush: whether to forcibly flush the stream.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(print)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "248c2581",
+ "metadata": {},
+ "source": [
+ "That `value` cannot be passed by name:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "529c5dac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "'value' is an invalid keyword argument for print()\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(value=\"hello\")\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f4baed67",
+ "metadata": {},
+ "source": [
+ "Instead, the parameter **must** be passed positionally:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "8c147557",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(\"hello\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2840374",
+ "metadata": {},
+ "source": [
+ "Until Python 3.8, it was not possible to reproduce such behavior with user-defined functions."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "158674a9",
+ "metadata": {},
+ "source": [
+ "Now you can, by using the slash character(`/`). Parameters defined **before** the `/` become **positional-only** parameters:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "aeebd0f8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /):\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "858727b6",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "4f73c741",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "my_func() got some positional-only arguments passed as keyword arguments: 'a, b'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " my_func(a=1, b=2)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f5967700",
+ "metadata": {},
+ "source": [
+ "You can of course mix this along with the special parameters `*` and `**`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "d17254b3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, /, *, c):\n",
+ " print(a + b + c)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "b35d884e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "13\n"
+ ]
+ }
+ ],
+ "source": [
+ "my_func(1, 2, c=10)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "573aca30",
+ "metadata": {},
+ "source": [
+ "#### f-string Enhancements"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "89ee51f9",
+ "metadata": {},
+ "source": [
+ "Often we use f-strings to interpolate the name of a variable and it's value:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "f79a630b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "a, b = \"hello\", \"world\"\n",
+ "print(f\"a={a}, b={b}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "24747607",
+ "metadata": {},
+ "source": [
+ "Python 3.8 provides a shortcut way of doing the same thing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "3ae5c0c4",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a='hello', b='world'\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=}, {b=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "141558b4",
+ "metadata": {},
+ "source": [
+ "You can even use [format specifiers](https://docs.python.org/3/library/string.html#formatspec)\n",
+ "to further customize the output:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "e75716ac",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "a=hello, b=world\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{a=:s}, {b=:s}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4dcdc5d0",
+ "metadata": {},
+ "source": [
+ "Or when dealing with other types:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "362bf6b5",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime\n",
+ "from math import pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "c91b7536",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = datetime.utcnow()\n",
+ "e = pi"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "545c77a2",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=datetime.datetime(2022, 3, 20, 6, 1, 13, 990493), e=3.141592653589793\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=}, {e=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4637ecd5",
+ "metadata": {},
+ "source": [
+ "And applying some format specifiers:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "75c4052b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "d=2022-03-20 06:01:13, e=3.142\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f\"{d=:%Y-%m-%d %H:%M:%S}, {e=:.3f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "076773ed",
+ "metadata": {},
+ "source": [
+ "It will even display the text of an expression if you use one in your f-string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "0ce46ace",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1 + 2=3, ' '.join(sentence)='Python rocks!'\n"
+ ]
+ }
+ ],
+ "source": [
+ "sentence = [\"Python\", \"rocks!\"]\n",
+ "print(f\"{1 + 2=}, {' '.join(sentence)=}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9e3783ea",
+ "metadata": {},
+ "source": [
+ "#### The `as_integer_ratio()` Method"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "15ccd5ad",
+ "metadata": {},
+ "source": [
+ "The types `bool`, `int` and `Fraction` now all implement an `as_integer_ratio()` method which returns a tuple consisting of the numerator and denominator. Remember that `Decimal` and `float` already implement the same method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "8313fc80",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from fractions import Fraction"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "7a1ae84a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "f = Fraction(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "id": "a94fc3ed",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(2, 3)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "f.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "id": "f32942ec",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(12, 1)"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 12\n",
+ "a.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "id": "06980a8c",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 1)"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "flag = True\n",
+ "flag.as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a3091e0e",
+ "metadata": {},
+ "source": [
+ "The advantage of this is mainly for polymorphism (or duck-typing), where you can now use `as_integer_ratio` irrespective of whether the variable is a `bool`, an `int`, a `float`, a `Decimal` or a `Fraction`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "id": "8a362bf8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from decimal import Decimal"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "id": "ab4a78aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(33, 100)"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Decimal(\"0.33\").as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "5ee29a47",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(7070651414971679, 2251799813685248)"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(3.14).as_integer_ratio()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "df1e85de",
+ "metadata": {},
+ "source": [
+ "#### The `lru_cache` decorator"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "226efb47",
+ "metadata": {},
+ "source": [
+ "As we saw in this course, we can use the `lru_cache` decorator to appky an LRU cache to our functions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "20501526",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import lru_cache"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "07d699f0",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache(maxsize=3)\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "id": "45a0cd5a",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fea747d4",
+ "metadata": {},
+ "source": [
+ "If we don't specify `maxsize`, it will default to `128`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "id": "447be276",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache()\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "id": "53fee4fd",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "354224848179261915075"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "fib(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5cf8e33a",
+ "metadata": {},
+ "source": [
+ "The change made to this decorator in Python 3.8 allows us not to use those empty parentheses:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "id": "4185658b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@lru_cache\n",
+ "def fib(n):\n",
+ " if n <=2 :\n",
+ " return 1\n",
+ " else:\n",
+ " return fib(n-1) + fib(n-2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "76a9aed5",
+ "metadata": {},
+ "source": [
+ "#### `math` Module"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0af410c0",
+ "metadata": {},
+ "source": [
+ "Many examples I use throughout this course calculate the Euclidean distance between two points:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "id": "b511addc",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "id": "0b66c006",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "1.4142135623730951\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = (0, 0)\n",
+ "b = (1, 1)\n",
+ "\n",
+ "dist = math.sqrt((b[0] - a[1]) ** 2 + (b[1] - a[1]) ** 2)\n",
+ "print(dist)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d276589d",
+ "metadata": {},
+ "source": [
+ "Now, it's much easier using the `dist()` function the `math` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "id": "1f774757",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1.4142135623730951"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math.dist(a, b)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "13afb1f1",
+ "metadata": {},
+ "source": [
+ "#### The `namedtuple` Implementation"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a22a839e",
+ "metadata": {},
+ "source": [
+ "Actually these changes were added to Python 3.7, but since I don't have a separate lecture for Python 3.7 changes (most did not apply to this course), here it is."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1a579fbb",
+ "metadata": {},
+ "source": [
+ "The `_source` attribute was **removed**. There quite a discussion on this, and the the core dev who implemented and supported this essentially gave up trying to keep this in - it was deemed to cause too much \"overhead\". So, sadly (wearing my teacher's hat), it is gone. It is no more. It's not pining, it's just dead. :-)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d5e3bfd0",
+ "metadata": {},
+ "source": [
+ "The method I showed you for defining defaults for named tuples still works, and could still be used, but Python 3.7 added the `defaults` parameter to the named tuple definition."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "id": "3538a2c2",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import namedtuple"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "id": "024bcc51",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults=(10, 20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "id": "9dd8a877",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "id": "db7f47e7",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 40,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fb0bc811",
+ "metadata": {},
+ "source": [
+ "You don't have to specify defaults for everything, but if you do not, be aware that defaults will be applied from **right** to **left**. Which makes sense given that in Python non-defaulted parameters must be defined **before** defaulted parameters."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "id": "8f6ad2ca",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = (20, 30))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "id": "bc9d5345",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "id": "eceeaec2",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=10, b=20, c=30)"
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "64188b1c",
+ "metadata": {},
+ "source": [
+ "Note that with this way of specifying defaults you can easily define the same default for all items in the named tuple using the `*` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "id": "8b36d7c3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c d e f\", defaults=(\"xyz\",) * 6)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "id": "1d448806",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "id": "b16758de",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a='xyz', b='xyz', c='xyz', d='xyz', e='xyz', f='xyz')"
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bbcbaf53",
+ "metadata": {},
+ "source": [
+ "Just be careful if you use a **mutable** type to do this!!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "id": "91b28470",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a b c\", defaults = ([],) * 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "id": "cad11f5c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt = NT()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "id": "0cb7ceac",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[], b=[], c=[])"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "id": "466d9520",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nt.a.append(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "id": "74826099",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[10]"
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt.a"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6d00b122",
+ "metadata": {},
+ "source": [
+ "But watch this!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "id": "4759e6f4",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NT(a=[10], b=[10], c=[10])"
+ ]
+ },
+ "execution_count": 52,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nt"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "972c666e",
+ "metadata": {},
+ "source": [
+ "I hope you understand what happened here without me telling you!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6590d73a",
+ "metadata": {},
+ "source": [
+ "The **same** list object was re-used 3 times in the defaults."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "720e13bb",
+ "metadata": {},
+ "source": [
+ "You can easily recover your defaults using the `_field_defaults` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "id": "586498ae",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "NT = namedtuple(\"NT\", \"a, b, c\", defaults=(1, 2, 3))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "id": "20f4012e",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 1, 'b': 2, 'c': 3}"
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "NT._field_defaults"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "70c3a717",
+ "metadata": {},
+ "source": [
+ "One change of note in Python 3.8, the `_as_dict()` method now returns a standard dictionary (key ordered in the same way as the named tuple). Prior to this version, it would return an `OrderedDict` since standard Python dictionaries did not guarantee any specific key order, but since they now do, there's no need to use the `DefaultDict` anymore."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ecb5b3a0",
+ "metadata": {},
+ "source": [
+ "#### Other Things"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9d8ec24b",
+ "metadata": {},
+ "source": [
+ "These are few other odds and ends that you might find of interest:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3602bbab",
+ "metadata": {},
+ "source": [
+ "The built-in `reversed` function now works with dictionary views:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "id": "4f68e46b",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = {'a': 1, 'b': 2}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "id": "83fc356d",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['a', 'b']"
+ ]
+ },
+ "execution_count": 56,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(d.keys())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "id": "10648abb",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['b', 'a']"
+ ]
+ },
+ "execution_count": 57,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.keys()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "id": "4a4885c3",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[2, 1]"
+ ]
+ },
+ "execution_count": 58,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.values()))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 59,
+ "id": "13785eb9",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('b', 2), ('a', 1)]"
+ ]
+ },
+ "execution_count": 59,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(reversed(d.items()))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e14d5c14",
+ "metadata": {},
+ "source": [
+ "The `continue` statement was not permitted in the `finally` clause of a loop, but is now supported."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fe507127",
+ "metadata": {},
+ "source": [
+ "Earlier in Part 1, we discussed string interning, as well as how a small selection of integers are essentially \"cached\" by Python and re-used whenever the literal is encountered. This meant we could use `is` instead of `==` in some cases, and that helped us get a clearer understanding of what's going on. **BUT**, as we also discussed, you should **not**, in practice, use `is` for comparing objects such as integers, strings, etc (usually we are more interested in whether is the same value, rather than the identical object) - the fact that this works is an implementation detail and not guaranteed to work the same way from one Python version to another.\n",
+ "\n",
+ "Although linters will usually catch those kinds of issues, not everyone uses a Python linter - so Python 3.8 will now emit a **warning** if you compare variables of certain types with literal constants!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 60,
+ "id": "e659956e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/3780910533.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 1\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 60,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 1\n",
+ "a is 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 61,
+ "id": "d970904d",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "<>:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ "/var/folders/kg/20pf1n8j6pjg09bwxz6cgw0r0000gn/T/ipykernel_33116/4272392880.py:2: SyntaxWarning: \"is\" with a literal. Did you mean \"==\"?\n",
+ " a is 'hello'\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 61,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = 'hello'\n",
+ "a is 'hello'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "01c01a49",
+ "metadata": {},
+ "source": [
+ "But we do not get a warning in a situation such as this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 62,
+ "id": "c0d535bc",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 62,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a = [1, 2, 3]\n",
+ "\n",
+ "a is [1, 2, 3]"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.10.2"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/Part 3/Section 12 - Extras/01 - MappingProxyType.ipynb b/Part 3/Section 12 - Extras/01 - MappingProxyType.ipynb
new file mode 100644
index 00000000..07ce4485
--- /dev/null
+++ b/Part 3/Section 12 - Extras/01 - MappingProxyType.ipynb
@@ -0,0 +1,371 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### MappingProxyType"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The mapping proxy type is an easy way to create a read-only **view** of any dictionary.\n",
+ "\n",
+ "This can be handy if you want to pass a dictionary around, and have that view reflect the underlying dictionary (even if it is mutated), but not allow the receiver to be able to modify the dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In fact, this is used by classes all the time:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Test:\n",
+ " a = 100"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'a': 100,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Test.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, what is returned here is not actually a `dict` object, but a `mappingproxy`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To create a mapping proxy from a dictionary we use the `MappingProxyType` from the `types` module:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from types import MappingProxyType"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = {'a': 1, 'b': 2}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "mp = MappingProxyType(d)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This mapping proxy still behaves like a dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['a', 'b']"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(mp.keys())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[1, 2]"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(mp.values())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('a', 1), ('b', 2)]"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(mp.items())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mp.get('a', 'not found')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'not found'"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mp.get('c', 'not found')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But we cannot mutate it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "TypeError: 'mappingproxy' object does not support item assignment\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " mp['a'] = 100\n",
+ "except TypeError as ex:\n",
+ " print('TypeError: ', ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "On the other hand, if the underlying dictionary is mutated:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d['a'] = 100\n",
+ "d['c'] = 'new item'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 100, 'b': 2, 'c': 'new item'}"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'a': 100, 'b': 2, 'c': 'new item'})"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "mp"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And as you can see, the mapping proxy \"sees\" the changes in the undelying dictionary - so it behaves like a view, in the same way `keys()`, `values()` and `items()` do."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can obtain a **shallow** copy of the proxy by using the `copy()` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "cp = mp.copy()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'a': 100, 'b': 2, 'c': 'new item'}"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cp"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, `cp` is a plain `dict`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.7.4"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/01 - Objects and Classes.ipynb b/Part 4/Section 02 - Classes/01 - Objects and Classes.ipynb
new file mode 100644
index 00000000..8e65f24e
--- /dev/null
+++ b/Part 4/Section 02 - Classes/01 - Objects and Classes.ipynb
@@ -0,0 +1,469 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Objects and Classes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A class is a type of object. In Python we create classes using the `class` keyword."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now this class doesn't do much, but it is an object of type `type` (which is itself an object)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "type"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(Person)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "type"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(type)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Classes have \"built-in\" attributes, even though we did not specifically add any to the class ourselves.\n",
+ "\n",
+ "For example, they have a name:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Person'"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__name__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "They are also callables, and calling a class results in the creation and return of a new **instance** of that class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now the type of the object is the class used to build that object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Person"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "These instances also have \"built_in\" properties, which we will cover throughout this course.\n",
+ "\n",
+ "For example, they have a `__class__` property that tells us which class was used to create the instance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Person"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see that returns the class object used to instantiate `p`.\n",
+ "\n",
+ "In fact:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p) is p.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can also use `isinstance` to test if an object is an instance of a particular class - now this gets a bit more complicated when we use inheritance, but right now we're not, so it's quite straightforward:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(p, Person)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(p, str)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can even use `isinstance` with our class, since we know it's type is `type`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(Person, type)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`type` is like the most generic kind of **class** object - we'll come back to this when discussing meta programming.\n",
+ "\n",
+ "We really need inheritance to understand how this works, but every class **is** a `type` object (it inherits all the properties of `type`).\n",
+ "\n",
+ "For now let's just see what functionality `type` has:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on class type in module builtins:\n",
+ "\n",
+ "class type(object)\n",
+ " | type(object_or_name, bases, dict)\n",
+ " | type(object) -> the object's type\n",
+ " | type(name, bases, dict) -> a new type\n",
+ " | \n",
+ " | Methods defined here:\n",
+ " | \n",
+ " | __call__(self, /, *args, **kwargs)\n",
+ " | Call self as a function.\n",
+ " | \n",
+ " | __delattr__(self, name, /)\n",
+ " | Implement delattr(self, name).\n",
+ " | \n",
+ " | __dir__(...)\n",
+ " | __dir__() -> list\n",
+ " | specialized __dir__ implementation for types\n",
+ " | \n",
+ " | __getattribute__(self, name, /)\n",
+ " | Return getattr(self, name).\n",
+ " | \n",
+ " | __init__(self, /, *args, **kwargs)\n",
+ " | Initialize self. See help(type(self)) for accurate signature.\n",
+ " | \n",
+ " | __instancecheck__(...)\n",
+ " | __instancecheck__() -> bool\n",
+ " | check if an object is an instance\n",
+ " | \n",
+ " | __new__(*args, **kwargs)\n",
+ " | Create and return a new object. See help(type) for accurate signature.\n",
+ " | \n",
+ " | __prepare__(...)\n",
+ " | __prepare__() -> dict\n",
+ " | used to create the namespace for the class statement\n",
+ " | \n",
+ " | __repr__(self, /)\n",
+ " | Return repr(self).\n",
+ " | \n",
+ " | __setattr__(self, name, value, /)\n",
+ " | Implement setattr(self, name, value).\n",
+ " | \n",
+ " | __sizeof__(...)\n",
+ " | __sizeof__() -> int\n",
+ " | return memory consumption of the type object\n",
+ " | \n",
+ " | __subclasscheck__(...)\n",
+ " | __subclasscheck__() -> bool\n",
+ " | check if a class is a subclass\n",
+ " | \n",
+ " | __subclasses__(...)\n",
+ " | __subclasses__() -> list of immediate subclasses\n",
+ " | \n",
+ " | mro(...)\n",
+ " | mro() -> list\n",
+ " | return a type's method resolution order\n",
+ " | \n",
+ " | ----------------------------------------------------------------------\n",
+ " | Data descriptors defined here:\n",
+ " | \n",
+ " | __abstractmethods__\n",
+ " | \n",
+ " | __dict__\n",
+ " | \n",
+ " | __text_signature__\n",
+ " | \n",
+ " | ----------------------------------------------------------------------\n",
+ " | Data and other attributes defined here:\n",
+ " | \n",
+ " | __base__ = \n",
+ " | The most base type\n",
+ " | \n",
+ " | __bases__ = (,)\n",
+ " | \n",
+ " | __basicsize__ = 864\n",
+ " | \n",
+ " | __dictoffset__ = 264\n",
+ " | \n",
+ " | __flags__ = 2148291584\n",
+ " | \n",
+ " | __itemsize__ = 40\n",
+ " | \n",
+ " | __mro__ = (, )\n",
+ " | \n",
+ " | __weakrefoffset__ = 368\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(type)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see it has a `__call__` method (that's how our class becomes callable), and a bunch of other attributes and methods that we'll see throughout this course.\n",
+ "\n",
+ "Our class objects also have these properties, because they inherit from the `type` object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And in fact, `type` is an instance of itself - that's kind of weird, and not the case for our own classes:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(type, type)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(Person, Person)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/02 - Class Attributes.ipynb b/Part 4/Section 02 - Classes/02 - Class Attributes.ipynb
new file mode 100644
index 00000000..94797e2d
--- /dev/null
+++ b/Part 4/Section 02 - Classes/02 - Class Attributes.ipynb
@@ -0,0 +1,609 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Class Attributes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we saw, when we create a class Python automatically builds-in properties and behaviors into our class object, like making it callable, and properties like `__name__`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Person'"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__name__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`__name__` is a **class attribute**. We can add our own class attributes easily this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Program:\n",
+ " language = 'Python'\n",
+ " version = '3.6'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Program'"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__name__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Python'"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.language"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.6'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.version"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here we used \"dotted notation\" to access the class attributes. In fact we can also use dotted notation to set the class attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Program.version = '3.7'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7'"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.version"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But we can also use the functions `getattr` and `setattr` to read and write these attributes:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7'"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "getattr(Program, 'version')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(Program, 'version', '3.6')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('3.6', '3.6')"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.version, getattr(Program, 'version')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Python is a dynamic language, and we can create attributes at run-time, outside of the class definition itself:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Program.x = 100"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Using dotted notation we added an attribute `x` to the Person class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(100, 100)"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.x, getattr(Program, 'x')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could also just have used a `setattr` function call:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(Program, 'y', 200)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(200, 200)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.y, getattr(Program, 'y')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So where is the state stored? Usually in a dictionary that is attached to the **class** object (often referred to as the **namespace** of the class):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'version': '3.6',\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None,\n",
+ " 'x': 100,\n",
+ " 'y': 200})"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see that dictionary contains our attributes: `language`, `version`, `x`, `y` with their corresponding current values."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Notice also that `Program.__dict__` does not return a dictionary, but a `mappingproxy` object - this is essentially a read-only dictionary that we cannot modify directly (but we can modify it by using `setattr`, or dotted notation)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example, if we change the value of an attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(Program, 'x', -10)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We'll see this reflected in the underlying dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'version': '3.6',\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None,\n",
+ " 'x': -10,\n",
+ " 'y': 200})"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Deleting Attributes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, we can create and mutate class attributes at run-time. Can we delete attributes too?\n",
+ "\n",
+ "The answer of course is yes. We can either use the `del` keyword, or the `delattr` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del Program.x"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'version': '3.6',\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None,\n",
+ " 'y': 200})"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "delattr(Program, 'y')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Direct Namespace Access"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'version': '3.6',\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although `__dict__` returns a `mappingproxy` object, it still is a hash map and essentially behaves like a read-only dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Python'"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__['language']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[('__module__', '__main__'),\n",
+ " ('language', 'Python'),\n",
+ " ('version', '3.6'),\n",
+ " ('__dict__', ),\n",
+ " ('__weakref__', ),\n",
+ " ('__doc__', None)]"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "list(Program.__dict__.items())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "One word of caution: not every attribute that a class has lives in that dictionary (we'll come back to this later).\n",
+ "\n",
+ "For example, you'll notice that the `__name__` attribute is not there:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Program'"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__name__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\"__name__\" in Program.__dict__"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.9.10"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/03 - Callable Class Attributes.ipynb b/Part 4/Section 02 - Classes/03 - Callable Class Attributes.ipynb
new file mode 100644
index 00000000..cc127305
--- /dev/null
+++ b/Part 4/Section 02 - Classes/03 - Callable Class Attributes.ipynb
@@ -0,0 +1,179 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Callable Class Attributes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Class attributes can be any object type, including callables such as functions:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Program:\n",
+ " language = 'Python'\n",
+ " \n",
+ " def say_hello():\n",
+ " print(f'Hello from {Program.language}!')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'say_hello': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see, the `say_hello` symbol is in the class dictionary.\n",
+ "\n",
+ "We can also retrieve it using either `getattr` or dotted notation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(,\n",
+ " )"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.say_hello, getattr(Program, 'say_hello')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course we can call it, since it is a callable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello from Python!\n"
+ ]
+ }
+ ],
+ "source": [
+ "Program.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello from Python!\n"
+ ]
+ }
+ ],
+ "source": [
+ "getattr(Program, 'say_hello')()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can even access it via the namespace dictionary as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello from Python!\n"
+ ]
+ }
+ ],
+ "source": [
+ "Program.__dict__['say_hello']()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/04 - Classes are Callable.ipynb b/Part 4/Section 02 - Classes/04 - Classes are Callable.ipynb
new file mode 100644
index 00000000..20811109
--- /dev/null
+++ b/Part 4/Section 02 - Classes/04 - Classes are Callable.ipynb
@@ -0,0 +1,322 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Classes are Callable"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we saw earlier, one of the things Python does for us when we create a class is to make it callable.\n",
+ "\n",
+ "Calling a class creates a new instance of the class - an object of that particular type."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Program:\n",
+ " language = 'Python'\n",
+ " \n",
+ " def say_hello():\n",
+ " print(f'Hello from {Program.language}!')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Program()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Program"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(p, Program)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "These instances have their own namespace, and their own `__dict__` that is distinct from the class `__dict__`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'language': 'Python',\n",
+ " 'say_hello': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Program.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Instances also have attributes that may not be visible in their `__dict__` (they are being stored elsewhere, as we'll examine later):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Program"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although we can use `__class__` we can also use `type`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p) is p.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Generally we use `type` instead of using `__class__` just like we usually use `len()` instead of accessing `__len__`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Why? Well, one reason is that people can mess around with the `__class__` attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyClass:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "m = MyClass()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(__main__.MyClass, __main__.MyClass)"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(m), m.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But look at what happens here:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyClass:\n",
+ " __class__ = str"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "m = MyClass()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(__main__.MyClass, str)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(m), m.__class__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So as you can see, `type` wasn't fooled!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/05 - Data Attributes.ipynb b/Part 4/Section 02 - Classes/05 - Data Attributes.ipynb
new file mode 100644
index 00000000..d4746ca9
--- /dev/null
+++ b/Part 4/Section 02 - Classes/05 - Data Attributes.ipynb
@@ -0,0 +1,648 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Data Attributes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's focus on data attributes first (non-callables).\n",
+ "\n",
+ "As we saw before we can have class attributes - they live in the class dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class BankAccount:\n",
+ " apr = 1.2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'apr': 1.2,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "BankAccount.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1.2"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "BankAccount.apr"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now when we create instances of that class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "acc_1 = BankAccount()\n",
+ "acc_2 = BankAccount()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The instance dictionaries are currently empty:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "({}, {})"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.__dict__, acc_2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Yet, these instances do have an `apr` attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1.2, 1.2)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.apr, acc_2.apr"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Where is that value coming from? The class the objects were created from!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In fact, if we modify the class attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "BankAccount.apr = 2.5"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We'll see this reflected in the instances as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(2.5, 2.5)"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.apr, acc_2.apr"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And if we a a class attribute to `BankAccount`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "BankAccount.account_type = 'Savings'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('Savings', 'Savings')"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.account_type, acc_2.account_type"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see modifying attributes in the **class** are reflected in the instances too - that's because Python does not find an `apr` attribute in the instance dic tionary, so next it looks in the class that was used to create the instance.\n",
+ "\n",
+ "Which raises the question, what happens if we add `apr` to the **instance** dictionary?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "acc_1.apr = 0"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Well that did not raise an exception - so what's happening now:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "({'apr': 0}, {})"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.__dict__, acc_2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, we actually create an entry for `apr` in the state dictionary of `acc_1`.\n",
+ "\n",
+ "Now that we have it there, it we try to get the attribute value `apr` for `acc_1`, Python will find it in the instance dictionary, so it will use that instead!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(0, 2.5)"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.apr, acc_2.apr"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In effect, the instance attribute `apr` is **hiding** the class attribute.\n",
+ "\n",
+ "You'll notice also that `acc_2` was **not** affected - this is because we did not modify `acc_2`'s dictionary, just the dictionary for `acc_1`.\n",
+ "\n",
+ "And the `getattr` and `setattr` functions work the same way as dotted notation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{}\n",
+ "2.5\n",
+ "2.5\n"
+ ]
+ }
+ ],
+ "source": [
+ "acc_1 = BankAccount()\n",
+ "print(acc_1.__dict__)\n",
+ "print(acc_1.apr)\n",
+ "print(getattr(acc_1, 'apr'))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "{'apr': 0}\n",
+ "0\n",
+ "0\n"
+ ]
+ }
+ ],
+ "source": [
+ "setattr(acc_1, 'apr', 0)\n",
+ "print(acc_1.__dict__)\n",
+ "print(acc_1.apr)\n",
+ "print(getattr(acc_1, 'apr'))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can even add instance attributes directly to an instance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "acc_1.bank = 'Acme Savings & Loans'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'apr': 0, 'bank': 'Acme Savings & Loans'}"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But this is specific to the instance, and only that specific instance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "acc_2 = BankAccount()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see `acc_2` has an empty instance dictionary."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So it is really important to distingush between **class attributes** and **instance attributes**.\n",
+ "\n",
+ "**Class attributes** are like attributes that are \"common\" to all instances - because the attribute does not live in the instance, but in the class itself.\n",
+ "\n",
+ "On the other hand, **instance attributes** are specific to each instance, and values for the same attribute can be different across multiple instances, as we just saw with `acc_1.apr` and `acc_2.apr`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, in summary, classes and instances each have their own state - usually maintained in a dictionary, available through `__dict__`. Irrespective of where the state is stored, when we look up an attribute on an instance, Python will first look for the attribute in the instance's local state. If it does not find it there, it will next look for it in the class of the instance."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "One other thing to note is the difference in type between class and instance `__dict__`.\n",
+ "\n",
+ "Classes as we saw, return a `mapping proxy` object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'apr': 2.5,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None,\n",
+ " 'account_type': 'Savings'})"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "BankAccount.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But instances, return a real dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'apr': 0, 'bank': 'Acme Savings & Loans'}"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "acc_1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So with instances, unlike with classes, we can manipulate that dictionary directly:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Program:\n",
+ " language = 'Python'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Program()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.__dict__['version'] = '3.7'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'version': '3.7'}"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('3.7', '3.7')"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.version, getattr(p, 'version')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But once again, this only affects that specific **instance**."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/06 - Function Attributes.ipynb b/Part 4/Section 02 - Classes/06 - Function Attributes.ipynb
new file mode 100644
index 00000000..e4975a27
--- /dev/null
+++ b/Part 4/Section 02 - Classes/06 - Function Attributes.ipynb
@@ -0,0 +1,854 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Function Attributes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So far, we have been dealing with non-callable attributes. When attributes are actually functions, things behave differently."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def say_hello():\n",
+ " print('Hello!')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "function"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(Person.say_hello)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see it is just a plain function, and be called as usual:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello!\n"
+ ]
+ }
+ ],
+ "source": [
+ "Person.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's create an instance of that class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f88a06937b8'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We know we can access class attributes via the instance, so we should also be able to access the function attribute in the same way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "method"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p.say_hello)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hmm, the type has changed from `function` to `method`, and the function representation states that it is a **bound method** of the **specific object** `p` we created (notice the memory address)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And if we try to call the function from the instance, here's what happens:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "TypeError say_hello() takes 0 positional arguments but 1 was given\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.say_hello()\n",
+ "except Exception as ex:\n",
+ " print(type(ex).__name__, ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`method` is an actual type in Python, and, like functions, they are callables, but they have one distinguishing feature. They need to be bound to an object, and that object reference is passed to the underlying function.\n",
+ "\n",
+ "Often when we define functions in a class and call them from the instance we need to know which **specific** instance was used to call the function. This allows us to interact with the instance variables.\n",
+ "\n",
+ "To do this, Python will automatically transform an ordinary function defined in a class into a method when it is called from an instance of the class.\n",
+ "\n",
+ "Further, it will \"bind\" the method to the instance - meaning that the instance will be passed as the **first** argument to the function being called.\n",
+ "\n",
+ "It does this using **descriptors** which we'll come back to in detail later.\n",
+ "\n",
+ "For now let's just explore this a bit more:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def say_hello(*args):\n",
+ " print('say_hello args:', args)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "say_hello args: ()\n"
+ ]
+ }
+ ],
+ "source": [
+ "Person.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see, calling `say_hello` from the **class**, just calls the function (it is just a function).\n",
+ "\n",
+ "But when we call it from an instance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f88d0428748'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p = Person()\n",
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "say_hello args: (<__main__.Person object at 0x7f88d0428748>,)\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You can see that the object `p` was passed as an argument to the class function `say_hello`.\n",
+ "\n",
+ "The obvious advantage is that we can now interact with instance attributes easily:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def set_name(instance_obj, new_name):\n",
+ " instance_obj.name = new_name # or setattr(instance_obj, 'name', new_name)\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.set_name('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Alex'}"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "\n",
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This has essentially the same effect as doing this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Person.set_name(p, 'John')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'John'}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By convention, the first argument is usually named `self`, but asd you just saw we can name it whatever we want - it just will be in the instance when the method variant of the function is called - and it is called an **instance method**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But **methods** are objects created by Python when calling class functions from an instance.\n",
+ "\n",
+ "They have their own unique attributes too:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def say_hello(self):\n",
+ " print(f'{self} says hello')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "m_hello = p.say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "method"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(m_hello)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example it has a `__func__` attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "m_hello.__func__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "which happens to be the class function used to create the method (the underlying function)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But remember that a method is bound to an instance. In this case we got the method from the `p` object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f88d0428c18'"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "<__main__.Person at 0x7f88d0428c18>"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "m_hello.__self__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, the method also has a reference to the object it is **bound** to."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So think of methods as functions that have been bound to a specific object, and that object is passed in as the first argument of the function call. The remaining arguments are then passed after that."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Instance methods are created automatically for us, when we define functions inside our class definitions.\n",
+ "\n",
+ "This even holds true if we monkey-patch our classes at run-time:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def say_hello(self):\n",
+ " print(f'instance method called from {self}')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f88d0435f28'"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p = Person()\n",
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "instance method called from <__main__.Person object at 0x7f88d0435f28>\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Person.do_work = lambda self: f\"do_work called from {self}\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'say_hello': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None,\n",
+ " 'do_work': (self)>})"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so both functions are in the class `__dict__`.\n",
+ "\n",
+ "let's create an instance and see what happens:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ " of <__main__.Person object at 0x7f88d0435f28>>"
+ ]
+ },
+ "execution_count": 34,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.do_work"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'do_work called from <__main__.Person object at 0x7f88d0435f28>'"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.do_work()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But be careful, if we add a function to the **instance** directly, this does not work the same - we have create a function in the instance, so it is not considered a method (since it was not defined in the class):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.other_func = lambda *args: print(f'other_func called with {args}')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(*args)>"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.other_func"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 38,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'other_func' in Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "other_func called with ()\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.other_func()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, `other_func` is, and behaves, like an ordinary function."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Long story short, functions defined in a class are transformed into methods when called from instances of the class. So of course, we have to account for that extra argument that is passed to the method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/07 - Initializing Class Instances.ipynb b/Part 4/Section 02 - Classes/07 - Initializing Class Instances.ipynb
new file mode 100644
index 00000000..a93107f6
--- /dev/null
+++ b/Part 4/Section 02 - Classes/07 - Initializing Class Instances.ipynb
@@ -0,0 +1,251 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Initializing Class Instances"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When we create a new instance of a class two separate things are happening:\n",
+ "1. The object instance is **created**\n",
+ "2. The object instance is then further **initialized**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can \"intercept\" both the creating and initialization phases, by using special methods `__new__` and `__init__`.\n",
+ "\n",
+ "We'll come back to `__new__` later. For now we'll focus on `__init__`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What's important to remember, is that `__init__` is an **instance method**. By the time `__init__` is called, the new object has **already** been created, and our `__init__` function defined in the class is now treated like a **method** bound to the instance."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self):\n",
+ " print(f'Initializing a new Person object: {self}')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Initializing a new Person object: <__main__.Person object at 0x7f80a022b0f0>\n"
+ ]
+ }
+ ],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we can see that `p` has the same memory address:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f80a022b0f0'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Because `__init__` is an instance method, we have access to the object (instance) state within the method, so we can use it to manipulate the object state:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Eric'}"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What actually happens is that after the new instance has been created, Python sees and automatically calls `.__init__(self, *args, **kwargs)`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this is no different that if we had done it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def initialize(self, name):\n",
+ " self.name = name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.initialize('Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Eric'}"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But by using the `__init__` method both these things are done automatically for us.\n",
+ "\n",
+ "Just remember that by the time `__init__` is called, the instance has **already** been created, and `__init__` is an instance method."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/08 - Creating Attributes at Run-Time.ipynb b/Part 4/Section 02 - Classes/08 - Creating Attributes at Run-Time.ipynb
new file mode 100644
index 00000000..36d2483b
--- /dev/null
+++ b/Part 4/Section 02 - Classes/08 - Creating Attributes at Run-Time.ipynb
@@ -0,0 +1,749 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Creating Attributes at Run-Time"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We already saw that we can add attributes to instances at run-time, and that it affects just that single instance:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person()\n",
+ "p2 = Person()\n",
+ "\n",
+ "p1.name = 'Alex'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Alex'}"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So what happens if we add a function as an attribute to our instances directly (we can even do the same within an `__init__` method, works the same way)?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Remember that if we add a function to the class itself, calling the function from the instance will result in a method. \n",
+ "\n",
+ "Here, the result is different, since we are adding the function directly to the instance, not the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1.say_hello = lambda: 'Hello!'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Alex', 'say_hello': ()>}"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "()>"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.say_hello"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, that attribute is a **plain** function - it is **not** being interpreted as a **method**."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Hello!'"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Of course, the other instances do not know anything about that function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, the question becomes, **can** we create a **method** on a specific instance?\n",
+ "\n",
+ "The answer (of course!) is yes, but we have to explicitly tell Python we are setting up a method bound to that specific instance.\n",
+ "\n",
+ "We do this by creating a `method` type object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from types import MethodType"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person('Eric')\n",
+ "p2 = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's create a `method` object, and bind it to `p1`. First we create a function that will handle the bound object as it's first argument, and use the instance `name` property."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def say_hello(self):\n",
+ " return f'{self.name} says hello!'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we can use that function just by itself, passing in any object that has a `name` attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('Eric says hello!', 'Alex says hello!')"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "say_hello(p1), say_hello(p2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now however, we are going to create a method bound to `p1` specifically:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1_say_hello = MethodType(say_hello, p1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1_say_hello"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see that method is bound to the instance `p1`. But how do we call it?\n",
+ "\n",
+ "If we try to use dotted notation or a `getattr`, that won't work because the `p1` object does not know anything about that method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "'Person' object has no attribute 'p1_say_hello'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p1.p1_say_hello()\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "All we need to do is add that method to the instance dictionary - giving it whatever name we want:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1.say_hello = p1_say_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Eric',\n",
+ " 'say_hello': >}"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so now out instance knows about that method that we stored under the name `say_hello`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Eric says hello!'"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "or, we can use the `getattr` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Eric says hello!'"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "getattr(p1, 'say_hello')()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course, othe instances know nothing about this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Alex'}"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p2.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, to create a bound method after the object has initially been created, we just create a bound method and add it to the instance itself.\n",
+ "\n",
+ "We can do it this way (what we just saw):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Alex'}"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1 = Person('Alex')\n",
+ "p1.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1.say_hello = MethodType(lambda self: f'{self.name} says hello', p1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex says hello'"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1.say_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But we can also do this from any instance method too."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Suppose we want some class to have some functionality that is called the same way but will differ from instance to instance. Although we could use inheritance, here I want some kind of 'plug-in' approach and we can do this without inheritance, mixins, or anything like that!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from types import MethodType\n",
+ "\n",
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def register_do_work(self, func):\n",
+ " setattr(self, '_do_work', MethodType(func, self))\n",
+ " \n",
+ " def do_work(self):\n",
+ " do_work_method = getattr(self, '_do_work', None)\n",
+ " # if attribute exists we'll get it back, otherwise it will be None\n",
+ " if do_work_method:\n",
+ " return do_work_method()\n",
+ " else:\n",
+ " raise AttributeError('You must first register a do_work method')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "math_teacher = Person('Eric')\n",
+ "english_teacher = Person('John')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Right now neither the math nor the english teacher can do any woirk because we haven't \"registered\" a worker yet:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "You must first register a do_work method\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " math_teacher.do_work()\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ok, so let's do that:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def work_math(self):\n",
+ " return f'{self.name} will teach differentials today.'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "math_teacher.register_do_work(work_math)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'name': 'Eric',\n",
+ " '_do_work': >}"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math_teacher.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Eric will teach differentials today.'"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "math_teacher.do_work()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we can create a different `do_work` method for the English teacher:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def work_english(self):\n",
+ " return f'{self.name} will analyze Hamlet today.'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "english_teacher.register_do_work(work_english)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'John will analyze Hamlet today.'"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "english_teacher.do_work()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/09 - Properties.ipynb b/Part 4/Section 02 - Classes/09 - Properties.ipynb
new file mode 100644
index 00000000..25bf9477
--- /dev/null
+++ b/Part 4/Section 02 - Classes/09 - Properties.ipynb
@@ -0,0 +1,1063 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Properties"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To be clear, here we are examining **instance** properties. That is, we define the property in the class we are defining, but the property itself is going to be **instance** specific, i.e. different instances will support different values for the property. Just like instance attributes. The main difference is that we will use accessor method to get, set (and optionally) delete the associated instance value."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As I mentioned in the lecture, because properties use the same dotted notation (and the same `getattr`, `setattr` and `delattr` functions), we do not need to **start** with properties. Often a bare attribute works just fine, and if, later, we decide we need to manage getting/setting/deleting the attribute value, we can switch over to properties without breaking our class interface. This is unlike languages like Java - and hence why in those languages it is recommended to **always** use getter and setter functions. *Not so* in Python!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A **property** in Python is essentially a class instance - we'll come back to what that class looks like when we study descriptors. For now, we are going to use the `property` function in Python which is a convenience callable essentially."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's start with a simple example and a bare attribute:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this class has a single instance **attribute**, `name`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we can access and modify that attribute using either dotted notation or the `getattr` and `setattr` methods:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "getattr(p, 'name')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "p.name = 'John'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(p, 'name', 'Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Eric'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now suppose we wan't to disallow setting an empty string or `None` for the name. Also, we'll require the name to be a string.\n",
+ "\n",
+ "To do that we are going to create an instance method that will handle the logic and setting of the value. We also create an instance method to retrieve the attribute value.\n",
+ "\n",
+ "We'll use `_name` as the instance variable to store the name."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.set_name(name)\n",
+ " \n",
+ " def get_name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def set_name(self, value):\n",
+ " if isinstance(value, str) and len(value.strip()) > 0:\n",
+ " # this is valid\n",
+ " self._name = value.strip()\n",
+ " else:\n",
+ " raise ValueError('name must be a non-empty string')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "name must be a non-empty string\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.set_name(100)\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.set_name('Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Eric'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.get_name()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Of course, our users can still manipulate the atribute directly if they want by using the \"private\" attribute `_name`. You can't stop anyone from doing this in Python - they should know better than to do that, but we're all good programmers, and know what and what not to do!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The way we set up our initializer, the validation will work too:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "name must be a non-empty string\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p = Person('')\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this works, but it's a bit of pain to use the method names. So let's turn this into a property instead. We start with the class we just had and tweak it a bit:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name # note how we are actually setting the value for name using the property!\n",
+ " \n",
+ " def get_name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def set_name(self, value):\n",
+ " if isinstance(value, str) and len(value.strip()) > 0:\n",
+ " # this is valid\n",
+ " self._name = value.strip()\n",
+ " else:\n",
+ " raise ValueError('name must be a non-empty string')\n",
+ " \n",
+ " name = property(fget=get_name, fset=set_name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.name = 'Eric'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "name must be a non-empty string\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.name = None\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now we have the benefit of using accessor methods, without having to call the methods explicitly.\n",
+ "\n",
+ "In fact, even `getattr` and `setattr` will work the same way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(p, 'name', 'John') # or p.name = 'John'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'John'"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "getattr(p, 'name') # or simply p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's examine the instance dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'John'}"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You'll see we can find the underlying \"private\" attribute we are using to store the name. But the property itself (`name`) is not in the dictionary.\n",
+ "\n",
+ "The property was defined in the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " '__init__': ,\n",
+ " 'get_name': ,\n",
+ " 'set_name': ,\n",
+ " 'name': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And you can see it's type is `property`.\n",
+ "\n",
+ "So when we type `p.name` or `p.name = value`, Python recognizes that `'name` is a `property` and therefore uses the accessor methods. (How it does we'll see later when we study descriptors).\n",
+ "\n",
+ "What's interesting is that even if we muck around with the instance dictionary, Python does not get confused - (and as usual in Python, just because you **can** do something does not mean you **should**!)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Alex'}"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.__dict__['name'] = 'John'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Alex', 'name': 'John'}"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, we now have `name` in our instance dictionary.\n",
+ "\n",
+ "Let's retrieve the `name` via dotted notation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That's obviously still using the getter method.\n",
+ "\n",
+ "And setting the name:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.name = 'Raymond'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Raymond', 'name': 'John'}"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, it used the setter method.\n",
+ "\n",
+ "And the same thing happens with `setattr` and `getattr`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Raymond'"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "getattr(p, 'name')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "setattr(p, 'name', 'Python')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Python', 'name': 'John'}"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see the `setattr` method used the property setter."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For completeness, let's see how the deleter method works:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " def get_name(self):\n",
+ " print('getting name')\n",
+ " return self._name\n",
+ " \n",
+ " def set_name(self, value):\n",
+ " print('setting name')\n",
+ " self._name = value\n",
+ " \n",
+ " def del_name(self):\n",
+ " print('deleting name')\n",
+ " del self._name # or whatever \"cleanup\" we want to do\n",
+ " \n",
+ " name = property(get_name, set_name, del_name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Alex'}"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "setting name\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.name = 'Eric'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Eric'}"
+ ]
+ },
+ "execution_count": 39,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "deleting name\n"
+ ]
+ }
+ ],
+ "source": [
+ "del p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 41,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, the property still exists (since it is defined in the class) - all we did was remove the underlying value for the property (the `_name` instance attribute):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name\n",
+ "'Person' object has no attribute '_name'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.name\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see the issue is that the getter function is trying to find `_name` in the attribute, which no longer exists. So the getter and setter still exist (i.e. the property still exists), so we can still assign to it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "setting name\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.name = 'Alex'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 44,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The last param in `property` is just a docstring. So we could do this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " \"\"\"This is a Person object\"\"\"\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " def get_name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def set_name(self, value):\n",
+ " self._name = value\n",
+ " \n",
+ " name = property(get_name, set_name, doc=\"The person's name.\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on property:\n",
+ "\n",
+ " The person's name.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person.name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on class Person in module __main__:\n",
+ "\n",
+ "class Person(builtins.object)\n",
+ " | This is a Person object\n",
+ " | \n",
+ " | Methods defined here:\n",
+ " | \n",
+ " | __init__(self, name)\n",
+ " | Initialize self. See help(type(self)) for accurate signature.\n",
+ " | \n",
+ " | get_name(self)\n",
+ " | \n",
+ " | set_name(self, value)\n",
+ " | \n",
+ " | ----------------------------------------------------------------------\n",
+ " | Data descriptors defined here:\n",
+ " | \n",
+ " | __dict__\n",
+ " | dictionary for instance variables (if defined)\n",
+ " | \n",
+ " | __weakref__\n",
+ " | list of weak references to the object (if defined)\n",
+ " | \n",
+ " | name\n",
+ " | The person's name.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/10 - Property Decorators.ipynb b/Part 4/Section 02 - Classes/10 - Property Decorators.ipynb
new file mode 100644
index 00000000..6380af61
--- /dev/null
+++ b/Part 4/Section 02 - Classes/10 - Property Decorators.ipynb
@@ -0,0 +1,1326 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Property Decorators"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As I explain in the lecture video, the `property` callable actually returns itself:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = property(fget=lambda self: print('getting property'))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see `p` is a property, and in fact is the same property that was created."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Think back to how decorators work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_decorator(fn):\n",
+ " print('decorating function')\n",
+ " def inner(*args, **kwargs):\n",
+ " print('running decorated function')\n",
+ " return fn(*args, **kwargs)\n",
+ " return inner"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def undecorated_function(a, b):\n",
+ " print('running original function')\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we can decorate our undecorated function this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "decorating function\n"
+ ]
+ }
+ ],
+ "source": [
+ "decorated_func = my_decorator(undecorated_function)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we can call the decorated function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "running decorated function\n",
+ "running original function\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "30"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "decorated_func(10, 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now instead of giving the decorate function a new symbol, we could have just re-used the same symbol:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "decorating function\n"
+ ]
+ }
+ ],
+ "source": [
+ "def my_func(a, b):\n",
+ " print('running original function')\n",
+ " return a + b\n",
+ "\n",
+ "my_func = my_decorator(my_func)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "running decorated function\n",
+ "running original function\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "30"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(10, 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course this is exactly what the decorator `@` syntax does:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "decorating function\n"
+ ]
+ }
+ ],
+ "source": [
+ "@my_decorator\n",
+ "def my_func(a, b):\n",
+ " print('running original function')\n",
+ " return a + b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "running decorated function\n",
+ "running original function\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "30"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "my_func(10, 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ok, now that we've refreshed our memory on decorators, we should be ready to look at the `property` callable.\n",
+ "\n",
+ "The `property` callable creates a property object, **and returns it**.\n",
+ "\n",
+ "In other words, we could create our property this way, as usual:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " name = property(name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p = Person('Alex')\n",
+ "\n",
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But you'll notice that line: `name = property(name)` - that's exactly what the decorator syntax does for us!\n",
+ "\n",
+ "So instead we can write:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Guido'"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p = Person('Guido')\n",
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If you refresh your memory on the single dispatch generic function decorator, you'll remember that the decorated function included another property, the `register` property that was itself a decorator.\n",
+ "\n",
+ "Well, the `property` object has some properties, like `setter` that will basically accept a reference to the setter method, and return itself also."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = property(lambda self: 'getter')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['__class__',\n",
+ " '__delattr__',\n",
+ " '__delete__',\n",
+ " '__dir__',\n",
+ " '__doc__',\n",
+ " '__eq__',\n",
+ " '__format__',\n",
+ " '__ge__',\n",
+ " '__get__',\n",
+ " '__getattribute__',\n",
+ " '__gt__',\n",
+ " '__hash__',\n",
+ " '__init__',\n",
+ " '__init_subclass__',\n",
+ " '__isabstractmethod__',\n",
+ " '__le__',\n",
+ " '__lt__',\n",
+ " '__ne__',\n",
+ " '__new__',\n",
+ " '__reduce__',\n",
+ " '__reduce_ex__',\n",
+ " '__repr__',\n",
+ " '__set__',\n",
+ " '__setattr__',\n",
+ " '__sizeof__',\n",
+ " '__str__',\n",
+ " '__subclasshook__',\n",
+ " 'deleter',\n",
+ " 'fdel',\n",
+ " 'fget',\n",
+ " 'fset',\n",
+ " 'getter',\n",
+ " 'setter']"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, we can \"register\" and setter method, using the `setter` callable, and get our property back as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p2 = p.setter(lambda self: 'setter')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(140202095607384, 140202095618152)"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "id(p), id(p2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now you'll notice that the property id has changed. The setter callable actually creates a new property (with both the original getter, and the new setter assigned).\n",
+ "\n",
+ "But that does not really matter, we just have a new property object that we can use to assign to a symbol - and that property will have both the getter and the setter defined.\n",
+ "\n",
+ "Let's do this manually (without the decorator syntax first):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " name = property(name)\n",
+ " \n",
+ " # creating another symbol that holds on to \n",
+ " # the name property\n",
+ " name_prop = name \n",
+ " \n",
+ " # because herte I'm redefining name, so we lose \n",
+ " # our original reference to the property object\n",
+ " def name(self, value):\n",
+ " self._name = value\n",
+ " \n",
+ " name = name_prop.setter(name)\n",
+ " \n",
+ " # finally delete name_prop which we no longer need\n",
+ " del name_prop"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " '__init__': ,\n",
+ " 'name': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we now have a `name` property that we created in two steps: first create the property with just a getter.\n",
+ "\n",
+ "Then we replaced our property with a new property that had both the getter and the setter."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p = Person('Alex')\n",
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Raymond'"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name = 'Raymond'\n",
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hopefully you can now see where the original property (with just the getter), had a callable `setter` that \"added\" the setter to the property (by creating a new property with both getter and setter), that also returned the (new) property object.\n",
+ "\n",
+ "So, we can simplify our code this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " # what's the property name now? --> name\n",
+ " # so name has a setter callable\n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that if we had not named our setter function `name` the property name would have changed!\n",
+ "\n",
+ "Remember that:\n",
+ "```\n",
+ "@dec\n",
+ "def my_func():\n",
+ " pass\n",
+ " ```\n",
+ " returns a decorated function with the same name as the original function"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " '__init__': ,\n",
+ " 'name': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Guido'"
+ ]
+ },
+ "execution_count": 28,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name = 'Guido'\n",
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Just to show you, if we had not used the same name for the setter function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " # property is now called name\n",
+ " \n",
+ " @name.setter\n",
+ " def full_name(self, value):\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " '__init__': ,\n",
+ " 'name': ,\n",
+ " 'full_name': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.__dict__"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see we now have two properties on the class! The first one `name` will only work as a getter. And the second one `full_name` will work as both a getter and a setter:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.full_name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.full_name = 'Raymond'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Raymond'"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.full_name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But this won't work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "can't set attribute\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.name = 'Guido'\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Technically, the property callable has both a getter and setter method - so we can create the setter first, then \"add in\" the getter. But since the first argument to `property` is the getter, we have to work a bit more to do it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " name = property() # an \"empty\" prroperty - no getter or setter\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By the way, we now have a property that can be set, but not read back!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Alex'}"
+ ]
+ },
+ "execution_count": 39,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.name = 'Raymond'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Raymond'}"
+ ]
+ },
+ "execution_count": 41,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unreadable attribute\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.name\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, if you ever need an attribute that is \"write-only\" - you can do it. Maybe the data is sensitive, and you want to set it, but not show back to users... But the data is never truly private, so at best you're obfuscating the data - so in my experience I've never had to do something like that. Just wanted you to see this in case the need ever came up."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But let's finish this up and make the property read/write:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " name = property() # an \"empty\" prroperty - no getter or setter\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " self._name = value\n",
+ " \n",
+ " @name.getter\n",
+ " def name(self):\n",
+ " return self._name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 45,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p.name = 'Raymond'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Raymond'"
+ ]
+ },
+ "execution_count": 47,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The deleter works the same way, and we'll come back to it soon."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Lastly you'll recall that we could set up a docstring when using the `property` callable.\n",
+ "\n",
+ "The standard technique is to simply define the docstring in the getter function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " \"\"\"The Person's name.\"\"\"\n",
+ " return self._name\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on property:\n",
+ "\n",
+ " The Person's name.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person.name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on class Person in module __main__:\n",
+ "\n",
+ "class Person(builtins.object)\n",
+ " | Methods defined here:\n",
+ " | \n",
+ " | __init__(self, name)\n",
+ " | Initialize self. See help(type(self)) for accurate signature.\n",
+ " | \n",
+ " | ----------------------------------------------------------------------\n",
+ " | Data descriptors defined here:\n",
+ " | \n",
+ " | __dict__\n",
+ " | dictionary for instance variables (if defined)\n",
+ " | \n",
+ " | __weakref__\n",
+ " | list of weak references to the object (if defined)\n",
+ " | \n",
+ " | name\n",
+ " | The Person's name.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happens if we set it in the setter instead?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " \"\"\"The Person's name.\"\"\"\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on property:\n",
+ "\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person.name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on class Person in module __main__:\n",
+ "\n",
+ "class Person(builtins.object)\n",
+ " | Methods defined here:\n",
+ " | \n",
+ " | __init__(self, name)\n",
+ " | Initialize self. See help(type(self)) for accurate signature.\n",
+ " | \n",
+ " | ----------------------------------------------------------------------\n",
+ " | Data descriptors defined here:\n",
+ " | \n",
+ " | __dict__\n",
+ " | dictionary for instance variables (if defined)\n",
+ " | \n",
+ " | __weakref__\n",
+ " | list of weak references to the object (if defined)\n",
+ " | \n",
+ " | name\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, the property docstring is only set on the getter. So how to set a docstring with a write-only property? We can do that when we create the initial property:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " name = property(doc='Write-only name property.')\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " self._name = value"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Help on property:\n",
+ "\n",
+ " Write-only name property.\n",
+ "\n"
+ ]
+ }
+ ],
+ "source": [
+ "help(Person.name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/11 - Read-Only and Computed Properties.ipynb b/Part 4/Section 02 - Classes/11 - Read-Only and Computed Properties.ipynb
new file mode 100644
index 00000000..889beacd
--- /dev/null
+++ b/Part 4/Section 02 - Classes/11 - Read-Only and Computed Properties.ipynb
@@ -0,0 +1,470 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Read-Only and Computed Properties"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although write-only properties are not that common, read-only properties (i.e. that define a getter but not a setter) are quite common for a number of things."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Of course, we can create read-only properties, but since nothing is private, at best we are \"suggesting\" to the users of our class they should treat the property as read-only. There's always a way to hack around that of course.\n",
+ "\n",
+ "But still, it's good to be able to at least explicitly indicate to a user that a property is meant to be read-only."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The use case I'm going to focus on in this video, is one of computed properties. Those are properties that may not actually have a backing variable, but are instead calculated on the fly."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Consider this simple example of a `Circle` class where we can read/write the radius of the circle, but want a computed property for the area. We don't need to store the area value, we can alway calculate it given the current radius value."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from math import pi\n",
+ "\n",
+ "class Circle:\n",
+ " def __init__(self, radius):\n",
+ " self.radius = radius\n",
+ " \n",
+ " @property\n",
+ " def area(self):\n",
+ " print('calculating area...')\n",
+ " return pi * (self.radius ** 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "calculating area...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "3.141592653589793"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c = Circle(1)\n",
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could certainly just use a class method `area()`, but the area is more a property of the circle, so it makes more sense to just retrive it as a property, without the extra `()` to make the call."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The advantage of how we did this is that shoudl the radius of the circle ever change, the area property will immediately reflect that."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "calculating area...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "12.566370614359172"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.radius = 2\n",
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "On the other hand, it's also a weakness - every time we need the area of the circle, it gets recalculated, even if the radius has not changed!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "calculating area...\n",
+ "calculating area...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "12.566370614359172"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.area\n",
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now we can use properties to fix this problem without breaking our interface!\n",
+ "\n",
+ "We are going to cache the area value, and only-recalculate it if the radius has changed.\n",
+ "\n",
+ "In order for us to know if the radius has changed, we are going to make it into a property, and the setter will keep track of whether the radius is set, in which case it will invalidate the cached area value."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Circle:\n",
+ " def __init__(self, radius):\n",
+ " self.radius = radius\n",
+ " self._area = None\n",
+ " \n",
+ " @property\n",
+ " def radius(self):\n",
+ " return self._radius\n",
+ " \n",
+ " @radius.setter\n",
+ " def radius(self, value):\n",
+ " # if radius value is set we invalidate our cached _area value\n",
+ " # we could make this more intelligent and see if the radius has actually changed\n",
+ " # but keeping it simple\n",
+ " self._area = None\n",
+ " # we could even add validation here, like value has to be numeric, non-negative, etc\n",
+ " self._radius = value\n",
+ " \n",
+ " @property\n",
+ " def area(self):\n",
+ " if self._area is None:\n",
+ " # value not cached - calculate it\n",
+ " print('Calculating area...')\n",
+ " self._area = pi * (self.radius ** 2)\n",
+ " return self._area"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "c = Circle(1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Calculating area...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "3.141592653589793"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3.141592653589793"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "c.radius = 2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Calculating area...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "12.566370614359172"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "12.566370614359172"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "c.area"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There are a lot of other uses for calculate properties.\n",
+ "\n",
+ "Some properties may even do a lot work, like retrieving data from a database, making a call to some external API, and so on."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's write a class that takes a URL, downloads the web page for that URL and provides us some metrics on that URL - like how long it took to download, the size (in bytes) of the page."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although I am going to use the `urllib` module for this, I strongly recommend you use the `requests` 3rd party library instead: http://docs.python-requests.org"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import urllib\n",
+ "from time import perf_counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class WebPage:\n",
+ " def __init__(self, url):\n",
+ " self.url = url\n",
+ " self._page = None\n",
+ " self._load_time_secs = None\n",
+ " self._page_size = None\n",
+ " \n",
+ " @property\n",
+ " def url(self):\n",
+ " return self._url\n",
+ " \n",
+ " @url.setter\n",
+ " def url(self, value):\n",
+ " self._url = value\n",
+ " self._page = None\n",
+ " # we'll lazy load the page - i.e. we wait until some property is requested\n",
+ " \n",
+ " @property\n",
+ " def page(self):\n",
+ " if self._page is None:\n",
+ " self.download_page()\n",
+ " return self._page\n",
+ " \n",
+ " @property\n",
+ " def page_size(self):\n",
+ " if self._page is None:\n",
+ " # need to first download the page\n",
+ " self.download_page()\n",
+ " return self._page_size\n",
+ " \n",
+ " @property\n",
+ " def time_elapsed(self):\n",
+ " if self._page is None:\n",
+ " self.download_page()\n",
+ " return self._load_time_secs\n",
+ " \n",
+ " def download_page(self):\n",
+ " self._page_size = None\n",
+ " self._load_time_secs = None\n",
+ " start_time = perf_counter()\n",
+ " with urllib.request.urlopen(self.url) as f:\n",
+ " self._page = f.read()\n",
+ " end_time = perf_counter()\n",
+ " \n",
+ " self._page_size = len(self._page)\n",
+ " self._load_time_secs = end_time - start_time"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "https://www.google.com \tsize=11_489 \telapsed=0.20 secs\n",
+ "https://www.python.org \tsize=49_132 \telapsed=0.18 secs\n",
+ "https://www.yahoo.com \tsize=524_548 \telapsed=0.77 secs\n"
+ ]
+ }
+ ],
+ "source": [
+ "urls = [\n",
+ " 'https://www.google.com',\n",
+ " 'https://www.python.org',\n",
+ " 'https://www.yahoo.com'\n",
+ "]\n",
+ "\n",
+ "for url in urls:\n",
+ " page = WebPage(url)\n",
+ " print(f'{url} \\tsize={format(page.page_size, \"_\")} \\telapsed={page.time_elapsed:.2f} secs')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/12 - Deleting Properties.ipynb b/Part 4/Section 02 - Classes/12 - Deleting Properties.ipynb
new file mode 100644
index 00000000..d2875b6f
--- /dev/null
+++ b/Part 4/Section 02 - Classes/12 - Deleting Properties.ipynb
@@ -0,0 +1,361 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Deleting Properties"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Just like we can delete an attribute from an instance object, we can also delete a property from an instance object.\n",
+ "\n",
+ "Note that this action simply runs the deleter method, but the property remains defined **on the class**. It does not remove the property from the class, instead it is generally used to remove the property value from the **instance**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Properties, like attributes, can be deleted by using the `del` keyword, or the `delattr` function."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ "\n",
+ " def get_name(self):\n",
+ " print('getting name property value...')\n",
+ " return self._name\n",
+ " \n",
+ " def set_name(self, value):\n",
+ " print(f'setting name property to {value}...')\n",
+ " self._name = value\n",
+ " \n",
+ " def del_name(self):\n",
+ " # delete the underlying data\n",
+ " print('deleting name property value...')\n",
+ " del self._name\n",
+ " \n",
+ " name = property(fget=get_name, fset=set_name, fdel=del_name, doc='Person name.')\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "setting name property to Guido...\n"
+ ]
+ }
+ ],
+ "source": [
+ "p = Person('Guido')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name property value...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Guido'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And the underlying `_name` property is in our instance dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{'_name': 'Guido'}"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "deleting name property value...\n"
+ ]
+ }
+ ],
+ "source": [
+ "del p.name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see, the underlying `_name` attribute is no longer present in the instance dictionary:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{}"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name property value...\n",
+ "'Person' object has no attribute '_name'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(p.name)\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, the property deletion did not remove the property definition, that still exists."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Alternatively, we can use the `delattr` function as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "setting name property to Raymond...\n"
+ ]
+ }
+ ],
+ "source": [
+ " p = Person('Raymond')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "deleting name property value...\n"
+ ]
+ }
+ ],
+ "source": [
+ "delattr(p, 'name')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And we can of course use the decorator syntax as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ "\n",
+ " @property\n",
+ " def name(self):\n",
+ " print('getting name property value...')\n",
+ " return self._name\n",
+ " \n",
+ " @name.setter\n",
+ " def name(self, value):\n",
+ " \"\"\"Person name\"\"\"\n",
+ " print(f'setting name property to {value}...')\n",
+ " self._name = value\n",
+ " \n",
+ " @name.deleter\n",
+ " def name(self):\n",
+ " # delete the underlying data\n",
+ " print('deleting name property value...')\n",
+ " del self._name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "setting name property to Alex...\n"
+ ]
+ }
+ ],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "getting name property value...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Alex'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "deleting name property value...\n"
+ ]
+ }
+ ],
+ "source": [
+ "del p.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/13 - Class and Static Methods.ipynb b/Part 4/Section 02 - Classes/13 - Class and Static Methods.ipynb
new file mode 100644
index 00000000..f9f9848d
--- /dev/null
+++ b/Part 4/Section 02 - Classes/13 - Class and Static Methods.ipynb
@@ -0,0 +1,1211 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Class and Static Methods"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Asd we saw, when we define a function inside a class, how it behaves (as a function or a method) depends on how the function is accessed: from the class, or from the instance. (We'll cover how that works when we look at descriptors later in this course)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def hello(arg='default'):\n",
+ " print(f'Hello, with arg={arg}')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we call `hello` from the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello, with arg=default\n"
+ ]
+ }
+ ],
+ "source": [
+ "Person.hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You'll notice that `hello` was called without any arguments, in fact, `hello` is a regular function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Person.hello"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But if we call `hello` from an instance, things are different:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p.hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Hello, with arg=<__main__.Person object at 0x7f8f287fb860>\n"
+ ]
+ }
+ ],
+ "source": [
+ "p.hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0x7f8f287fb860'"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hex(id(p))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And as you can see the instance `p` was passed as an argument to `hello`. \n",
+ "\n",
+ "Sometimes however, we define functions in a class that do not interact with the instance itself, but may need something from the class. In those cases, we want the class to be passed to the function as an argument, whether it is called from the class or from an instance of the class.\n",
+ "\n",
+ "These are called **class methods**. You'll note that the behavior needs to be different - we don't want the instance to be passed to the function when called from an instance, we want the **class** to be passed to it. In addition, when called from the class, we **also** want the class to be passed to it (this is similar to `static` methods in Java, not to be confused with, as we'll see in a bit, static methods in Python).\n",
+ "\n",
+ "We use the `@classmethod` decorator to define class methods, and the first argument of these methods will always be the class where the method is defined."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see a simple example first:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyClass:\n",
+ " def hello():\n",
+ " # this IS an instance method, we just forgot to add a parameter to capture the instance\n",
+ " # when this is called from an instance - so this will fail\n",
+ " print('hello...')\n",
+ " \n",
+ " def instance_hello(arg):\n",
+ " print(f'hello from {arg}')\n",
+ " \n",
+ " @classmethod\n",
+ " def class_hello(arg):\n",
+ " print(f'hello from {arg}')\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "m = MyClass()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello...\n"
+ ]
+ }
+ ],
+ "source": [
+ "MyClass.hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But, as expected, this won't work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello() takes 0 positional arguments but 1 was given\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " m.hello()\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "On the other hand, notice now the instance method when called from the instance and the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello from <__main__.MyClass object at 0x7f8ed87fff60>\n"
+ ]
+ }
+ ],
+ "source": [
+ "m.instance_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "instance_hello() missing 1 required positional argument: 'arg'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " MyClass.instance_hello()\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, the instance method needs to be called from the instance. If we call it from the class, no argument is passed to the function, so we end up with an exception.\n",
+ "\n",
+ "This is not the case with class methods - whether we call the method from the class, or the instance, that first argument will always be provided by Python, and will be the class object (not the instance).\n",
+ "\n",
+ "Notice how the bindings are different:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.class_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "m.class_hello"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see in both these cases, `class_hello` is bound to the class.\n",
+ "\n",
+ "But with an instance method, the bindings behave differently:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.instance_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ">"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "m.instance_hello"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, whenever we call `class_hello` the method is bound to the **class**, and the first argument is the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello from \n"
+ ]
+ }
+ ],
+ "source": [
+ "MyClass.class_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello from \n"
+ ]
+ }
+ ],
+ "source": [
+ "m.class_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although in this example I used `arg` as the parameter name in our methods, the normal **convention** is to use `self` and `cls` - that way everyone knows what we're talking about!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We sometimes also want to define functions in a class and always have them be just that - functions, never bound to either the class or the instance, however we call them. Often we do this because we need to utility function that is specific to our class, and we want to keep our class self-contained, or maybe we're writing a library of functions (though modules and packages may be more appropriate for this)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "These are called **static** methods. (So be careful here, Python static methods and Java static methods do not have the same meaning!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can define static methods using the `@staticmethod` decorator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyClass:\n",
+ " def instance_hello(self):\n",
+ " print(f'Instance method bound to {self}')\n",
+ " \n",
+ " @classmethod\n",
+ " def class_hello(cls):\n",
+ " print(f'Class method bound to {cls}')\n",
+ " \n",
+ " @staticmethod\n",
+ " def static_hello():\n",
+ " print('Static method not bound to anything')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "m = MyClass()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Instance method bound to <__main__.MyClass object at 0x7f8ed8811a58>\n"
+ ]
+ }
+ ],
+ "source": [
+ "m.instance_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Class method bound to \n"
+ ]
+ }
+ ],
+ "source": [
+ "MyClass.class_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Class method bound to \n"
+ ]
+ }
+ ],
+ "source": [
+ "m.class_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And the static method can be called either from the class or the instance, but is never bound:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.static_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "m.static_hello"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Static method not bound to anything\n"
+ ]
+ }
+ ],
+ "source": [
+ "MyClass.static_hello()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Static method not bound to anything\n"
+ ]
+ }
+ ],
+ "source": [
+ "m.static_hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Example"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see a more concrete example of using these different method types.\n",
+ "\n",
+ "We're going to create a `Timer` class that will allow us to get the current time (in both UTC and some timezone), as well as record start/stop times.\n",
+ "\n",
+ "We want to have the same timezone for all instances of our `Timer` class with an easy way to change the timezone for all instances when needed.\n",
+ "\n",
+ "If you need to work with timezones, I recommend you use the `pyrz` 3rd party library. Here, I'll just use the standard library, which is definitely not as easy to use as `pytz`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime, timezone, timedelta\n",
+ "\n",
+ "class Timer:\n",
+ " tz = timezone.utc # class variable to store the timezone - default to UTC\n",
+ " \n",
+ " @classmethod\n",
+ " def set_tz(cls, offset, name):\n",
+ " cls.tz = timezone(timedelta(hours=offset), name)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So `tz` is a class attribute, and we can set it using a class method `set_timezone` - any instances will share the same `tz` value (unless we override it at the instance level)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Timer.set_tz(-7, 'MST')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.timezone(datetime.timedelta(-1, 61200), 'MST')"
+ ]
+ },
+ "execution_count": 31,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Timer.tz"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "t1 = Timer()\n",
+ "t2 = Timer()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(datetime.timezone(datetime.timedelta(-1, 61200), 'MST'),\n",
+ " datetime.timezone(datetime.timedelta(-1, 61200), 'MST'))"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "t1.tz, t2.tz"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Timer.set_tz(-8, 'PST')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(datetime.timezone(datetime.timedelta(-1, 57600), 'PST'),\n",
+ " datetime.timezone(datetime.timedelta(-1, 57600), 'PST'))"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "t1.tz, t2.tz"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next we want a function to return the current UTC time. Obviously this has nothing to do with either the class or the instance, so it is a prime candidate for a static method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Timer:\n",
+ " tz = timezone.utc # class variable to store the timezone - default to UTC\n",
+ " \n",
+ " @staticmethod\n",
+ " def current_dt_utc():\n",
+ " return datetime.now(timezone.utc)\n",
+ " \n",
+ " @classmethod\n",
+ " def set_tz(cls, offset, name):\n",
+ " cls.tz = timezone(timedelta(hours=offset), name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2019, 6, 2, 23, 25, 59, 714761, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 37,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Timer.current_dt_utc()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "t = Timer()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2019, 6, 2, 23, 25, 59, 723565, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 39,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "t.current_dt_utc()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next we want a method that will return the current time based on the set time zone. Obviously the time zone is a class variable, so we'll need to access that, but we don't need any instance data, so this is a prime candidate for a class method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Timer:\n",
+ " tz = timezone.utc # class variable to store the timezone - default to UTC\n",
+ " \n",
+ " @staticmethod\n",
+ " def current_dt_utc():\n",
+ " return datetime.now(timezone.utc)\n",
+ " \n",
+ " @classmethod\n",
+ " def set_tz(cls, offset, name):\n",
+ " cls.tz = timezone(timedelta(hours=offset), name)\n",
+ " \n",
+ " @classmethod\n",
+ " def current_dt(cls):\n",
+ " return datetime.now(cls.tz)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(datetime.datetime(2019, 6, 2, 23, 25, 59, 733420, tzinfo=datetime.timezone.utc),\n",
+ " datetime.datetime(2019, 6, 2, 23, 25, 59, 733423, tzinfo=datetime.timezone.utc))"
+ ]
+ },
+ "execution_count": 41,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Timer.current_dt_utc(), Timer.current_dt()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "t1 = Timer()\n",
+ "t2 = Timer()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(datetime.datetime(2019, 6, 2, 23, 25, 59, 741248, tzinfo=datetime.timezone.utc),\n",
+ " datetime.datetime(2019, 6, 2, 23, 25, 59, 741251, tzinfo=datetime.timezone.utc))"
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "t1.current_dt_utc(), t1.current_dt()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2019, 6, 2, 23, 25, 59, 745699, tzinfo=datetime.timezone.utc)"
+ ]
+ },
+ "execution_count": 44,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "t2.current_dt()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And if we change the time zone (we can do so either via the class or the instance, no difference, since the `set_tz` method is always bound to the class):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "t2.set_tz(-7, 'MST')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "mappingproxy({'__module__': '__main__',\n",
+ " 'tz': datetime.timezone(datetime.timedelta(-1, 61200), 'MST'),\n",
+ " 'current_dt_utc': ,\n",
+ " 'set_tz': ,\n",
+ " 'current_dt': ,\n",
+ " '__dict__': ,\n",
+ " '__weakref__': ,\n",
+ " '__doc__': None})"
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Timer.__dict__"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(datetime.datetime(2019, 6, 2, 23, 25, 59, 761523, tzinfo=datetime.timezone.utc),\n",
+ " datetime.datetime(2019, 6, 2, 16, 25, 59, 761526, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200), 'MST')),\n",
+ " datetime.datetime(2019, 6, 2, 16, 25, 59, 761526, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200), 'MST')),\n",
+ " datetime.datetime(2019, 6, 2, 16, 25, 59, 761527, tzinfo=datetime.timezone(datetime.timedelta(-1, 61200), 'MST')))"
+ ]
+ },
+ "execution_count": 47,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Timer.current_dt_utc(), Timer.current_dt(), t1.current_dt(), t2.current_dt()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So far we have not needed any instances to work with this class!\n",
+ "\n",
+ "Now we're going to add functionality to start/stop a timer. Obviously we want this to be instance based, since we want to be able to create multiple timers."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TimerError(Exception):\n",
+ " \"\"\"A custom exception used for Timer class\"\"\"\n",
+ " # (since \"\"\"...\"\"\" is a statement, we don't need to pass)\n",
+ " \n",
+ "class Timer:\n",
+ " tz = timezone.utc # class variable to store the timezone - default to UTC\n",
+ " \n",
+ " def __init__(self):\n",
+ " # use these instance variables to keep track of start/end times\n",
+ " self._time_start = None\n",
+ " self._time_end = None\n",
+ " \n",
+ " @staticmethod\n",
+ " def current_dt_utc():\n",
+ " \"\"\"Returns non-naive current UTC\"\"\"\n",
+ " return datetime.now(timezone.utc)\n",
+ " \n",
+ " @classmethod\n",
+ " def set_tz(cls, offset, name):\n",
+ " cls.tz = timezone(timedelta(hours=offset), name)\n",
+ " \n",
+ " @classmethod\n",
+ " def current_dt(cls):\n",
+ " return datetime.now(cls.tz)\n",
+ " \n",
+ " def start(self):\n",
+ " # internally we always non-naive UTC\n",
+ " self._time_start = self.current_dt_utc()\n",
+ " self._time_end = None\n",
+ " \n",
+ " def stop(self):\n",
+ " if self._time_start is None:\n",
+ " # cannot stop if timer was not started!\n",
+ " raise TimerError('Timer must be started before it can be stopped.')\n",
+ " self._time_end = self.current_dt_utc()\n",
+ " \n",
+ " @property\n",
+ " def start_time(self):\n",
+ " if self._time_start is None:\n",
+ " raise TimerError('Timer has not been started.')\n",
+ " # since tz is a class variable, we can just as easily access it from self\n",
+ " return self._time_start.astimezone(self.tz) \n",
+ " \n",
+ " @property\n",
+ " def end_time(self):\n",
+ " if self._time_end is None:\n",
+ " raise TimerError('Timer has not been stopped.')\n",
+ " return self._time_end.astimezone(self.tz)\n",
+ " \n",
+ " @property\n",
+ " def elapsed(self):\n",
+ " if self._time_start is None:\n",
+ " raise TimerError('Timer must be started before an elapsed time is available')\n",
+ " \n",
+ " if self._time_end is None:\n",
+ " # timer has not ben stopped, calculate elapsed between start and now\n",
+ " elapsed_time = self.current_dt_utc() - self._time_start\n",
+ " else:\n",
+ " # timer has been stopped, calculate elapsed between start and end\n",
+ " elapsed_time = self._time_end - self._time_start\n",
+ " \n",
+ " return elapsed_time.total_seconds()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Start time: 2019-06-02 23:25:59.777250+00:00\n",
+ "End time: 2019-06-02 23:26:01.781431+00:00\n",
+ "Elapsed: 2.004181 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "from time import sleep\n",
+ "\n",
+ "t1 = Timer()\n",
+ "t1.start()\n",
+ "sleep(2)\n",
+ "t1.stop()\n",
+ "print(f'Start time: {t1.start_time}')\n",
+ "print(f'End time: {t1.end_time}')\n",
+ "print(f'Elapsed: {t1.elapsed} seconds')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Start time: 2019-06-02 23:26:01.787596+00:00\n",
+ "End time: 2019-06-02 23:26:04.792814+00:00\n",
+ "Elapsed: 3.005218 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "t2 = Timer()\n",
+ "t2.start()\n",
+ "sleep(3)\n",
+ "t2.stop()\n",
+ "print(f'Start time: {t2.start_time}')\n",
+ "print(f'End time: {t2.end_time}')\n",
+ "print(f'Elapsed: {t2.elapsed} seconds')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So our timer works. Furthermore, we want to use `MST` throughout our application, so we'll set it, and since it's a class level attribute, we only need to change it once:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Timer.set_tz(-7, 'MST')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Start time: 2019-06-02 16:25:59.777250-07:00\n",
+ "End time: 2019-06-02 16:26:01.781431-07:00\n",
+ "Elapsed: 2.004181 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f'Start time: {t1.start_time}')\n",
+ "print(f'End time: {t1.end_time}')\n",
+ "print(f'Elapsed: {t1.elapsed} seconds')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Start time: 2019-06-02 16:26:01.787596-07:00\n",
+ "End time: 2019-06-02 16:26:04.792814-07:00\n",
+ "Elapsed: 3.005218 seconds\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(f'Start time: {t2.start_time}')\n",
+ "print(f'End time: {t2.end_time}')\n",
+ "print(f'Elapsed: {t2.elapsed} seconds')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 02 - Classes/14 - Class Body Scope.ipynb b/Part 4/Section 02 - Classes/14 - Class Body Scope.ipynb
new file mode 100644
index 00000000..b5a97b22
--- /dev/null
+++ b/Part 4/Section 02 - Classes/14 - Class Body Scope.ipynb
@@ -0,0 +1,535 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Class Body Scope"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The class body is a scope and therefore has it's own namespace. Inside that scope we can reference symbols like we would within any other scope:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Language:\n",
+ " MAJOR = 3\n",
+ " MINOR = 7\n",
+ " REVISION = 4\n",
+ " FULL = '{}.{}.{}'.format(MAJOR, MINOR, REVISION)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7.4'"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Language.FULL"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, functions defined inside the class are not nested in the body scope - instead they are nested in whatever scope the class itself is in."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means that we cannot reference the class symbols inside a function without also telling Python where to look for it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Language:\n",
+ " MAJOR = 3\n",
+ " MINOR = 7\n",
+ " REVISION = 4\n",
+ " \n",
+ " @property\n",
+ " def version(self):\n",
+ " return '{}.{}.{}'.format(self.MAJOR, self.MINOR, self.REVISION)\n",
+ " \n",
+ " @classmethod\n",
+ " def cls_version(cls):\n",
+ " return '{}.{}.{}'.format(cls.MAJOR, cls.MINOR, cls.REVISION)\n",
+ " \n",
+ " @staticmethod\n",
+ " def static_version():\n",
+ " return '{}.{}.{}'.format(Language.MAJOR, Language.MINOR, Language.REVISION)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7.4'"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "l = Language()\n",
+ "l.version"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7.4'"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Language.cls_version()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7.4'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Language.static_version()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Basically think that the function symbols are in the class body namespace, but the functions themselves are defined externally to the class - just as if we had written it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def full_version():\n",
+ " return '{}.{}.{}'.format(Language.MAJOR, Language.MINOR, Language.REVISION)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'3.7.4'"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "full_version()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So writing something like this will not work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Language:\n",
+ " MAJOR = 3\n",
+ " MINOR = 7\n",
+ " REVISION = 4\n",
+ " \n",
+ " @classmethod\n",
+ " def cls_version(cls):\n",
+ " return '{}.{}.{}'.format(MAJOR, MINOR, REVISION)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "NameError",
+ "evalue": "name 'MAJOR' is not defined",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
+ "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mLanguage\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcls_version\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
+ "\u001b[0;32m\u001b[0m in \u001b[0;36mcls_version\u001b[0;34m(cls)\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m@\u001b[0m\u001b[0mclassmethod\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mcls_version\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcls\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0;34m'{}.{}.{}'\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mformat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mMAJOR\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mMINOR\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mREVISION\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m: name 'MAJOR' is not defined"
+ ]
+ }
+ ],
+ "source": [
+ "Language.cls_version()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This behavior can lead to subtle bugs if we aren't careful. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happens if the names `MAJOR`, `MINOR` and `REVISION` **are** defined in the enclosing scope?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "MAJOR = 0\n",
+ "MINOR = 0\n",
+ "REVISION = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0.0.1'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Language.cls_version()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See what happened?!!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now of course, the nested scopes follow the same usual rules, so we could technically have something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "MAJOR = 0\n",
+ "MINOR = 0\n",
+ "REVISION = 1\n",
+ "\n",
+ "def gen_class():\n",
+ " MAJOR = 0\n",
+ " MINOR = 4\n",
+ " REVISION = 2\n",
+ " \n",
+ " class Language:\n",
+ " MAJOR = 3\n",
+ " MINOR = 7\n",
+ " REVISION = 4\n",
+ "\n",
+ " @classmethod\n",
+ " def version(cls):\n",
+ " return '{}.{}.{}'.format(MAJOR, MINOR, REVISION)\n",
+ " \n",
+ " return Language"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "cls = gen_class()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0.4.2'"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cls.version()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Notice how the scope of `version` was nested inside `gen_class` which itself is nested in the `global` scope.\n",
+ "\n",
+ "When we called the `version` method, it found the `MAJOR`, `MINOR` and `REVISION` in the closest enclosing scope - which turned out to be the `gen_class` scope.\n",
+ "\n",
+ "This means by the way, that `version` is not only a method, but actually a closure."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import inspect"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "ClosureVars(nonlocals={'MAJOR': 0, 'MINOR': 4, 'REVISION': 2}, globals={}, builtins={'format': }, unbound=set())"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "inspect.getclosurevars(cls.version)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This last example of \"unexpected\" behavior I want to show you was show to me by a friend who was puzzled by it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "name = 'Guido'\n",
+ "\n",
+ "class MyClass:\n",
+ " name = 'Raymond'\n",
+ " list_1 = [name] * 3\n",
+ " list_2 = [name.upper() for i in range(3)]\n",
+ " \n",
+ " @classmethod\n",
+ " def hello(cls):\n",
+ " return '{} says hello'.format(name)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['Raymond', 'Raymond', 'Raymond']"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.list_1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since the expression `[name] * 3` lives in the class body, it uses `name` that it finds in the class namespace."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Guido says hello'"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.hello()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here, `name` is used inside a function, so the closest `name` symbol is the one in the module/global scope. Hence we see that `Guido` was used."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['GUIDO', 'GUIDO', 'GUIDO']"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "MyClass.list_2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That one is more puzzling... Why is the expression `[name.upper() for i in range(3)]` using `name` from the enclosing (module/global) scope, and not the one from the class namespace like `[name] * 3` did?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Remember what we discussed about comprehensions?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "They are essentially thinly veiled **functions**!!!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So they behave like a function would, and therefore are not nested in the class body scope, but, in this case, in the module/global scope!"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/01 - Project 1.ipynb b/Part 4/Section 03 - Project 1/01 - Project 1.ipynb
new file mode 100644
index 00000000..af712e6d
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/01 - Project 1.ipynb
@@ -0,0 +1,131 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We need to design an dimplement a class that will be used to represent bank accounts.\n",
+ "\n",
+ "We want the following functionality and characteristics:\n",
+ "- accounts are uniquely identified by an **account number** (assume it will just be passed in the initializer)\n",
+ "- account holders have a **first** and **last** name\n",
+ "- accounts have an associated **preferred time zone offset** (e.g. -7 for MST)\n",
+ "- **balances** need to be zero or higher, and should not be directly settable.\n",
+ "- but, **deposits** and **withdrawals** can be made (given sufficient funds)\n",
+ " - if a withdrawal is attempted that would result in nagative funds, the transaction should be declined.\n",
+ "- a **monthly interest rate** exists and is applicable to all accounts **uniformly**. There should be a method that can be called to calculate the interest on the current balance using the current interest rate, and **add it** to the balance.\n",
+ "- each deposit and withdrawal must generate a **confirmation number** composed of:\n",
+ " - the transaction type: `D` for deposit, and `W` for withdrawal, `I` for interest deposit, and `X` for declined (in which case the balance remains unaffected)\n",
+ " - the account number\n",
+ " - the time the transaction was made, using UTC\n",
+ " - an incrementing number (that increments across all accounts and transactions)\n",
+ " - for (extreme!) simplicity assume that the transaction id starts at zero (or whatever number you choose) whenever the program starts\n",
+ " - the confirmation number should be returned from any of the transaction methods (deposit, withdraw, etc)\n",
+ "- create a **method** that, given a confirmation number, returns:\n",
+ " - the account number, transaction code (D, W, etc), datetime (UTC format), date time (in whatever timezone is specified in te argument, but more human readable), the transaction ID\n",
+ " - make it so it is a nicely structured object (so can use dotted notation to access these three attributes)\n",
+ " - I purposefully made it so the desired timezone is passed as an argument. Can you figure out why? (hint: does this method require any information from any instance?)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example, we may have an account with:\n",
+ "- account number `140568` \n",
+ "- preferred time zone offset of -7 (MST) \n",
+ "- an existing balance of `100.00`\n",
+ "\n",
+ "Suppose the last transaction ID in the system was `123`, and a deposit is made for `50.00` on `2019-03-15T14:59:00` (UTC) on that account (or `2019-03-15T07:59:00` in account's preferred time zone offset)\n",
+ "\n",
+ "The new balance should reflect `150.00` and the confirmation number returned should look something like this:\n",
+ "\n",
+ "```D-140568-20190315145900-124```\n",
+ "\n",
+ "We also want a method that given the confirmation number returns an object with attributes:\n",
+ "- `result.account_number` --> `140568`\n",
+ "- `result.transaction_code` --> `D`\n",
+ "- `result.transaction_id` --> `124`\n",
+ "- `result.time` --> `2019-03-15 07:59:00 (MST)`\n",
+ "- `result.time_utc` --> `2019-03-15T14:59:00`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Furthermore, if current interest rate is `0.5%`, and the account's balance is `1000.00`, then the result of calling the `deposit_interest` (or whatever name you choose) method, should result in a new transaction and a new balance of `1050.00`. Calling this method should also return a confirmation number.\n",
+ "\n",
+ "For simplicty, just use floats, but be aware that for these types of situations you'll probably want to use `Decimal` objects instead of floats."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There are going to be many ways to design something like this, especially since I have not nailed down all the specific requirements, so you'll have to fill the gaps yourself and decide what other things you may want to implement (like is the account number going to be a mutable property, or \"read-only\" and so on).\n",
+ "\n",
+ "See how many different ideas you can use from what we covered in the last section. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "My approach will end up creating two classes: a `TimeZone` class used to store the time zone name and offset definition (in hours and minutes), and a main class called `Account` that will have the following \"public\" interface:\n",
+ "- initializer with account number, first name, last name, optional preferred time zone, starting balance (defaults to 0)\n",
+ "- a first name property (read/write)\n",
+ "- a last name property (read/write)\n",
+ "- a full name property (computed, read-only)\n",
+ "- a balance property (read-only)\n",
+ "- an interest rate property (class level property)\n",
+ "- deposit, withdraw, pay_interest methods\n",
+ "- parse confirmation code\n",
+ "\n",
+ "Class will have additional state and methods, but those will be used for implementation."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You should also remember to test your code! In the solutions I will introduce you to Python's `unittest` package. Even if you skip this project, at least review that video and/or notebook if you are unfamiliar with `unittest`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/02 - TimeZone Class.ipynb b/Part 4/Section 03 - Project 1/02 - TimeZone Class.ipynb
new file mode 100644
index 00000000..f5d15c2a
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/02 - TimeZone Class.ipynb
@@ -0,0 +1,190 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1: TimeZone class"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's start with the timezone class. This one will have two instance attributes, offset and name. I'm going to create those as read-only properties. Offsets should be provided as a timespan (timedelta) of hours and minutes - we'll allow specifying the hour and minute offsets separately in the __init__, but the offset property will combine those as a timespan object."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " \n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's try it out and make sure it's working:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tz1 = TimeZone('ABC', -2, -15)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'ABC'"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "tz1.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2019-06-02 23:27:15.937254\n"
+ ]
+ }
+ ],
+ "source": [
+ "from datetime import datetime\n",
+ "\n",
+ "dt = datetime.utcnow()\n",
+ "print(dt)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2019-06-02 21:12:15.937254\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(dt + tz1.offset)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see the offset seems to be working (-2:15 from current time)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "(We really should be writing unit tests as we write our code - but I'll show you unit tests in the last section of this project, and next project we can code and unit test in parallel)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/03 - Transaction Numbers.ipynb b/Part 4/Section 03 - Project 1/03 - Transaction Numbers.ipynb
new file mode 100644
index 00000000..eacca953
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/03 - Transaction Numbers.ipynb
@@ -0,0 +1,232 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1: Transaction Numbers"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next I want something for the transaction ID logic.\n",
+ "\n",
+ "Basically, we just need an initialized counter that returns the next value every time it is called.\n",
+ "\n",
+ "We have different ways of doing this - since this is an OOP course, you might be tempted to jump straight into a class implementation for this.\n",
+ "\n",
+ "We could do it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TransactionID:\n",
+ " def __init__(self, start_id):\n",
+ " self._start_id = start_id\n",
+ " \n",
+ " def next(self):\n",
+ " self._start_id += 1\n",
+ " return self._start_id"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could then use an instance of this class as a class attribute for `Account` thusly:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = TransactionID(100)\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " new_trans_id = Account.transaction_counter.next()\n",
+ " return new_trans_id"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "101\n",
+ "102\n",
+ "103\n"
+ ]
+ }
+ ],
+ "source": [
+ "a1 = Account()\n",
+ "a2 = Account()\n",
+ "\n",
+ "print(a1.make_transaction())\n",
+ "print(a2.make_transaction())\n",
+ "print(a1.make_transaction())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, that works just fine, but if we think about this a bit more, we should see that we really do not need a class to solve this particular problem. We could even implement the iterator protocol for this class (implementing `__iter__` and `__next__`), but a simple infinite generator will work just as well.\n",
+ "\n",
+ "So moral of the story here, don't just jump into solving every problem using classes - this isn't Java, we don't need a class for everything!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Instead, I'm going to implement it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def transaction_ids(start_id):\n",
+ " while True:\n",
+ " start_id += 1\n",
+ " yield start_id"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we can use it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = transaction_ids(100)\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " new_trans_id = next(Account.transaction_counter)\n",
+ " return new_trans_id"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "101\n",
+ "102\n",
+ "103\n"
+ ]
+ }
+ ],
+ "source": [
+ "a1 = Account()\n",
+ "a2 = Account()\n",
+ "\n",
+ "print(a1.make_transaction())\n",
+ "print(a2.make_transaction())\n",
+ "print(a1.make_transaction())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this works equally well, but if we recall the `counter` method in the `itertools` module, we can simplify this even further:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "\n",
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " new_trans_id = next(Account.transaction_counter)\n",
+ " return new_trans_id"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "100\n",
+ "101\n",
+ "102\n"
+ ]
+ }
+ ],
+ "source": [
+ "a1 = Account()\n",
+ "a2 = Account()\n",
+ "\n",
+ "print(a1.make_transaction())\n",
+ "print(a2.make_transaction())\n",
+ "print(a1.make_transaction())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/04 - Account Number, First Name, Last Name.ipynb b/Part 4/Section 03 - Project 1/04 - Account Number, First Name, Last Name.ipynb
new file mode 100644
index 00000000..cecee75d
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/04 - Account Number, First Name, Last Name.ipynb
@@ -0,0 +1,345 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1: Account Number, First Name, Last Name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's our code so far:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")\n",
+ " \n",
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's implement the properties for account number, first name and last name."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError('First name cannot be empty.')\n",
+ " self._first_name = value\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError('Last name cannot be empty.')\n",
+ " self._last_name = value\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You'll notice how we are using the same basic functionality to validate the first and last names. Most likely we'll need to add additional validations, in which case we'd have to add it to both places.\n",
+ "\n",
+ "I don't like repetitive code, so I'm going to move the validation into a separate function. That function won't need access to the instance data, so that's a prime candidate for a static method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self._first_name = Account.validate_name(value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self._last_name = Account.validate_name(value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " \n",
+ " @staticmethod\n",
+ " def validate_name(value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " return str(value).strip()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Last Name cannot be empty.\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a = Account('12345', 'John', '')\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, just to show you how we could use `setattr`, we could also do something like this instead:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Last Name cannot be empty.\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a = Account('12345', 'John', '')\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = Account('12345', 'Alex', 'Martelli')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('Alex', 'Martelli', 'Alex Martelli')"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.first_name, a.last_name, a.full_name"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, whichever approach you prefer - I favor the second one because that way I have the same validation apply to both first and last name properties."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/05 - Adding Preferred TimeZone Property.ipynb b/Part 4/Section 03 - Project 1/05 - Adding Preferred TimeZone Property.ipynb
new file mode 100644
index 00000000..88c99969
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/05 - Adding Preferred TimeZone Property.ipynb
@@ -0,0 +1,252 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1: Adding the Preferred TimeZone Property"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's where we left off with our code:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")\n",
+ " \n",
+ " \n",
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The preferred time zone is in instance attribute, and should be read-write (account holder may want to change time zones later). We'll add it to the `__init__` method, and default it to UTC (so 0 offset), but provide getters and setters to read/write it later if needed."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, \n",
+ " timezone=None):\n",
+ " # in practice we probably would want to add checks to make \n",
+ " # sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Time zone must be a valid TimeZone object.\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a = Account('123', 'John', 'Smith', '-7:00')\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "TimeZone(name='UTC', offset_hours=0, offset_minutes=0)\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = Account('123', 'John', 'Smith')\n",
+ "print(a.timezone)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/06 - Balance.ipynb b/Part 4/Section 03 - Project 1/06 - Balance.ipynb
new file mode 100644
index 00000000..216a8f15
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/06 - Balance.ipynb
@@ -0,0 +1,275 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1 - Balance"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's where we left off with our code:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}' \n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Next we need to add something to maintain the balance. Again this is going to be a \"read-only\" property, and we'll add it as an optional param to the `__init__` method as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, \n",
+ " timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "100.0\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = Account('1234', 'John', 'Cleese', initial_balance=100)\n",
+ "print(a.balance)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "can't set attribute\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a.balance = 200\n",
+ "except AttributeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/07 - Interest Rate.ipynb b/Part 4/Section 03 - Project 1/07 - Interest Rate.ipynb
new file mode 100644
index 00000000..c3d2f153
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/07 - Interest Rate.ipynb
@@ -0,0 +1,481 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1 - Interest Rate"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our code so far:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The interest rate is common across all bank accounts, so we can use a class attribute for it. \n",
+ "\n",
+ "We haven't studied how to write class properties (we'll see how when we look at descriptors), so for now we could just use a bare attribute - not ideal, but let's try that first."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " interest_rate = 0.5 # percentage\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a1 = Account(1234, 'Monty', 'Python', initial_balance=0)\n",
+ "a2 = Account(2345, 'John', 'Cleese', initial_balance=0)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(0.5, 0.5)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a1.interest_rate, a2.interest_rate"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Account.interest_rate = 0.025"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(0.025, 0.025)"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a1.interest_rate, a2.interest_rate"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we don't feel comfortable with the bare attribute and want to validate changing the interest rate, then we could use a more Java-like approach with getter and setter class methods. \n",
+ "\n",
+ "We'll start by changing the class variable name to indicate it is a \"private\" attribute, then add a getter and a setter class method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "0.5"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Account.get_interest_rate()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Account.set_interest_rate(10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "10"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Account.get_interest_rate()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Interest rate cannot be negative.\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " Account.set_interest_rate(-10)\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Interest rate must be a real number\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " Account.set_interest_rate(1+1j)\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/08 - Transaction Codes.ipynb b/Part 4/Section 03 - Project 1/08 - Transaction Codes.ipynb
new file mode 100644
index 00000000..acf47bbe
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/08 - Transaction Codes.ipynb
@@ -0,0 +1,281 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1: Setting up Transaction Codes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our code so far:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, \n",
+ " timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to \n",
+ " # make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although we _could_ use hardcoded values for the `D`, `W`, `I`, and `X` transaction codes, I prefer to store them in a dictionary and lookup the code whenever I need to. That way, if we ever need to change those codes for some reason, we don't have to hunt them down in the code itself.\n",
+ "\n",
+ "So for that, I'm going to use a \"private\" class attribute (dictionary), with the assumption that the keys will **not** change, but the associated values (codes) **can**. We could actually go on step further and define \"constants\" for the keys as well, but I don't think that's really necessary.\n",
+ "\n",
+ "A better approach would be to use an **enumeration** type - but we're not there yet!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/09 - Confirmation Code.ipynb b/Part 4/Section 03 - Project 1/09 - Confirmation Code.ipynb
new file mode 100644
index 00000000..5f56bbf2
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/09 - Confirmation Code.ipynb
@@ -0,0 +1,757 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1 - Implementing Confirmation Codes"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our code so far:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As I mentioned earlier the code should contain:\n",
+ "- the transaction code\n",
+ "- the account number\n",
+ "- the date / time in UTC of the transaction\n",
+ "- the transaction number\n",
+ "\n",
+ "Something like:\n",
+ "```D-140568-20190115154500-124```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's first build this function in isolation, and then we'll add it to the class once we're happy with it:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def generate_confirmation_code(account_number, transaction_id, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{account_number}-{dt_str}-{transaction_id}'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'X-123-20190602232855-1000'"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "generate_confirmation_code(123, 1000, 'X')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's incorporate that as an instance method in our class - we won't need to pass account_numberor transaction_id - we can get those ourselves from within the class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we can test it out, let's write a dummy transaction method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " return self.generate_confirmation_code('dummy')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = Account('A100', 'John', 'Cleese', initial_balance=100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'dummy-A100-20190602232855-100'"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.make_transaction()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'dummy-A100-20190602232855-101'"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.make_transaction()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Confirmation Parser"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This one is actually going to be a static method. We don't really require the instance to reverse-engineer the confirmation code. We could, but then we probably would also want to check that the account number embedded in the conformation code is the same as the instance account number we are decoding from. There's not really a need for that.\n",
+ "\n",
+ "The other thing is we want to have a neat dotted notation to recover the various properties of the partsed confirmation code.\n",
+ "Once again, before jumping into creating a utility class for that, we can really get away with a named tuple here instead!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see what a confirmation code looks like:\n",
+ "```\n",
+ "dummy-A100-20190325224918-101\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, we can split things on a `-` symbol, and we'll have to parse the date time string into an actual date time (and we know confirmation codes use UTC dates)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import namedtuple\n",
+ "\n",
+ "Confirmation = namedtuple('Confirmation', 'account_number, transaction_code, transaction_id, time_utc, time')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " return self.generate_confirmation_code('dummy')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so let's try this out, and make sure it's working (within reason, this will not catch all badly formatted confirmation codes by any means):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "dummy-A100-20190602232855-100\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = Account('A100', 'John', 'Cleese', initial_balance=100)\n",
+ "conf_code = a.make_transaction()\n",
+ "print(conf_code)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Confirmation(account_number='A100', transaction_code='dummy', transaction_id='100', time_utc='2019-06-02T23:28:55', time='2019-06-02 23:28:55 (UTC)')"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Account.parse_confirmation_code(conf_code)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Confirmation(account_number='A100', transaction_code='dummy', transaction_id='100', time_utc='2019-06-02T23:28:55', time='2019-06-02 16:28:55 (MST)')"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "Account.parse_confirmation_code(conf_code, TimeZone('MST', -7, 0))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Invalid transaction datetime\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " Account.parse_confirmation_code('X-A100-asdasd-123')\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/10 - Transactions.ipynb b/Part 4/Section 03 - Project 1/10 - Transactions.ipynb
new file mode 100644
index 00000000..43beca30
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/10 - Transactions.ipynb
@@ -0,0 +1,807 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1 - Transactions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Our code so far:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta, datetime\n",
+ "from collections import namedtuple\n",
+ "\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def make_transaction(self):\n",
+ " return self.generate_confirmation_code('dummy')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now it's time to add in support for the various transaction methods:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = float(initial_balance) # force use of floats here, but maybe Decimal would be better\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def deposit(self, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Deposit value must be a real number.')\n",
+ " if value <= 0:\n",
+ " raise ValueError('Deposit value must be a positive number.')\n",
+ " \n",
+ " # get transaction code\n",
+ " transaction_code = Account._transaction_codes['deposit']\n",
+ " \n",
+ " # generate a confirmation code\n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # make deposit and return conf code\n",
+ " self._balance += value\n",
+ " return conf_code\n",
+ " \n",
+ " def withdraw(self, value):\n",
+ " # hmmm... repetitive code! we'll need to fix this\n",
+ " # TODO: refactor a function to validate a valid positive number\n",
+ " # and use in __init__, deposit and \n",
+ " \n",
+ " accepted = False\n",
+ " if self.balance - value < 0:\n",
+ " # insufficient funds - we'll reject this transaction\n",
+ " transaction_code = Account._transaction_codes['rejected']\n",
+ " else:\n",
+ " transaction_code = Account._transaction_codes['withdraw']\n",
+ " accepted = True\n",
+ " \n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # Doing this here in case there's a problem generating a confirmation code\n",
+ " # - do not want to modify the balance if we cannot generate a transaction code successfully\n",
+ " if accepted:\n",
+ " self._balance -= value\n",
+ " \n",
+ " return conf_code\n",
+ " \n",
+ " def pay_interestt(self):\n",
+ " interest = self.balance * Account.get_interest_rate() / 100\n",
+ " conf_code = self.generate_confirmation_code(Account._transaction_codes['interest'])\n",
+ " self._balance += interest\n",
+ " return conf_code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = Account('A100', 'Eric', 'Idle', TimeZone('MST', -7, 0), 100.0)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "100.0"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.balance"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'D-A100-20190602232906-100'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.deposit(100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "200.0"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.balance"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'W-A100-20190602232907-101'"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.withdraw(100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "100.0"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.balance"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'X-A100-20190602232907-102'"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.withdraw(1000)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "100.0"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a.balance"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Refactoring"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now, let's refactor some code. We have to do that real positive number validation. We'll deal with it in the same we dealt with the name validations, except we won't be storing anything - this is going to be a good candidate for a static method.\n",
+ "\n",
+ "While we're at it, we'll modify our `__init__` method as well to validate the balance. Remember I had stated in the project description that balances should never be negative. So, I'm going to introduce a subtle bug here where the initialization will validate that the initial balance is a real number, but will not validate that it be non-negative. We'll \"catch\" that bug later."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = Account.validate_real_number(initial_balance)\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " @staticmethod\n",
+ " def validate_real_number(value, min_value=None):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Value must be a real number.')\n",
+ " \n",
+ " if min_value is not None and value < min_value:\n",
+ " raise ValueError(f'Value must be at least {min_value}')\n",
+ " \n",
+ " # validation passed, return valid value\n",
+ " return value\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def deposit(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " \n",
+ " # get transaction code\n",
+ " transaction_code = Account._transaction_codes['deposit']\n",
+ " \n",
+ " # generate a confirmation code\n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # make deposit and return conf code\n",
+ " self._balance += value\n",
+ " return conf_code\n",
+ " \n",
+ " def withdraw(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " accepted = False\n",
+ " if self.balance - value < 0:\n",
+ " # insufficient funds - we'll reject this transaction\n",
+ " transaction_code = Account._transaction_codes['rejected']\n",
+ " else:\n",
+ " transaction_code = Account._transaction_codes['withdraw']\n",
+ " accepted = True\n",
+ " \n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # Doing this here in case there's a problem generating a confirmation code\n",
+ " # - do not want to modify the balance if we cannot generate a transaction code successfully\n",
+ " if accepted:\n",
+ " self._balance -= value\n",
+ " \n",
+ " return conf_code\n",
+ " \n",
+ " def pay_interest(self):\n",
+ " interest = self.balance * Account.get_interest_rate() / 100\n",
+ " conf_code = self.generate_confirmation_code(self._transaction_codes['interest'])\n",
+ " self._balance += interest\n",
+ " return conf_code"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We should now be seeing exceptions when using non-real or negative numbers"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = Account('A100', 'Eric', 'Idle', initial_balance=100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Value must be at least 0.01\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a.deposit(-100)\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Value must be a real number.\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " a.withdraw(\"100\")\n",
+ "except ValueError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this is where I am going to leave this implementation. In reality, there are a lof of other things we should consider such as additional validations, defining equality for two `Account` instances, and so on.\n",
+ "\n",
+ "Also, one major piece we have not really done is any kind of testing! We manually tested various pieces as we were coding, but there are multiple problems with this:\n",
+ "- the tests are not easily repeatable - every time we change code in our `Account` class we **really** need to re-run all the tests to make sure everything still works as expected and we have not broken anything.\n",
+ "- our tests were woefully inadequate - we tested just a few cases, and almost no edge cases.\n",
+ "\n",
+ "For serious production work, we need to test at least at the following levels:\n",
+ "- unit testing - where we test each piece of code in isolation and make sure all code branches are tested, edge cases are tested, etc (coverage)\n",
+ "- integration testing - where we test that multiple parts of our code works together correctly. For example, testing that multiple account creation, deposits, interest deposits, withdrawals, confirmation codes, etc work properly as a whole."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 03 - Project 1/11 - Testing using unittest.ipynb b/Part 4/Section 03 - Project 1/11 - Testing using unittest.ipynb
new file mode 100644
index 00000000..0b711f77
--- /dev/null
+++ b/Part 4/Section 03 - Project 1/11 - Testing using unittest.ipynb
@@ -0,0 +1,1655 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 1 - Unit Testing"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can imagine to fully test this code is going to take quite a bit of effort. I'm not going to do this here, so I very well may have bugs in my code. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In practice, a whole suite of tests should be written to ensure this code is working properly."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If you're thinking this will be as much work as writing the code itself - well... It will probably be **more** work.\n",
+ "\n",
+ "In my experience, designing and implementing unit tests takes longer than writing the code in the first place!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's a manual approach to a bit of integration testing:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First, our code:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import itertools\n",
+ "import numbers\n",
+ "from datetime import timedelta, datetime\n",
+ "from collections import namedtuple\n",
+ "\n",
+ "\n",
+ "class TimeZone:\n",
+ " def __init__(self, name, offset_hours, offset_minutes):\n",
+ " if name is None or len(str(name).strip()) == 0:\n",
+ " raise ValueError('Timezone name cannot be empty.')\n",
+ " \n",
+ " self._name = str(name).strip()\n",
+ " # technically we should check that offset is a\n",
+ " if not isinstance(offset_hours, numbers.Integral):\n",
+ " raise ValueError('Hour offset must be an integer.')\n",
+ " \n",
+ " if not isinstance(offset_minutes, numbers.Integral):\n",
+ " raise ValueError('Minutes offset must be an integer.')\n",
+ " \n",
+ " if offset_minutes < -59 or offset_minutes > 59:\n",
+ " raise ValueError('Minutes offset must between -59 and 59 (inclusive).')\n",
+ " \n",
+ " # for time delta sign of minutes will be set to sign of hours\n",
+ " offset = timedelta(hours=offset_hours, minutes=offset_minutes)\n",
+ "\n",
+ " # offsets are technically bounded between -12:00 and 14:00\n",
+ " # see: https://en.wikipedia.org/wiki/List_of_UTC_time_offsets\n",
+ " if offset < timedelta(hours=-12, minutes=0) or offset > timedelta(hours=14, minutes=0):\n",
+ " raise ValueError('Offset must be between -12:00 and +14:00.')\n",
+ " \n",
+ " self._offset_hours = offset_hours\n",
+ " self._offset_minutes = offset_minutes\n",
+ " self._offset = offset\n",
+ " \n",
+ " @property\n",
+ " def offset(self):\n",
+ " return self._offset\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return (isinstance(other, TimeZone) and \n",
+ " self.name == other.name and \n",
+ " self._offset_hours == other._offset_hours and\n",
+ " self._offset_minutes == other._offset_minutes)\n",
+ " def __repr__(self):\n",
+ " return (f\"TimeZone(name='{self.name}', \"\n",
+ " f\"offset_hours={self._offset_hours}, \"\n",
+ " f\"offset_minutes={self._offset_minutes})\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = Account.validate_real_number(initial_balance)\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if value is None or len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " @staticmethod\n",
+ " def validate_real_number(value, min_value=None):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Value must be a real number.')\n",
+ " \n",
+ " if min_value is not None and value < min_value:\n",
+ " raise ValueError(f'Value must be at least {min_value}')\n",
+ " \n",
+ " # validation passed, return valid value\n",
+ " return value\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def deposit(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " \n",
+ " # get transaction code\n",
+ " transaction_code = Account._transaction_codes['deposit']\n",
+ " \n",
+ " # generate a confirmation code\n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # make deposit and return conf code\n",
+ " self._balance += value\n",
+ " return conf_code\n",
+ " \n",
+ " def withdraw(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " accepted = False\n",
+ " if self.balance - value < 0:\n",
+ " # insufficient funds - we'll reject this transaction\n",
+ " transaction_code = Account._transaction_codes['rejected']\n",
+ " else:\n",
+ " transaction_code = Account._transaction_codes['withdraw']\n",
+ " accepted = True\n",
+ " \n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # Doing this here in case there's a problem generating a confirmation code\n",
+ " # - do not want to modify the balance if we cannot generate a transaction code successfully\n",
+ " if accepted:\n",
+ " self._balance -= value\n",
+ " \n",
+ " return conf_code\n",
+ " \n",
+ " def pay_interest(self):\n",
+ " interest = self.balance * Account.get_interest_rate() / 100\n",
+ " conf_code = self.generate_confirmation_code(Account._transaction_codes['interest'])\n",
+ " self._balance += interest\n",
+ " return conf_code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "100\n",
+ "D-A100-20190602232958-100\n",
+ "250.02\n",
+ "W-A100-20190602232958-101\n",
+ "250.0\n",
+ "1.0\n",
+ "I-A100-20190602232958-102\n",
+ "252.5\n",
+ "X-A100-20190602232958-103\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = Account('A100', 'Eric', 'Idle', timezone=TimeZone('MST', -7, 0), initial_balance=100)\n",
+ "print(a.balance)\n",
+ "print(a.deposit(150.02))\n",
+ "print(a.balance)\n",
+ "print(a.withdraw(0.02))\n",
+ "print(a.balance)\n",
+ "Account.set_interest_rate(1.0)\n",
+ "print(a.get_interest_rate())\n",
+ "print(a.pay_interest())\n",
+ "print(a.balance)\n",
+ "print(a.withdraw(1000))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so that works, but of course we really need to test things a whole lot more, including various scenarios (like withdrawing with insufficient funds, and so on). Also our tests really need to be easily repeatable so we can re-run our tests every time we make a code change.\n",
+ "\n",
+ "For that I'm going to introduce you to the `unitest` framework in Python.\n",
+ "\n",
+ "In production environments, a 3rd party library (that leverages `unittest`) is used that extends the base `unittest` framework. But for now, `unittest` will work just fine for us."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Normally, unit tests are invoked from the command line, which in turn sets up a test runner and seamlessly runs our tests. In this case, so I can stay within a Jupyter Notebook I'll have to add a few extra chunks of code to set up a test runner manually - this is usually not necessary."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import unittest"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def run_tests(test_class):\n",
+ " suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n",
+ " runner = unittest.TextTestRunner(verbosity=2)\n",
+ " result = runner.run(suite)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see how some simple tests are setup and executed:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " def test_ok(self):\n",
+ " self.assertEqual(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_ok (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 1 test in 0.001s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In cases where the a test fails:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " def test_ok(self):\n",
+ " self.assertEqual(1, 0)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_ok (__main__.TestAccount) ... FAIL\n",
+ "\n",
+ "======================================================================\n",
+ "FAIL: test_ok (__main__.TestAccount)\n",
+ "----------------------------------------------------------------------\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 3, in test_ok\n",
+ " self.assertEqual(1, 0)\n",
+ "AssertionError: 1 != 0\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 1 test in 0.001s\n",
+ "\n",
+ "FAILED (failures=1)\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now we can write some simple unit tests. The only thing is that each unit test should be a function in the class that starts with the word `test` - that way it is automatically identified as a unit test.\n",
+ "\n",
+ "We also have the option of defining setup and tear down functionality - these are just methods that will be executed before **each** test method, and right **after**. - here's a simple example that shows how that works:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " def setUp(self):\n",
+ " print('Running setup...')\n",
+ " self.account_number = 'A100'\n",
+ " \n",
+ " def tearDown(self):\n",
+ " print('Running tear down...')\n",
+ " \n",
+ " def test_1(self):\n",
+ " self.account_number = 'A200'\n",
+ " self.assertTrue('A200', self.account_number)\n",
+ " \n",
+ " def test_2(self):\n",
+ " self.assertTrue('A100', self.account_number)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_1 (__main__.TestAccount) ... ok\n",
+ "test_2 (__main__.TestAccount) ... "
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Running setup...\n",
+ "Running tear down...\n",
+ "Running setup...\n",
+ "Running tear down...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 2 tests in 0.001s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Even, if the test fails, the tear down method will still run:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " def setUp(self):\n",
+ " print('Running setup...')\n",
+ " \n",
+ " def tearDown(self):\n",
+ " print('Running tear down...')\n",
+ " \n",
+ " def testOK(self):\n",
+ " self.assertTrue(False)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "testOK (__main__.TestAccount) ... "
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Running setup...\n",
+ "Running tear down...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "FAIL\n",
+ "\n",
+ "======================================================================\n",
+ "FAIL: testOK (__main__.TestAccount)\n",
+ "----------------------------------------------------------------------\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 9, in testOK\n",
+ " self.assertTrue(False)\n",
+ "AssertionError: False is not true\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 1 test in 0.001s\n",
+ "\n",
+ "FAILED (failures=1)\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we could use `setUp` to maybe create some bank accounts that we can use throughout our tests. Remember that `TestAccount` is a class, so we can create instance attributes in the `setUp` method, and access them in any of the instance methods (like the test methods).\n",
+ "\n",
+ "Another thing to watch out for is that there is no guarantee of the order in which the unit tests are run. Best practice is that unit tests should be independent of each other."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's add some simple unit tests for the TimeZone class first:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for test_tz in test_timezones:\n",
+ " self.assertNotEqual(tz, test_tz)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 3 tests in 0.002s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Notice how we needed to run multiple scenarios for testing non-equal time zones. This is a fairly common occurrence, and there's a better way to set this up so we actually have separate tests, that are distinguishable from each other (it's slightly easier when using pytest, but the end result is similar):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 3 tests in 0.002s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Where this might be handy is in the case of a test failure:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30),\n",
+ " TimeZone('ABC', -1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... \n",
+ "======================================================================\n",
+ "FAIL: test_timezones_not_equal (__main__.TestAccount) (test_number=3)\n",
+ "----------------------------------------------------------------------\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 24, in test_timezones_not_equal\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ "AssertionError: TimeZone(name='ABC', offset_hours=-1, offset_minutes=-30) == TimeZone(name='ABC', offset_hours=-1, offset_minutes=-30)\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 3 tests in 0.002s\n",
+ "\n",
+ "FAILED (failures=1)\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see we have a message associated with the failed test.\n",
+ "\n",
+ "Let's go back and remove that incorrect test:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now we can start adding additional unit tests for our Account class.\n",
+ "\n",
+ "Remember that unit tests are meant to test one specific piece of functionality - don't try to group too much in your tests, as otherwise the error messages can become less meaningful, making harder to track down the actual problem.\n",
+ "\n",
+ "A recommended practice is either to set up unit tests **before** you write your code, or soon after. Here I left writing unit tests to the end, and this leads to badly written, or simply omitted unit tests because it becomes too tedious!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "I'm only going to add a few more tests, and you can continue writing them on your own. We'll use unit tests again, and introduce additional functionality over time."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ " \n",
+ " def test_create_account(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " self.assertEqual(account_number, a.account_number)\n",
+ " self.assertEqual(first_name, a.first_name)\n",
+ " self.assertEqual(last_name, a.last_name)\n",
+ " self.assertEqual(first_name + ' ' + last_name, a.full_name)\n",
+ " self.assertEqual(tz, a.timezone)\n",
+ " self.assertEqual(balance, a.balance)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 4 tests in 0.003s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "One last piece of unit testing functionality, is handling exceptions when they are **expected**, for example creating an account with an empty first name should result in a `ValueError` exception. We can write a unit test that will test this expected exception, and which will fail if the exception is not encountered (or is a different exception).\n",
+ "\n",
+ "To do this we need to indicate that an exception is expected, as well as the expected exception class."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ " \n",
+ " def test_create_account(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " self.assertEqual(account_number, a.account_number)\n",
+ " self.assertEqual(first_name, a.first_name)\n",
+ " self.assertEqual(last_name, a.last_name)\n",
+ " self.assertEqual(first_name + ' ' + last_name, a.full_name)\n",
+ " self.assertEqual(tz, a.timezone)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " \n",
+ " def test_create_account_blank_first_name(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = ''\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " with self.assertRaises(ValueError):\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_account_blank_first_name (__main__.TestAccount) ... ok\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 5 tests in 0.003s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But, if we were looking for a different exception:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ " \n",
+ " def test_create_account(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " self.assertEqual(account_number, a.account_number)\n",
+ " self.assertEqual(first_name, a.first_name)\n",
+ " self.assertEqual(last_name, a.last_name)\n",
+ " self.assertEqual(first_name + ' ' + last_name, a.full_name)\n",
+ " self.assertEqual(tz, a.timezone)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " \n",
+ " def test_create_account_blank_first_name(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = ''\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " with self.assertRaises(TypeError):\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_account_blank_first_name (__main__.TestAccount) ... ERROR\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "======================================================================\n",
+ "ERROR: test_create_account_blank_first_name (__main__.TestAccount)\n",
+ "----------------------------------------------------------------------\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 48, in test_create_account_blank_first_name\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " File \"\", line 15, in __init__\n",
+ " self.first_name = first_name\n",
+ " File \"\", line 34, in first_name\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " File \"\", line 77, in validate_and_set_name\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ "ValueError: First Name cannot be empty.\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 5 tests in 0.004s\n",
+ "\n",
+ "FAILED (errors=1)\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can start to see, there are a lot of gaps in our `Account` implementation. For example, we allow empty account numbers, negative starting balances. As you start writing unit tests you will not only discover bugs in your code, but also gaps in your design and implementation!\n",
+ "\n",
+ "Let's fix our unit test back to expecting a `ValueError`, and write a few more."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ " \n",
+ " def test_create_account(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " self.assertEqual(account_number, a.account_number)\n",
+ " self.assertEqual(first_name, a.first_name)\n",
+ " self.assertEqual(last_name, a.last_name)\n",
+ " self.assertEqual(first_name + ' ' + last_name, a.full_name)\n",
+ " self.assertEqual(tz, a.timezone)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " \n",
+ " def test_create_account_blank_first_name(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = ''\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " with self.assertRaises(ValueError):\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " \n",
+ " def test_account_deposit_ok(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.deposit(100)\n",
+ " self.assertEqual(200, a.balance)\n",
+ " self.assertIn('D-', conf_code)\n",
+ " \n",
+ " def test_account_deposit_negative_amount(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " with self.assertRaises(ValueError):\n",
+ " conf_code = a.deposit(-100)\n",
+ " \n",
+ " def test_account_withdraw_ok(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.withdraw(20)\n",
+ " self.assertEqual(80, a.balance)\n",
+ " self.assertIn('W-', conf_code)\n",
+ " \n",
+ " \n",
+ " def test_account_withdraw_overdraw(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.withdraw(200)\n",
+ " self.assertIn('X-', conf_code)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_account_deposit_negative_amount (__main__.TestAccount) ... ok\n",
+ "test_account_deposit_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_overdraw (__main__.TestAccount) ... ok\n",
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_account_blank_first_name (__main__.TestAccount) ... ok\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 9 tests in 0.005s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's add one more unit test, that checkes to make sure we cannot create accounts with negative balances:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class TestAccount(unittest.TestCase):\n",
+ " \n",
+ " def test_create_timezone(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual('ABC', tz.name)\n",
+ " self.assertEqual(timedelta(hours=-1, minutes=-30), tz.offset)\n",
+ " \n",
+ " def test_timezones_equal(self):\n",
+ " tz1 = TimeZone('ABC', -1, -30)\n",
+ " tz2 = TimeZone('ABC', -1, -30)\n",
+ " self.assertEqual(tz1, tz2)\n",
+ " \n",
+ " def test_timezones_not_equal(self):\n",
+ " tz = TimeZone('ABC', -1, -30)\n",
+ " \n",
+ " test_timezones = (\n",
+ " TimeZone('DEF', -1, -30),\n",
+ " TimeZone('ABC', -1, 0),\n",
+ " TimeZone('ABC', 1, -30)\n",
+ " )\n",
+ " for i, test_tz in enumerate(test_timezones):\n",
+ " with self.subTest(test_number=i):\n",
+ " self.assertNotEqual(tz, test_tz)\n",
+ " \n",
+ " def test_create_account(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " self.assertEqual(account_number, a.account_number)\n",
+ " self.assertEqual(first_name, a.first_name)\n",
+ " self.assertEqual(last_name, a.last_name)\n",
+ " self.assertEqual(first_name + ' ' + last_name, a.full_name)\n",
+ " self.assertEqual(tz, a.timezone)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " \n",
+ " def test_create_account_blank_first_name(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = ''\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = 100.00\n",
+ " \n",
+ " with self.assertRaises(ValueError):\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " \n",
+ " def test_create_account_negative_balance(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " tz = TimeZone('TZ', 1, 30)\n",
+ " balance = -100.00\n",
+ " \n",
+ " with self.assertRaises(ValueError):\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ " \n",
+ " def test_account_deposit_ok(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.deposit(100)\n",
+ " self.assertEqual(200, a.balance)\n",
+ " self.assertIn('D-', conf_code)\n",
+ " \n",
+ " def test_account_deposit_negative_amount(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " with self.assertRaises(ValueError):\n",
+ " conf_code = a.deposit(-100)\n",
+ " \n",
+ " def test_account_withdraw_ok(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.withdraw(20)\n",
+ " self.assertEqual(80, a.balance)\n",
+ " self.assertIn('W-', conf_code)\n",
+ " \n",
+ " \n",
+ " def test_account_withdraw_overdraw(self):\n",
+ " account_number = 'A100'\n",
+ " first_name = 'FIRST'\n",
+ " last_name = 'LAST'\n",
+ " balance = 100.00\n",
+ " \n",
+ " a = Account(account_number, first_name, last_name, initial_balance=balance)\n",
+ " conf_code = a.withdraw(200)\n",
+ " self.assertIn('X-', conf_code)\n",
+ " self.assertEqual(balance, a.balance)\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_account_deposit_negative_amount (__main__.TestAccount) ... ok\n",
+ "test_account_deposit_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_overdraw (__main__.TestAccount) ... ok\n",
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_account_blank_first_name (__main__.TestAccount) ... ok\n",
+ "test_create_account_negative_balance (__main__.TestAccount) ... FAIL\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "======================================================================\n",
+ "FAIL: test_create_account_negative_balance (__main__.TestAccount)\n",
+ "----------------------------------------------------------------------\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 58, in test_create_account_negative_balance\n",
+ " a = Account(account_number, first_name, last_name, tz, balance)\n",
+ "AssertionError: ValueError not raised\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 10 tests in 0.006s\n",
+ "\n",
+ "FAILED (failures=1)\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Oh-oh, we are not raising an exception! That's a bug in our code.\n",
+ "\n",
+ "So, let's fix it, and re-run the tests:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Account:\n",
+ " transaction_counter = itertools.count(100)\n",
+ " _interest_rate = 0.5 # percentage\n",
+ " \n",
+ " _transaction_codes = {\n",
+ " 'deposit': 'D',\n",
+ " 'withdraw': 'W',\n",
+ " 'interest': 'I',\n",
+ " 'rejected': 'X'\n",
+ " }\n",
+ " \n",
+ " def __init__(self, account_number, first_name, last_name, timezone=None, initial_balance=0):\n",
+ " # in practice we probably would want to add checks to make sure these values are valid / non-empty\n",
+ " self._account_number = account_number\n",
+ " self.first_name = first_name\n",
+ " self.last_name = last_name\n",
+ " \n",
+ " if timezone is None:\n",
+ " timezone = TimeZone('UTC', 0, 0)\n",
+ " self.timezone = timezone\n",
+ " \n",
+ " self._balance = Account.validate_real_number(initial_balance, min_value=0)\n",
+ " \n",
+ " @property\n",
+ " def account_number(self):\n",
+ " return self._account_number\n",
+ " \n",
+ " @property \n",
+ " def first_name(self):\n",
+ " return self._first_name\n",
+ " \n",
+ " @first_name.setter\n",
+ " def first_name(self, value):\n",
+ " self.validate_and_set_name('_first_name', value, 'First Name')\n",
+ " \n",
+ " @property\n",
+ " def last_name(self):\n",
+ " return self._last_name\n",
+ " \n",
+ " @last_name.setter\n",
+ " def last_name(self, value):\n",
+ " self.validate_and_set_name('_last_name', value, 'Last Name')\n",
+ " \n",
+ " # also going to create a full_name computed property, for ease of use\n",
+ " @property\n",
+ " def full_name(self):\n",
+ " return f'{self.first_name} {self.last_name}'\n",
+ " \n",
+ " @property\n",
+ " def timezone(self):\n",
+ " return self._timezone\n",
+ " \n",
+ " @property\n",
+ " def balance(self):\n",
+ " return self._balance\n",
+ " \n",
+ " @timezone.setter\n",
+ " def timezone(self, value):\n",
+ " if not isinstance(value, TimeZone):\n",
+ " raise ValueError('Time zone must be a valid TimeZone object.')\n",
+ " self._timezone = value\n",
+ " \n",
+ " @classmethod\n",
+ " def get_interest_rate(cls):\n",
+ " return cls._interest_rate\n",
+ " \n",
+ " @classmethod\n",
+ " def set_interest_rate(cls, value):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Interest rate must be a real number')\n",
+ " if value < 0:\n",
+ " raise ValueError('Interest rate cannot be negative.')\n",
+ " cls._interest_rate = value\n",
+ " \n",
+ " def validate_and_set_name(self, property_name, value, field_title):\n",
+ " if len(str(value).strip()) == 0:\n",
+ " raise ValueError(f'{field_title} cannot be empty.')\n",
+ " setattr(self, property_name, value)\n",
+ " \n",
+ " @staticmethod\n",
+ " def validate_real_number(value, min_value=None):\n",
+ " if not isinstance(value, numbers.Real):\n",
+ " raise ValueError('Value must be a real number.')\n",
+ " \n",
+ " if min_value is not None and value < min_value:\n",
+ " raise ValueError(f'Value must be at least {min_value}')\n",
+ " \n",
+ " # validation passed, return valid value\n",
+ " return value\n",
+ " \n",
+ " def generate_confirmation_code(self, transaction_code):\n",
+ " # main difficulty here is to generate the current time in UTC using this formatting:\n",
+ " # YYYYMMDDHHMMSS\n",
+ " dt_str = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n",
+ " return f'{transaction_code}-{self.account_number}-{dt_str}-{next(Account.transaction_counter)}'\n",
+ " \n",
+ " @staticmethod\n",
+ " def parse_confirmation_code(confirmation_code, preferred_time_zone=None):\n",
+ " # dummy-A100-20190325224918-101\n",
+ " parts = confirmation_code.split('-')\n",
+ " if len(parts) != 4:\n",
+ " # really simplistic validation here - would need something better\n",
+ " raise ValueError('Invalid confirmation code')\n",
+ " \n",
+ " # unpack into separate variables\n",
+ " transaction_code, account_number, raw_dt_utc, transaction_id = parts\n",
+ " \n",
+ " # need to convert raw_dt_utc into a proper datetime object\n",
+ " try:\n",
+ " dt_utc = datetime.strptime(raw_dt_utc, '%Y%m%d%H%M%S')\n",
+ " except ValueError as ex:\n",
+ " # again, probably need better error handling here\n",
+ " raise ValueError('Invalid transaction datetime') from ex\n",
+ " \n",
+ " if preferred_time_zone is None:\n",
+ " preferred_time_zone = TimeZone('UTC', 0, 0)\n",
+ " \n",
+ " if not isinstance(preferred_time_zone, TimeZone):\n",
+ " raise ValueError('Invalid TimeZone specified.')\n",
+ " \n",
+ " dt_preferred = dt_utc + preferred_time_zone.offset\n",
+ " dt_preferred_str = f\"{dt_preferred.strftime('%Y-%m-%d %H:%M:%S')} ({preferred_time_zone.name})\"\n",
+ " \n",
+ " return Confirmation(account_number, transaction_code, transaction_id, dt_utc.isoformat(), dt_preferred_str)\n",
+ " \n",
+ " def deposit(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " \n",
+ " # get transaction code\n",
+ " transaction_code = Account._transaction_codes['deposit']\n",
+ " \n",
+ " # generate a confirmation code\n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # make deposit and return conf code\n",
+ " self._balance += value\n",
+ " return conf_code\n",
+ " \n",
+ " def withdraw(self, value):\n",
+ " value = Account.validate_real_number(value, min_value=0.01)\n",
+ " accepted = False\n",
+ " if self.balance - value < 0:\n",
+ " # insufficient funds - we'll reject this transaction\n",
+ " transaction_code = Account._transaction_codes['rejected']\n",
+ " else:\n",
+ " transaction_code = Account._transaction_codes['withdraw']\n",
+ " accepted = True\n",
+ " \n",
+ " conf_code = self.generate_confirmation_code(transaction_code)\n",
+ " \n",
+ " # Doing this here in case there's a problem generating a confirmation code\n",
+ " # - do not want to modify the balance if we cannot generate a transaction code successfully\n",
+ " if accepted:\n",
+ " self._balance -= value\n",
+ " \n",
+ " return conf_code\n",
+ " \n",
+ " def pay_interest(self):\n",
+ " interest = self.balance * Account.get_interest_rate() / 100\n",
+ " conf_code = self.generate_confirmation_code(Account._transaction_codes['interest'])\n",
+ " self._balance += interest\n",
+ " return conf_code"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "test_account_deposit_negative_amount (__main__.TestAccount) ... ok\n",
+ "test_account_deposit_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_ok (__main__.TestAccount) ... ok\n",
+ "test_account_withdraw_overdraw (__main__.TestAccount) ... ok\n",
+ "test_create_account (__main__.TestAccount) ... ok\n",
+ "test_create_account_blank_first_name (__main__.TestAccount) ... ok\n",
+ "test_create_account_negative_balance (__main__.TestAccount) ... ok\n",
+ "test_create_timezone (__main__.TestAccount) ... ok\n",
+ "test_timezones_equal (__main__.TestAccount) ... ok\n",
+ "test_timezones_not_equal (__main__.TestAccount) ... ok\n",
+ "\n",
+ "----------------------------------------------------------------------\n",
+ "Ran 10 tests in 0.006s\n",
+ "\n",
+ "OK\n"
+ ]
+ }
+ ],
+ "source": [
+ "run_tests(TestAccount)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now our tests pass!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And so on... !\n",
+ "\n",
+ "You should add at least a few more unit tests to this to get some extra practice."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/01 - __str__ and __repr__ Methods.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/01 - __str__ and __repr__ Methods.ipynb
new file mode 100644
index 00000000..7f7a3e20
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/01 - __str__ and __repr__ Methods.ipynb
@@ -0,0 +1,703 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `__str__` and `__repr__`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see how this works by first implementing the `__repr__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name, age):\n",
+ " self.name = name\n",
+ " self.age = age\n",
+ " \n",
+ " def __repr__(self):\n",
+ " print('__repr__ called')\n",
+ " return f\"Person(name='{self.name}, age={self.age}')\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Python', 30)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's how Jupyter shows us the string representation for the object `p`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Person(name='Python, age=30')"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's what it looks like when we use the `print` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n",
+ "Person(name='Python, age=30')\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here's what happens if we call the `repr` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "\"Person(name='Python, age=30')\""
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "repr(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And here's what happens when we call the `str` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "\"Person(name='Python, age=30')\""
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "str(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, in all cases, our `__repr__` method was called.\n",
+ "\n",
+ "Now, let's implement a `__str__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name, age):\n",
+ " self.name = name\n",
+ " self.age = age\n",
+ " \n",
+ " def __repr__(self):\n",
+ " print('__repr__ called')\n",
+ " return f\"Person(name='{self.name}, age=self.age')\"\n",
+ " \n",
+ " def __str__(self):\n",
+ " print('__str__ called')\n",
+ " return self.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Python', 30)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And let's try out each of the ways to get a string representation for `p`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Person(name='Python, age=self.age')"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, same as before - uses the `__repr__` method."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n",
+ "Python\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, `print` will try to use `__str__` if present, otherwise it will fall back to using `__repr__`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Python'"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "str(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As expected, `str()` will try to use the `__str__` method first."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "\"Person(name='Python, age=self.age')\""
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "repr(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Whereas the `repr()` method will use the `__repr__` method directly."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happens if we define a `__str__` method, but not `__repr__` method.\n",
+ "\n",
+ "We'll look at inheritance later, but for now think of it as Python providing \"defaults\" for those methods when they are not present.\n",
+ "\n",
+ "Let's first see how it works if we do not have either of those methods for two different classes:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass\n",
+ "\n",
+ "class Point:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "person = Person()\n",
+ "point = Point()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('<__main__.Person object at 0x7fbfe954b860>',\n",
+ " '<__main__.Point object at 0x7fbfe954b9e8>')"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "repr(person), repr(point)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we can see, Python provides a default representation for objects that contains the class name, and the instance memory address.\n",
+ "\n",
+ "If we use `str()` instead, we get the same result:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('<__main__.Person object at 0x7fbfe954b860>',\n",
+ " '<__main__.Point object at 0x7fbfe954b9e8>')"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "str(person), str(point)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's go back to our original `Person` class and remove the `__repr__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name, age):\n",
+ " self.name = name\n",
+ " self.age = age\n",
+ " \n",
+ " def __str__(self):\n",
+ " print('__str__ called')\n",
+ " return self.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Python', 30)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "<__main__.Person at 0x7fbfe9569e48>"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'<__main__.Person object at 0x7fbfe9569e48>'"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "repr(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since we do not have a `__repr__` method, Python uses the \"default\" - it does not use our custom `__str__` method!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But if we use `print()` or `str()`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n",
+ "Python\n"
+ ]
+ }
+ ],
+ "source": [
+ "print(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Python'"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "str(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Lastly, various formatting functions will also prefer using the `__str__` method when available. Lert's first go back to our `Person` class that implements both:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name, age):\n",
+ " self.name = name\n",
+ " self.age = age\n",
+ " \n",
+ " def __repr__(self):\n",
+ " print('__repr__ called')\n",
+ " return f\"Person(name='{self.name}, age=self.age')\"\n",
+ " \n",
+ " def __str__(self):\n",
+ " print('__str__ called')\n",
+ " return self.name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Python', 30)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'The person is Python'"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "f'The person is {p}'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'The person is Python'"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'The person is {}'.format(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'The person is Python'"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "'The person is %s' % p"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/02 - Arithmetic Operators.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/02 - Arithmetic Operators.ipynb
new file mode 100644
index 00000000..95690987
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/02 - Arithmetic Operators.ipynb
@@ -0,0 +1,1528 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Arithmetic Operators"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's first look at some simple example of using the straightforward `__add__`, `__sub__`, etc."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's say we want to implement a `Vector` class that supports various arithmetic operations. We won't assume a specific number of dimensions - that will be determined by how many arguments are passed to the `__init__` method. We will however require the arguments to be Real numbers.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, let's support addition and subtraction of vectors - they'll need to be of the same dimension, othwerwise we should raise a `TypeError` exception (consistent with the exception Python raises if you try to add a string and an int for example)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's try out our class and see how things work at this point:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "v2 = Vector(10, 10)\n",
+ "v3 = Vector(1, 2, 3, 4)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Vector(1, 2)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Vector(11, 12)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 + v2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Vector(11, 12)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v2 + v1 "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unsupported operand type(s) for +: 'Vector' and 'Vector'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(v1 + v3)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unsupported operand type(s) for +: 'Vector' and 'int'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " print(v1 + 100)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, let's add support for multiplication by a scalar value - e.g. multipliying a vector by a real num ber (not another vector).\n",
+ "\n",
+ "To do that we'll implement the `__mul__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if not isinstance(other, Real):\n",
+ " return NotImplemented\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__mul__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Vector(10, 20)"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 * 10"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But what happens if we reverse the operation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unsupported operand type(s) for *: 'int' and 'Vector'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " 10 * v1\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happened here is that Python first tried calling the addition operation on the `int` object, using the `Vector` as the second operand. Integers of course do no support this type, so Python tried using our `Vector` class - but not the `__mul__` since that is called when the `Vector` is the **left** operand. Instead, it is looking for (and does not find) a method to use when the `Vector` is the **right** operand.\n",
+ "\n",
+ "We can implement this method, using `__rmul__`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if not isinstance(other, Real):\n",
+ " return NotImplemented\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__mul__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Vector(10, 20)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 * 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__rmul__ called...\n",
+ "__mul__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Vector(10, 20)"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "10 * v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, let's say we want to implement the dot product of two vectors.\n",
+ "\n",
+ "If you are rusty on this, just do a quick read of this: https://en.wikipedia.org/wiki/Dot_product\n",
+ "\n",
+ "Basically we need vectors of equal dimension, and we calculate the sum of the product of components (pairwise) in each vector.\n",
+ "\n",
+ "We can implement it by differentiating between a `Real` and ` Vector` type in our `__mul__` method - of course we won't need it in the `__rmul__` method because if we implement multiplication between two `Vectors` we'll always have a `Vector` as the left operand, so `__mul__` will get called first."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "v2 = Vector(3, 4)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__mul__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "11"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 * v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could also implement the **cross** product of two vectors (which would return another vector).\n",
+ "\n",
+ "The calculations get a little more complicated, so I won't show you those details, but let's see how we could use the `@` operator to implement this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other\n",
+ " \n",
+ " def __matmul__(self, other):\n",
+ " print('__matmul__ called...')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "v2 = Vector(3, 4)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__mul__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "11"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 * v2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__matmul__ called...\n"
+ ]
+ }
+ ],
+ "source": [
+ "v1 @ v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### In-Place Operators"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We also have the in-place operators. Typically in-place operators will try to **mutate** the object on the left of the expression:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l = [1, 2]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "140460867509512"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "id(l)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l += [3]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(140460867509512, [1, 2, 3])"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "id(l), l"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, the list `l` mas mutated (memory address remained the same). This is not the same effect as:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867621128\n",
+ "140460867592136 [1, 2, 3]\n"
+ ]
+ }
+ ],
+ "source": [
+ "l = [1, 2]\n",
+ "print(id(l))\n",
+ "\n",
+ "l = l + [3]\n",
+ "print(id(l), l)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, here we ended up with a **new** list object.\n",
+ "\n",
+ "But in-place does **not** *guarantee* a mutation. For example, tuples are immutable objects:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460615377736\n",
+ "140460867314816 (1, 2, 3)\n"
+ ]
+ }
+ ],
+ "source": [
+ "t = (1, 2)\n",
+ "print(id(t))\n",
+ "t += (3, )\n",
+ "print(id(t), t)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see we ended up with a new tuple. Same thing happens with strings, integers, floats and so on, that are also immutable types. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's go back to our `Vector` class and implement in-place addition - but we'll implement it in such a way that we do not mutate the Vector, instead just returning a new Vector - similar to what we just saw with tuples:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " print('__radd__ called...')\n",
+ " return self + other"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867485200\n",
+ "__radd__ called...\n",
+ "140460867485312 Vector(11, 12)\n"
+ ]
+ }
+ ],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "v2 = Vector(10, 10)\n",
+ "\n",
+ "print(id(v1))\n",
+ "\n",
+ "v1 += v2\n",
+ "\n",
+ "print(id(v1), v1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, we end up with a new `Vector` object.\n",
+ "\n",
+ "Now let's modify this so we actually mutate the `Vector` object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " print('__radd__ called...')\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " self._components = tuple(components) # mutating our Vector object\n",
+ " return self # don't forget to return the result of the operation!\n",
+ " return NotImplemented\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867518080\n",
+ "__radd__ called...\n",
+ "140460867518080 Vector(11, 22)\n"
+ ]
+ }
+ ],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "v2 = Vector(10, 20)\n",
+ "\n",
+ "print(id(v1))\n",
+ "\n",
+ "v1 += v2\n",
+ "\n",
+ "print(id(v1), v1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see we **mutated** the object `v1`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's also implement the unary minus on our `Vector` class. In this case we just want to return a new `Vector` with each component negated:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " print('__radd__ called...')\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " self._components = tuple(components) # mutating our Vector object\n",
+ " return self # don't forget to return the result of the operation!\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __neg__(self):\n",
+ " print('__neg__ called...')\n",
+ " components = (-x for x in self.components)\n",
+ " return Vector(*components)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__neg__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Vector(-1, -2)"
+ ]
+ },
+ "execution_count": 35,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 = Vector(1, 2)\n",
+ "-v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we can use it in arithmetic operations such as:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__neg__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "Vector(9, 8)"
+ ]
+ },
+ "execution_count": 36,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v2 = Vector(10, 10)\n",
+ "\n",
+ "v2 + -v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Lastly, let's implement the `abs` function for our Vector. Right now it won't work:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "bad operand type for abs(): 'Vector'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " abs(v1)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But we can fix that:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from numbers import Real\n",
+ "from math import sqrt\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, *components):\n",
+ " # validate number of components is at least one, and all of them are real numbers\n",
+ " if len(components) < 1:\n",
+ " raise ValueError('Cannot create an empty Vector.')\n",
+ " for component in components:\n",
+ " if not isinstance(component, Real):\n",
+ " raise ValueError(f'Vector components must all be real numbers - {component} is invalid.')\n",
+ " \n",
+ " # use immutable storage for vector\n",
+ " self._components = tuple(components)\n",
+ " \n",
+ " def __len__(self):\n",
+ " return len(self._components)\n",
+ " \n",
+ " @property\n",
+ " def components(self):\n",
+ " return self._components\n",
+ " \n",
+ " def __repr__(self):\n",
+ " # works - but unwieldy for high dimension vectors\n",
+ " return f'Vector{self._components}'\n",
+ " \n",
+ " def validate_type_and_dimension(self, v):\n",
+ " return isinstance(v, Vector) and len(v) == len(self)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if not self.validate_type_and_dimension(other):\n",
+ " return NotImplemented\n",
+ " components = (x - y for x, y in zip(self.components, other.components))\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " print('__mul__ called...')\n",
+ " if isinstance(other, Real):\n",
+ " components = (other * x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " # dot product\n",
+ " components = (x * y for x, y in zip(self.components, other.components))\n",
+ " return sum(components)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __rmul__(self, other):\n",
+ " print('__rmul__ called...')\n",
+ " # for us, multiplication is commutative, so we can leverage our existing __mul__ method\n",
+ " return self * other\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " print('__radd__ called...')\n",
+ " if self.validate_type_and_dimension(other):\n",
+ " components = (x + y for x, y in zip(self.components, other.components))\n",
+ " self._components = tuple(components) # mutating our Vector object\n",
+ " return self # don't forget to return the result of the operation!\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __neg__(self):\n",
+ " print('__neg__ called...')\n",
+ " components = (-x for x in self.components)\n",
+ " return Vector(*components)\n",
+ " \n",
+ " def __abs__(self):\n",
+ " print('__abs__ called...')\n",
+ " return sqrt(sum(x ** 2 for x in self.components))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__abs__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "1.4142135623730951"
+ ]
+ },
+ "execution_count": 40,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "abs(v1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Other Uses"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Of course, these arithmetic operators are not restricted to working with numbers. We've seen them work with strings as well for example, or lists even.\n",
+ "\n",
+ "We can also use them in our custom classes in different ways where we want to implement and attach special meaning to these operators.\n",
+ "\n",
+ "For example, we might have a `Family` class that holds together:\n",
+ "- mother and father `Person` objects\n",
+ "- a list of children `Person` objects\n",
+ "\n",
+ "We want to make it such that we can add children simply by using inplace addition."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f\"Person('{self.name}')\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person('John')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Family:\n",
+ " def __init__(self, mother, father):\n",
+ " self.mother = mother\n",
+ " self.father = father\n",
+ " self.children = []\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " self.children.append(other)\n",
+ " return self\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867516680\n"
+ ]
+ }
+ ],
+ "source": [
+ "f = Family(Person('Mary'), Person('John'))\n",
+ "print(id(f))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867516680\n",
+ "[Person('Eric')]\n"
+ ]
+ }
+ ],
+ "source": [
+ "f += Person('Eric')\n",
+ "print(id(f))\n",
+ "print(f.children)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140460867516680\n",
+ "[Person('Eric'), Person('Michael')]\n"
+ ]
+ }
+ ],
+ "source": [
+ "f += Person('Michael')\n",
+ "print(id(f))\n",
+ "print(f.children)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, don't feel restricted to using these operators for numerical use cases only."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/03 - Rich Comparisons.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/03 - Rich Comparisons.ipynb
new file mode 100644
index 00000000..77559e6c
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/03 - Rich Comparisons.ipynb
@@ -0,0 +1,922 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Rich Comparisons"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is quite staightforward. We can choose to implement any number of these rich comparison operators in our classes.\n",
+ "\n",
+ "Furthermore, if one comparison does not exist, Python will try to the reverse the operands and the operator (and unlike the arithmetic operators, both operands can be of the same type).\n",
+ "\n",
+ "Let's use a 2D `Vector` class to check this out:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "140301551452112 140301551452000\n"
+ ]
+ }
+ ],
+ "source": [
+ "v1 = Vector(0, 0)\n",
+ "v2 = Vector(0, 0)\n",
+ "print(id(v1), id(v2))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 == v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By default, Python will use `is` when we do not provide an implementation for `==`. In this case we have two different objects, so they do not compare `==`.\n",
+ "\n",
+ "Let's change that:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " if isinstance(other, Vector):\n",
+ " return self.x == other.x and self.y == other.y\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(1, 1)\n",
+ "v2 = Vector(1, 1)\n",
+ "v3 = Vector(10, 10)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(True, False)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 == v2, v1 is v2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 == v3"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could even support an equality comparison with other iterable types. Let's say we want to support equality comparisons with tuples:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return self.x == other.x and self.y == other.y\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(10, 11)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 == (10, 11)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In fact, although tuples do not implement equality against a `Vector`, it will still work because Python will reflect the operation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(10, 11) == v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can also implement the other rich comparison operators in the same way.\n",
+ "\n",
+ "Let's implement the `<` operator:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We'll consider a Vector to be less than another vector if it's length (Euclidean) is less than the other.\n",
+ "\n",
+ "We're actually going to make use of the `abs` function for this, so we'll define the `__abs__` method as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from math import sqrt\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return self.x == other.x and self.y == other.y\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __abs__(self):\n",
+ " return sqrt(self.x ** 2 + self.y ** 2)\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return abs(self) < abs(other)\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(0, 0)\n",
+ "v2 = Vector(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 < v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What's interesting is that `>` between two vectors will work as well:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v2 > v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happened is that since `__gt__` was not implemented, Python decided to reflect the operation, so instead of actually running this comparison:\n",
+ "\n",
+ "```v2 > v1```\n",
+ "\n",
+ "Python actually ran:\n",
+ "\n",
+ "```v1 < v2```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What about with tuples?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 < (1, 1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And the reverse?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "(1, 1) > v1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "That worked too. How about `<=`, since we have `,` and `==` defined, will Python be able to use both to come up with a result?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(Vector(x=0, y=0), Vector(x=1, y=1))"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1, v2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "'<=' not supported between instances of 'Vector' and 'Vector'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " v1 <= v2\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Nope - so we have to implement it ourselves. Let's do that:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from math import sqrt\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return self.x == other.x and self.y == other.y\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __abs__(self):\n",
+ " return sqrt(self.x ** 2 + self.y ** 2)\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return abs(self) < abs(other)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __le__(self, other):\n",
+ " return self == other or self < other"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(0, 0)\n",
+ "v2 = Vector(0, 0)\n",
+ "v3 = Vector(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 <= v2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 <= v3"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 <= (0.5, 0.5)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What about `>=`?"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 >= v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Again, Python was able to reverse the operation:\n",
+ "\n",
+ "```v1 >= v2```\n",
+ "\n",
+ "and run:\n",
+ "\n",
+ "```v2 <= v1```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We also have the `!=` operator:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 != v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "How did that work?\n",
+ "Well Python could not find a `__ne__` method, so it delegated to `__eq__` instead:\n",
+ "\n",
+ "```\n",
+ "not(v1 == v2)\n",
+ "```\n",
+ "\n",
+ "We can easily see this by adding a print statement to our `__eq__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from math import sqrt\n",
+ "\n",
+ "class Vector:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Vector(x={self.x}, y={self.y})'\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " print('__eq__ called...')\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return self.x == other.x and self.y == other.y\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __abs__(self):\n",
+ " return sqrt(self.x ** 2 + self.y ** 2)\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " if isinstance(other, tuple):\n",
+ " other = Vector(*other)\n",
+ " if isinstance(other, Vector):\n",
+ " return abs(self) < abs(other)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __le__(self, other):\n",
+ " return self == other or self < other"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "v1 = Vector(0, 0)\n",
+ "v2 = Vector(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__eq__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "v1 != v2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In many cases, we can derive most of the rich comparisons from just two base ones: the `__eq__` and one other one, maybe `__lt__`, or `__le__`, etc.\n",
+ "\n",
+ "For example, if `==` and `<` is defined, then:\n",
+ "- `a <= b` is `a == b or a < b`\n",
+ "- `a > b` is `b < a`\n",
+ "- `a >= b` is `a == b or b < a`\n",
+ "- `a != b` is `not(a == b)`\n",
+ "\n",
+ "On the other hand if we define `==` and `<=`, then:\n",
+ "- `a < b` is `a <= b and not(a == b)`\n",
+ "- `a >= b` is `b <= a`\n",
+ "- `a > b` is `b <= a and not(b == a)`\n",
+ "- `a != b` is `not(a == b)`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, instead of us defining all the various methods, we can use the `@total_ordering` decorator in the `functools` module, that will work with `__eq__` and **one** other rich comparison method, filling in all the gaps for us:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import total_ordering\n",
+ "\n",
+ "@total_ordering\n",
+ "class Number:\n",
+ " def __init__(self, x):\n",
+ " self.x = x\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " print('__eq__ called...')\n",
+ " if isinstance(other, Number):\n",
+ " return self.x == other.x\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " print('__lt__ called...')\n",
+ " if isinstance(other, Number):\n",
+ " return self.x < other.x\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = Number(1)\n",
+ "b = Number(2)\n",
+ "c = Number(1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__lt__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 32,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a < b"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__lt__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 33,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a <= b"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You'll notice that `__eq__` was not called - that's because `a < b` was True, and short-circuit evaluation. In this next example though, you'll see both methods are called:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__lt__ called...\n",
+ "__eq__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 34,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "a <= c"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "One thing I want to point out, according to the documentation the `__eq__` is not actually **required**. That's because as we saw earlier, all objects have a **default** implementation for `==` based on the memory address. That's usually not what we want, so we normally end up defining a custom `__eq__` implementation as well."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/04 - Hashing and Equality.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/04 - Hashing and Equality.ipynb
new file mode 100644
index 00000000..67cc8fe9
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/04 - Hashing and Equality.ipynb
@@ -0,0 +1,415 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Hashing and Equality"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By default, when we create a custom class, we inherit `__eq__` and `__hash__` from the `object` class."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['__class__',\n",
+ " '__delattr__',\n",
+ " '__dir__',\n",
+ " '__doc__',\n",
+ " '__eq__',\n",
+ " '__format__',\n",
+ " '__ge__',\n",
+ " '__getattribute__',\n",
+ " '__gt__',\n",
+ " '__hash__',\n",
+ " '__init__',\n",
+ " '__init_subclass__',\n",
+ " '__le__',\n",
+ " '__lt__',\n",
+ " '__ne__',\n",
+ " '__new__',\n",
+ " '__reduce__',\n",
+ " '__reduce_ex__',\n",
+ " '__repr__',\n",
+ " '__setattr__',\n",
+ " '__sizeof__',\n",
+ " '__str__',\n",
+ " '__subclasshook__']"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means that by default our custom classes produce hashable objects that can be used in mapping types such as dictionaries and sets."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person()\n",
+ "p2 = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(8779945178916, -9223363256909596903)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hash(p1), hash(p2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1 == p2"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "By default `__hash__` uses the object's identity, and `__eq__` will only evaluate to `True` if the two objects are the same objects (identity)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can override those default implementations ourselves. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we override the `__eq__` method, Python will automatically make our class unhashable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return isinstance(other, Person) and self.name == other.name\n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person('John')\n",
+ "p2 = Person('John')\n",
+ "p3 = Person('Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(True, False)"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p1 == p2, p1 == p3"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But now we have lost hashing:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unhashable type: 'Person'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " hash(p1)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is because two objects that compare equal should also have the same hash. However, Python's default is to use the object's identity. So if that were the case then `p1` and `p2` would be equal, but would not have the same hash.\n",
+ "\n",
+ "So Python sets the `__hash__` property to `None`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "NoneType"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p1.__hash__)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The downside to this is that we can no longer use instances of this class as keys in a dictionary or elements of a set:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "unhashable type: 'Person'\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " d = {p1: 'person 1'}\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can however provide our own override for `__hash__`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return isinstance(other, Person) and self.name == other.name\n",
+ " \n",
+ " def __hash__(self):\n",
+ " return hash(self.name)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We now have a `Person` class that supports equality based on the state of the class (the `name` in this instance) and is hashable too.\n",
+ "\n",
+ "We should also keep in mind that for this to work well in data structurfes such as dictionaries, what we use to create a hash of the class should remain immutable.\n",
+ "\n",
+ "So, a better approach would be to make the `name` property a read-only property:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self._name = name\n",
+ " \n",
+ " @property\n",
+ " def name(self):\n",
+ " return self._name\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " return isinstance(other, Person) and self.name == other.name\n",
+ " \n",
+ " def __hash__(self):\n",
+ " return hash(self.name)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now our Person instances can be used in sets and dictionaries (keys)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Person('Eric')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = {p1: 'Eric'}"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "{<__main__.Person at 0x7fc3d838f0f0>: 'Eric'}"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "s = {p1}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course since we now have equality defined in terms of the object state (and not the default of, essentially, the memory address), we can recover an element from a dictionary using different objects (identity wise) that have the same state (equality wise)."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/05 - Booleans.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/05 - Booleans.ipynb
new file mode 100644
index 00000000..c822af19
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/05 - Booleans.ipynb
@@ -0,0 +1,609 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Booleans"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we know every object in Python has an associated truth value. Empty container types are falsy, non-zero numbers are truthy, zero numbers are falsy, etc."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The way Python determines the truth value of our custom classes is to:\n",
+ "1. first look for an implementation of the `__bool__` method (which needs to return a boolean)\n",
+ "2. if not present, looks for `__len__` and will return `False` if that is `0`, and `True` otherwise\n",
+ "3. otherwise returns `True`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's look at some example which illustrate this behavior:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First let's not define anything, so our objects should always have a `True` associated truth value:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's implement the `__len__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyList:\n",
+ " def __init__(self, length):\n",
+ " self._length = length\n",
+ " \n",
+ " def __len__(self):\n",
+ " print('__len__ called')\n",
+ " return self._length"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "l1 = MyList(0) # so __len__ will return 0\n",
+ "l2 = MyList(10) # so __len__ will return 10"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__len__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(l1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__len__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(l2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So when we create custom iterables, as long as we have a `__len__` method implemented, we can actually skip implementing the `__bool__` method, and our class will remain consistent with other collection types behaviors (empty collections are falsy, otherwise truthy)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's implement the `__bool__` method though, just to see that if it is present it will get called instead of the `__len__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class MyList:\n",
+ " def __init__(self, length):\n",
+ " self._length = length\n",
+ " \n",
+ " def __len__(self):\n",
+ " print('__len__ called')\n",
+ " return self._length\n",
+ " \n",
+ " def __bool__(self):\n",
+ " print('__bool__ called')\n",
+ " return self._length > 0"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = MyList(0)\n",
+ "p2 = MyList(100)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__bool__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__bool__ called\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For classes that do not define `__len__` we may want to use the `__bool__` method. For example, consider a 2D `Point` class where we want to consider the origin point `(0,0)` falsy, and everything else truthy.\n",
+ "\n",
+ "By default, all instances of our `Point` class will be truthy (they have neither a `__len__` nor a `__bool__` method):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Point:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Point(0, 0)\n",
+ "p2 = Point(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(True, True)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1), bool(p2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now let's implement `__bool__` to get our desired functionality:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Point:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __bool__(self):\n",
+ " return self.x != 0 or self.y != 0"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Point(0, 0)\n",
+ "p2 = Point(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p2)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that with associated values, we could technically do something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1.x or p1.y)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p2.x or p2.y)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This works because any `0` number is falsy.\n",
+ "\n",
+ "So we might think we can use this approach instead of the explicit `!= 0` comparisons:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Point:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __bool__(self):\n",
+ " return self.x or self.y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Point(0, 0)\n",
+ "p2 = Point(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Then if we call `__bool__` directly:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(False, True)"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1.__bool__()), bool(p2.__bool__())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But it we try to use the `bool()` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__bool__ should return bool, returned int\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " bool(p1)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "we can see that we have an exception. Although we can work with truth values in most circumstances, Python insists that `__bool__` should return an actual boolean type."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we really wanted to, we could write:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Point:\n",
+ " def __init__(self, x, y):\n",
+ " self.x = x\n",
+ " self.y = y\n",
+ " \n",
+ " def __bool__(self):\n",
+ " return bool(self.x or self.y)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p1 = Point(0, 0)\n",
+ "p2 = Point(1, 1)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(False, True)"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "bool(p1), bool(p2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/06 - Callables.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/06 - Callables.ipynb
new file mode 100644
index 00000000..776622f3
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/06 - Callables.ipynb
@@ -0,0 +1,1530 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Making Objects Callable"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can make instances of our classes callables by implementing the `__call__` method."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's first see a simple example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __call__(self):\n",
+ " print('__call__ called...')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now we can use `p` as a callable too:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Person"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__call__ called...\n"
+ ]
+ }
+ ],
+ "source": [
+ "p()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is actually quite useful, and is widely used by Python itself."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example, the `functools` module has a `partial` function that we can use to create partial functions, like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import partial"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func(a, b, c):\n",
+ " return a, b, c"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can call this function with three arguments, but we could also create a partial function that essentially pre-sets some of the positional arguments:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "partial_func = partial(my_func, 10, 20)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now we can (indirectly) call `my_func` using `partial_func` using only an argument for `c`, with `a` and `b` pre-set to `10` and `20` respectively:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(10, 20, 30)"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "partial_func(30)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So I referred to `partial` as a function, but in reality it's just a callable (and this is why in Python we generally refer to things as callables, not just functions, because an object might be callable without being an actual function). In fact, we've seen this before with properties - these are callables, but they are not functions!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Back to `partial`, you'll notice that the `type` of `partial` is not a `function` at all!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "type"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(partial)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So the type is `type` which means `partial` is actually a class, not a function.\n",
+ "\n",
+ "We can easily re-create a simplified approximation of `partial` ourselves using the `__call__` method in a custom class."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Partial:\n",
+ " def __init__(self, func, *args):\n",
+ " self._func = func\n",
+ " self._args = args\n",
+ " \n",
+ " def __call__(self, *args):\n",
+ " return self._func(*self._args, *args)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "partial_func = Partial(my_func, 10, 20)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "__main__.Partial"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(partial_func)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(10, 20, 30)"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "partial_func(30)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Many such \"functions\" in Python are actually just general callables. The distinction is often not important."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is a built-in function in Python, `callable` that can be used to determine if an object is callable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "callable(print)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "callable(partial)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "callable(partial_func)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see our `Partial` class **instance** is callable, but the `Person` class instances will not be (the class itself is callable of course):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "callable(Person)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "callable(p)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Example: Cache with a cache-miss counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's take a look at another example. I want to implement a dictionary to act as a cache, but I also want to keep track of the cache misses so I can later evaluate if my caching strategy is effective or not."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The `defaultdict` class can be useful as a cache.\n",
+ "\n",
+ "Recall that I can specify a default callable to use when requesting a non-existent key from a `defaultdict`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from collections import defaultdict"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def default_value():\n",
+ " return 'N/A'"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = defaultdict(default_value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'N/A'"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d['a']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "dict_items([('a', 'N/A')])"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d.items()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, I want to use this `default_value` callable to keep track of the number of times it has been called - this will tell me how may times a non-existent key was requested from my `defaultdict`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "I could try to create a global counter, and use that in my `default_value` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "miss_counter = 0"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def default_value():\n",
+ " global miss_counter\n",
+ " miss_counter += 1\n",
+ " return 'N/A'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now we can use it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = defaultdict(default_value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'N/A'"
+ ]
+ },
+ "execution_count": 29,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "d['a'] = 1\n",
+ "d['a']\n",
+ "d['b']\n",
+ "d['c']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 30,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 30,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "miss_counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This works, but is not very good - the `default_value` function **relies** on us having a global `miss_counter` variable - if we don't have it our function won't work. Additionally we cannot use it to keep track of different cache instances since they would all use the same instance of `miss_counter`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 31,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del miss_counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 32,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "d = defaultdict(default_value)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 33,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "name 'miss_counter' is not defined\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " d['a']\n",
+ "except NameError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So nmaybe we can just pass in the counter (defined in our current scope) we want to use to the `default_value` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 34,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def default_value(counter):\n",
+ " counter += 1\n",
+ " return 'N/A'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But this **won't work**, because counter is now local to the function so the local `counter` will be incremented, not the `counter` from the outside scope."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Instead, we could use a class to maintain both a counter state, and return the default value for a cache miss:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 35,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class DefaultValue:\n",
+ " def __init__(self):\n",
+ " self.counter = 0\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " if isinstance(other, int):\n",
+ " self.counter += other\n",
+ " return self\n",
+ " raise ValueError('Can only increment with an integer value.')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we can use this class a a counter:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "default_value_1 = DefaultValue()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "default_value_1 += 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 38,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 38,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "default_value_1.counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So this works as a counter, but `default_value_1` is not callable, which is what we need to the `defaultdict`.\n",
+ "\n",
+ "So let's make it callable, and implement the behavior we need:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 39,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class DefaultValue:\n",
+ " def __init__(self):\n",
+ " self.counter = 0\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " if isinstance(other, int):\n",
+ " self.counter += other\n",
+ " return self\n",
+ " raise ValueError('Can only increment with an integer value.')\n",
+ " \n",
+ " def __call__(self):\n",
+ " self.counter += 1\n",
+ " return 'N/A'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now we can use this as our default callable for our default dicts:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def_1 = DefaultValue()\n",
+ "def_2 = DefaultValue()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 41,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "cache_1 = defaultdict(def_1)\n",
+ "cache_2 = defaultdict(def_2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "('N/A', 'N/A')"
+ ]
+ },
+ "execution_count": 42,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_1['a'], cache_1['b']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "def_1.counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'N/A'"
+ ]
+ },
+ "execution_count": 44,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_2['a']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 45,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "def_2.counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As one last little enhancement, I'm going to make the returned default value an instance attribute for more flexibility:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class DefaultValue:\n",
+ " def __init__(self, default_value):\n",
+ " self.default_value = default_value\n",
+ " self.counter = 0\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " if isinstance(other, int):\n",
+ " self.counter += other\n",
+ " return self\n",
+ " raise ValueError('Can only increment with an integer value.')\n",
+ " \n",
+ " def __call__(self):\n",
+ " self.counter += 1\n",
+ " return self.default_value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now we could use it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "cache_def_1 = DefaultValue(None)\n",
+ "cache_def_2 = DefaultValue(0)\n",
+ "\n",
+ "cache_1 = defaultdict(cache_def_1)\n",
+ "cache_2 = defaultdict(cache_def_2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(None, None, None)"
+ ]
+ },
+ "execution_count": 48,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_1['a'], cache_1['b'], cache_1['a']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_def_1.counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 50,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(0, 0, 0)"
+ ]
+ },
+ "execution_count": 50,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_2['a'], cache_2['b'], cache_2['c']"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "3"
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cache_def_2.counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So the `__call__` method can essentially be used to make **instances** of our classes callable.\n",
+ "\n",
+ "This is also very useful to create **decorator** classes.\n",
+ "\n",
+ "Often we just use closures to create decorators, but sometimes it is easier to use a class instead, or if we want our class to provide functionality beyond just being used as a decorator."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's look at an example."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Example: Profiling Functions"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For simplicity I will assume here that we only want to decorate functions defined at the module level. For creating a decorator that also works for methods (bound functions) we have to do a bit more work and will need to understand descriptors - more on descriptors later."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we want to easily be able to keep track of how many times our functions are called and how long they take to run on average."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although we could cretainly implement code directly inside our function to do this, it becomes repetitive if we need to do it for multiple functions - so a decorator is ideal for that.\n",
+ "\n",
+ "Let's look at how we can use a decorator class to keep track of how many times our function is called and also keep track of the time it takes to run on average."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We could certainly try a closure-based approach, maybe something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from time import perf_counter\n",
+ "from functools import wraps\n",
+ "\n",
+ "def profiler(fn):\n",
+ " counter = 0\n",
+ " total_elapsed = 0\n",
+ " avg_time = 0\n",
+ " \n",
+ " @wraps(fn)\n",
+ " def inner(*args, **kwargs):\n",
+ " nonlocal counter\n",
+ " nonlocal total_elapsed\n",
+ " nonlocal avg_time\n",
+ " counter += 1\n",
+ " start = perf_counter()\n",
+ " result = fn(*args, **kwargs)\n",
+ " end = perf_counter()\n",
+ " total_elapsed += (end - start)\n",
+ " avg_time = total_elapsed / counter\n",
+ " return result\n",
+ " \n",
+ " # we need to give a way to our users to look at the\n",
+ " # counter and avg_time values - spoiler: this won't work!\n",
+ " inner.counter = counter\n",
+ " inner.avg_time = avg_time\n",
+ " return inner"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, we added `counter` and `avg_time` as attributes to the `inner` function (the decorated function) - that works but looks a little weird - also notice that we calculate `avg_time` every time we call our decorated fuinction, even though the user may never request it - seems wasteful."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from time import sleep\n",
+ "import random\n",
+ "\n",
+ "random.seed(0)\n",
+ "\n",
+ "@profiler\n",
+ "def func1():\n",
+ " sleep(random.random())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(None, None)"
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func1(), func1()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "0"
+ ]
+ },
+ "execution_count": 55,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func1.counter"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hmm, that's weird - `counter` still shows zero. This is because we have to understand what we did in the decorator - we made `inner.counter` the value of `counter` **at the time the decorator function was called** - this is **not** the counter value that we keep updating!!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So instead we could try to fix it this way:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from time import perf_counter\n",
+ "from functools import wraps\n",
+ "\n",
+ "def profiler(fn):\n",
+ " _counter = 0\n",
+ " _total_elapsed = 0\n",
+ " _avg_time = 0\n",
+ " \n",
+ " @wraps(fn)\n",
+ " def inner(*args, **kwargs):\n",
+ " nonlocal _counter\n",
+ " nonlocal _total_elapsed\n",
+ " nonlocal _avg_time\n",
+ " _counter += 1\n",
+ " start = perf_counter()\n",
+ " result = fn(*args, **kwargs)\n",
+ " end = perf_counter()\n",
+ " _total_elapsed += (end - start)\n",
+ " return result\n",
+ " \n",
+ " # we need to give a way to our users to look at the\n",
+ " # counter and avg_time values - but we need to make sure\n",
+ " # it is using a cell reference!\n",
+ " def counter():\n",
+ " # this will now be a closure with a cell pointing to \n",
+ " # _counter\n",
+ " return _counter\n",
+ " \n",
+ " def avg_time():\n",
+ " return _total_elapsed / _counter\n",
+ " \n",
+ " inner.counter = counter\n",
+ " inner.avg_time = avg_time\n",
+ " return inner"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@profiler\n",
+ "def func1():\n",
+ " sleep(random.random())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(None, None)"
+ ]
+ },
+ "execution_count": 58,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func1(), func1()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 59,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 59,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func1.counter()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 60,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "0.3425700559746474"
+ ]
+ },
+ "execution_count": 60,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func1.avg_time()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so that works, but it's a little convoluted. In this case a decorator class will be much easier to write and read!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 61,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Profiler:\n",
+ " def __init__(self, fn):\n",
+ " self.counter = 0\n",
+ " self.total_elapsed = 0\n",
+ " self.fn = fn\n",
+ " \n",
+ " def __call__(self, *args, **kwargs):\n",
+ " self.counter += 1\n",
+ " start = perf_counter()\n",
+ " result = self.fn(*args, **kwargs)\n",
+ " end = perf_counter()\n",
+ " self.total_elapsed += (end - start)\n",
+ " return result\n",
+ " \n",
+ " @property\n",
+ " def avg_time(self):\n",
+ " return self.total_elapsed / self.counter\n",
+ " \n",
+ " "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So we can now use `Profiler` as a decorator!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 62,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@Profiler\n",
+ "def func_1(a, b):\n",
+ " sleep(random.random())\n",
+ " return (a, b)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 63,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(1, 2)"
+ ]
+ },
+ "execution_count": 63,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_1(1, 2)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 64,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 64,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_1.counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 65,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(2, 3)"
+ ]
+ },
+ "execution_count": 65,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_1(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 66,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 66,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_1.counter"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 67,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "0.46242688701022416"
+ ]
+ },
+ "execution_count": 67,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_1.avg_time"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course we can use it for other functions too:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 68,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "@Profiler\n",
+ "def func_2():\n",
+ " sleep(random.random())"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 69,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(None, None, None)"
+ ]
+ },
+ "execution_count": 69,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_2(), func_2(), func_2()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 70,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(3, 0.5231811150054758)"
+ ]
+ },
+ "execution_count": 70,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "func_2.counter, func_2.avg_time"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, it was much easier to implement this more complex decorator using a class and the `__call__` method than using a purely function approach. But of course, if the decorator is simple enough to implement using a functional approach, that's my preferred way of doing things! \n",
+ "\n",
+ "Just because I have a hammer does not mean everything is a nail!!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/07 - The __del__ Method.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/07 - The __del__ Method.ipynb
new file mode 100644
index 00000000..c1e32479
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/07 - The __del__ Method.ipynb
@@ -0,0 +1,781 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### The `__del__` Method"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The `__del__` method as we discussed in the lecture is called right before the object is about to be garbage collected. This is sometimes called the **finalizer**. It is sometimes referred to as the **destructor**, but that's not really accurate since that method does not destroy the object - that's the GC's responsibility - `__del__` just gets called prior to the GC destroying the object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although this method can be useful in some circumstances we need to be aware of some pitfalls:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "1. Using the `del` keyword does not call `__del__` directly - it just removes the symbol for wehatever namespace it is being deleted from and reduces the reference count by 1.\n",
+ "2. The `__del__` method is not called until the object is about to be destroyed - so using `del obj` decreases the ref count by 1, but if something else is referencing that object then `__del__` is **not** called.\n",
+ "3. Unhandled exceptions that occur in the `__del__` method are essentially ignored, and the exceptions are written to `sys.stderr`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It's actually pretty easy to have unwitting references to an object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's first write a small helper function to calculate the reference count for an object using it's memory address (which only works correctly if the object actually exists):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import ctypes\n",
+ "\n",
+ "def ref_count(address):\n",
+ " return ctypes.c_long.from_address(address).value"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's write a class that implements the `__del__` method:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Person({self.name})'\n",
+ " \n",
+ " def __del__(self):\n",
+ " print(f'__del__ called for {self}...')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's first see how the `__del__` gets called when we create then remove a reference to an instance in our global scope:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can now remove that reference from the symbol `p` to the instance either by using `del p` or even just setting `p` to `None`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__del__ called for Person(Alex)...\n"
+ ]
+ }
+ ],
+ "source": [
+ "p = None"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see the `__del__` was called.\n",
+ "\n",
+ "It works the same way with the `del` statement:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__del__ called for Person(Alex)...\n"
+ ]
+ }
+ ],
+ "source": [
+ "del p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's see how we might create an unwitting extra reference to the object.\n",
+ "\n",
+ "Let's implement a method that is going to create an exception:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name):\n",
+ " self.name = name\n",
+ " \n",
+ " def gen_ex(self):\n",
+ " raise ValueError('Something went bump...')\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Person({self.name})'\n",
+ " \n",
+ " def __del__(self):\n",
+ " print(f'__del__ called for {self}...')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person('Alex')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "At this point we have one reference to the object, the reference held by `p`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "1"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "p_id = id(p)\n",
+ "ref_count(p_id)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now let's make that exception happen and store the exception in a variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Something went bump...\n"
+ ]
+ }
+ ],
+ "source": [
+ "try:\n",
+ " p.gen_ex()\n",
+ "except ValueError as ex:\n",
+ " error = ex\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "ref_count(p_id)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see our reference count is now `2`. Why?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's look at the `error` variable:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['__cause__',\n",
+ " '__class__',\n",
+ " '__context__',\n",
+ " '__delattr__',\n",
+ " '__dict__',\n",
+ " '__dir__',\n",
+ " '__doc__',\n",
+ " '__eq__',\n",
+ " '__format__',\n",
+ " '__ge__',\n",
+ " '__getattribute__',\n",
+ " '__gt__',\n",
+ " '__hash__',\n",
+ " '__init__',\n",
+ " '__init_subclass__',\n",
+ " '__le__',\n",
+ " '__lt__',\n",
+ " '__ne__',\n",
+ " '__new__',\n",
+ " '__reduce__',\n",
+ " '__reduce_ex__',\n",
+ " '__repr__',\n",
+ " '__setattr__',\n",
+ " '__setstate__',\n",
+ " '__sizeof__',\n",
+ " '__str__',\n",
+ " '__subclasshook__',\n",
+ " '__suppress_context__',\n",
+ " '__traceback__',\n",
+ " 'args',\n",
+ " 'with_traceback']"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(error)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(error.__traceback__)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['__class__',\n",
+ " '__delattr__',\n",
+ " '__dir__',\n",
+ " '__doc__',\n",
+ " '__eq__',\n",
+ " '__format__',\n",
+ " '__ge__',\n",
+ " '__getattribute__',\n",
+ " '__gt__',\n",
+ " '__hash__',\n",
+ " '__init__',\n",
+ " '__init_subclass__',\n",
+ " '__le__',\n",
+ " '__lt__',\n",
+ " '__ne__',\n",
+ " '__new__',\n",
+ " '__reduce__',\n",
+ " '__reduce_ex__',\n",
+ " '__repr__',\n",
+ " '__setattr__',\n",
+ " '__sizeof__',\n",
+ " '__str__',\n",
+ " '__subclasshook__',\n",
+ " 'clear',\n",
+ " 'f_back',\n",
+ " 'f_builtins',\n",
+ " 'f_code',\n",
+ " 'f_globals',\n",
+ " 'f_lasti',\n",
+ " 'f_lineno',\n",
+ " 'f_locals',\n",
+ " 'f_trace']"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(error.__traceback__.tb_frame)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "p Person(Alex) 140665691193640 140665683500032\n"
+ ]
+ }
+ ],
+ "source": [
+ "for key, value in error.__traceback__.tb_frame.f_locals.copy().items():\n",
+ " if isinstance(value, Person):\n",
+ " print(key, value, id(value), id(key))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see the traceback contains a refererence to our object in it's dictionary - so we have a second reference to our object."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's check our reference count now, to make sure we did not inadvertently create even more references:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "2"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "ref_count(p_id)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now, even if we remove our reference to the object, we will still have something handing on to it, and the `__del__` method will not get called:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "del p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See! `__del__` was not called!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But now let's get rid of that exception we stored:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__del__ called for Person(Alex)...\n"
+ ]
+ }
+ ],
+ "source": [
+ "del error"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And now, as you can see, we finally had the `__del__` method called. (Note that depending on what you were doing in your notebook, you may not even see this call at all - which just means that something else is holding on to our object somewhere!)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For this reason it is rare for devs to use the `__del__` method for critical things like closing a file, or closing committing a transaction in a database, etc - instead use a context manager, and avoid using the `__del__` method."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Because you do not know when the `__del__` method is going to get called (unless you know exactly how your code might be creating references to the object), you could also get into a situation where other objects (like global objects) referenced in the `__del__` method will even still be around by the time `__del__` is called (it would get called when the module is destroyed, such as at program shutdown)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The last point to make about `__del__` is that any unhandled exceptions in the `__del__` method are essentially ignored by Python (although their output is sent to `sys.stderr`)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's see this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __del__(self):\n",
+ " raise ValueError('Something went bump...')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Exception ignored in: >\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 3, in __del__\n",
+ "ValueError: Something went bump...\n"
+ ]
+ }
+ ],
+ "source": [
+ "del p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What we are seeing here is actually the `stderr` output, which Jupyter redirects into our notebook."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import sys"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(,\n",
+ " )"
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "sys.stderr, sys.stdout"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What I'm going to do here is redirect `stderr` to a file instead, using a context manager:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class ErrToFile:\n",
+ " def __init__(self, fname):\n",
+ " self._fname = fname\n",
+ " self._current_stderr = sys.stderr\n",
+ " \n",
+ " def __enter__(self):\n",
+ " self._file = open(self._fname, 'w')\n",
+ " sys.stderr = self._file\n",
+ " \n",
+ " def __exit__(self, exc_type, exc_value, exc_tb):\n",
+ " sys.stderr = self._current_stderr\n",
+ " if self._file:\n",
+ " self._file.close()\n",
+ " return False"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "with ErrToFile('err.txt'):\n",
+ " del p"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, no exception was generated and our code continues to run happily along.\n",
+ "\n",
+ "But let's examine the contents of that file:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "['Exception ignored in: >\\n', 'Traceback (most recent call last):\\n', ' File \"\", line 3, in __del__\\n', 'ValueError: Something went bump...\\n']\n"
+ ]
+ }
+ ],
+ "source": [
+ "with open('err.txt') as f:\n",
+ " print(f.readlines())"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, as you can see the exception was silenced and the exception data was just sent to `stderr`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What this means is that you cannot trap exceptions that occur in the `__del__` method (from outside the `__del__` method to be exact):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "p was deleted (succesfully)\n",
+ "No exception seen!\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "Exception ignored in: >\n",
+ "Traceback (most recent call last):\n",
+ " File \"\", line 3, in __del__\n",
+ "ValueError: Something went bump...\n"
+ ]
+ }
+ ],
+ "source": [
+ "p = Person()\n",
+ "\n",
+ "try:\n",
+ " del p\n",
+ " print('p was deleted (succesfully)')\n",
+ "except ValueError as ex:\n",
+ " print('Exception caught!')\n",
+ "else:\n",
+ " print('No exception seen!')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Now all this does not mean you should just altogether avoid using the `__del__` method - you just need to be aware of its limitations, and be extra careful in your code with circular references or unintentional extra references to your objects.\n",
+ "Things get even dicier when using multi-threading, but that's beyond the scope of this course!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Personally I never use `__del__`. Instead I use context managers to manage releasing resources such as files, sockets, database connections, etc."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 04 - Polymorphism and Special Methods/08 - The __format__ Method.ipynb b/Part 4/Section 04 - Polymorphism and Special Methods/08 - The __format__ Method.ipynb
new file mode 100644
index 00000000..2ee8e208
--- /dev/null
+++ b/Part 4/Section 04 - Polymorphism and Special Methods/08 - The __format__ Method.ipynb
@@ -0,0 +1,318 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### The `__format__` Method"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We saw before the use of `__str__` and `__repr__`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However we have one more formatting function to look at!\n",
+ "\n",
+ "The `format()` function."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example we can use `format()` with a format specification for floats:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 0.1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'0.10000000000000000555'"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "format(a, '.20f')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or we can use it with a datetime object:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import datetime"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "now = datetime.utcnow()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "datetime.datetime(2019, 6, 13, 3, 43, 48, 904829)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "now"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "'Thu 2019-06-13 03:43 AM'"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "format(now, '%a %Y-%m-%d %I:%M %p')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We can implement support for format specifiers in our own classes by implementing the `__format__` method.\n",
+ "\n",
+ "This is actually quite complicated to do, so we usually delegate back to some other type's formatting.\n",
+ "\n",
+ "Just like with `__str__` and `__repr__`, `__format__` should return a string."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " def __init__(self, name, dob):\n",
+ " self.name = name\n",
+ " self.dob = dob\n",
+ " \n",
+ " def __repr__(self):\n",
+ " print('__repr__ called...')\n",
+ " return f'Person(name={self.name}, dob={self.dob.isoformat()})'\n",
+ " \n",
+ " def __str__(self):\n",
+ " print('__str__ called...')\n",
+ " return f'Person({self.name})'\n",
+ " \n",
+ " def __format__(self, date_format_spec):\n",
+ " print(f'__format__ called with {repr(date_format_spec)}...')\n",
+ " dob = format(self.dob, date_format_spec)\n",
+ " return f'Person(name={self.name}, dob={dob})'"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So now have:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from datetime import date\n",
+ "\n",
+ "p = Person('Alex', date(1900, 10, 20))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__str__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Person(Alex)'"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "str(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__repr__ called...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Person(name=Alex, dob=1900-10-20)'"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "repr(p)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__format__ called with '%B %d, %Y'...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Person(name=Alex, dob=October 20, 1900)'"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "format(p, '%B %d, %Y')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If we do not specify a format, then the `format` function will use an empty string:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "__format__ called with ''...\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Person(name=Alex, dob=1900-10-20)'"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "format(p)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 05 - Project 2/Project 2 - Solution.ipynb b/Part 4/Section 05 - Project 2/Project 2 - Solution.ipynb
new file mode 100644
index 00000000..d5390871
--- /dev/null
+++ b/Part 4/Section 05 - Project 2/Project 2 - Solution.ipynb
@@ -0,0 +1,540 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Project 2 - Solution"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import total_ordering\n",
+ "\n",
+ "@total_ordering\n",
+ "class Mod:\n",
+ " def __init__(self, value, modulus):\n",
+ " if not isinstance(modulus, int):\n",
+ " raise TypeError('Unsupported type for modulus')\n",
+ " if not isinstance(value, int):\n",
+ " raise TypeError('Unsupported type for value')\n",
+ " if modulus <= 0:\n",
+ " raise ValueError('Modulus must be positive')\n",
+ "\n",
+ " self._modulus = modulus\n",
+ " self._value = value % modulus # store residue as the value\n",
+ " \n",
+ " @property\n",
+ " def modulus(self):\n",
+ " return self._modulus\n",
+ " \n",
+ " @property\n",
+ " def value(self):\n",
+ " return self._value\n",
+ " \n",
+ " @value.setter\n",
+ " def value(self, value):\n",
+ " self._value = value\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Mod({self._value}, {self._modulus})'\n",
+ " \n",
+ " def __int__(self):\n",
+ " # calculates the value (residue)\n",
+ " return self.value\n",
+ "\n",
+ " def __eq__(self, other):\n",
+ " # calculates congruence (same equivalence class)\n",
+ " if isinstance(other, Mod):\n",
+ " if self.modulus != other.modulus:\n",
+ " return NotImplemented\n",
+ " else:\n",
+ " return self.value == other.value\n",
+ " elif isinstance(other, int):\n",
+ " return other % self.modulus == self.value\n",
+ " else:\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __hash__(self):\n",
+ " return hash((self.value, self.modulus))\n",
+ " \n",
+ " def __neg__(self):\n",
+ " return Mod(-self.value, self.modulus)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return Mod(self.value + other.value, self.modulus)\n",
+ " if isinstance(other, int):\n",
+ " return Mod(self.value + other, self.modulus)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " self.value = (self.value + other.value) % self.modulus\n",
+ " return self\n",
+ " elif isinstance(other, int):\n",
+ " self.value = (self.value + other) % self.modulus\n",
+ " return self\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return Mod(self.value - other.value, self.modulus)\n",
+ " if isinstance(other, int):\n",
+ " return Mod(self.value - other, self.modulus)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __isub__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " self.value = (self.value - other.value) % self.modulus\n",
+ " return self\n",
+ " if isinstance(other, int):\n",
+ " self.value = (self.value - other) % self.modulus\n",
+ " return self\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return Mod(self.value * other.value, self.modulus)\n",
+ " if isinstance(other, int):\n",
+ " return Mod(self.value * other, self.modulus)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __imul__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " self.value = (self.value * other.value) % self.modulus\n",
+ " return self\n",
+ " if isinstance(other, int):\n",
+ " self.value = (self.value * other) % self.modulus\n",
+ " return self\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __pow__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return Mod(self.value ** other.value, self.modulus)\n",
+ " if isinstance(other, int):\n",
+ " # use residue of other, to make computation potentially smaller\n",
+ " return Mod(self.value ** (other % self.modulus), self.modulus)\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __ipow__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " self.value = (self.value ** other.value) % self.modulus\n",
+ " return self\n",
+ " if isinstance(other, int):\n",
+ " # use residue of other, to make computation potentially smaller\n",
+ " self.value = (self.value ** (other % self.modulus)) % self.modulus\n",
+ " return self\n",
+ " return NotImplemented\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return self.value < other.value\n",
+ " if isinstance(other, int):\n",
+ " return self.value < other % self.modulus\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "You should test this class writing some unit tests!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so this class implementation seems to work, but I'm not happy about the amount of repetitive code we had to write (all those checks to make sure we either have a comparable Mod instance, and then either using the value of the Mod instance or the int depending on what was passed in).\n",
+ "\n",
+ "I really want to do something about that."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "First thing is I'm going to add a \"private\" method that will indicate whether two objects are compatible. Maybe something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def _is_compatible(self, other):\n",
+ " return isinstance(other, int) or (isinstance(other, Mod) and self.modulus == other.modulus)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But then I'm still left with which value do I use, `.value` or the `int` itself. So, I'm going to make that part of the compatibility check. \n",
+ "\n",
+ "Here, I'm going to use exceptions to indicate an incompatible type, otherwise I'll return the value we should use. \n",
+ "\n",
+ "Something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def _get_value(self, other):\n",
+ " if isinstance(other, int):\n",
+ " return other % self.modulus # return the residue\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulues:\n",
+ " return other.value\n",
+ " raise TypeError('Incompatible types.')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And then I can refactor my class accordingly. Also, even though we should technically return `NotImplemented` (to allow Python to use reflection), in this case the reflection is not going to be needed, so I'm just going to let the `TypeError` exception through.\n",
+ "\n",
+ "The only exception to this is for ordering - we **do** want Python to try to reflect a `<` if `>` is not implemented (although using `@total_ordering` means this does not really matter anyway)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import total_ordering\n",
+ "\n",
+ "@total_ordering\n",
+ "class Mod:\n",
+ " def __init__(self, value, modulus):\n",
+ " if not isinstance(modulus, int):\n",
+ " raise TypeError('Unsupported type for modulus')\n",
+ " if not isinstance(value, int):\n",
+ " raise TypeError('Unsupported type for value')\n",
+ " if modulus <= 0:\n",
+ " raise ValueError('Modulus must be positive')\n",
+ "\n",
+ " self._modulus = modulus\n",
+ " self._value = value % modulus # store residue as the value\n",
+ " \n",
+ " @property\n",
+ " def modulus(self):\n",
+ " return self._modulus\n",
+ " \n",
+ " @property\n",
+ " def value(self):\n",
+ " return self._value\n",
+ " \n",
+ " @value.setter\n",
+ " def value(self, value):\n",
+ " self._value = value\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Mod({self._value}, {self._modulus})'\n",
+ " \n",
+ " def __int__(self):\n",
+ " # calculates the value (residue)\n",
+ " return self.value\n",
+ "\n",
+ " def _get_value(self, other):\n",
+ " if isinstance(other, int):\n",
+ " return other % self.modulus # return the residue\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return other.value\n",
+ " raise TypeError('Incompatible types.')\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " # calculates congruence (same equivalence class)\n",
+ " other_value = self._get_value(other)\n",
+ " return other_value == self.value\n",
+ " \n",
+ " def __hash__(self):\n",
+ " return hash((self.value, self.modulus))\n",
+ " \n",
+ " def __neg__(self):\n",
+ " return Mod(-self.value, self.modulus)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " return Mod(self.value + other_value, self.modulus)\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " self.value = (self.value + other_value) % self.modulus\n",
+ " return self\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " return Mod(self.value - other_value, self.modulus)\n",
+ " \n",
+ " def __isub__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " self.value = (self.value - other_value) % self.modulus\n",
+ " return self\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " return Mod(self.value * other_value, self.modulus)\n",
+ " \n",
+ " def __imul__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " self.value = (self.value * other_value) % self.modulus\n",
+ " return self\n",
+ " \n",
+ " def __pow__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " return Mod(self.value ** other_value, self.modulus)\n",
+ " \n",
+ " def __ipow__(self, other):\n",
+ " other_value = self._get_value(other)\n",
+ " self.value = (self.value ** other_value) % self.modulus\n",
+ " return self\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " # here, raising a TypeError instead of returning NotImplemented\n",
+ " # would result in Python not trying the reflection - which we DO want\n",
+ " # although since we are using @total_ordering this does not really matter\n",
+ " try:\n",
+ " other_value = self._get_value(other)\n",
+ " return self.value < other_value\n",
+ " except TypeError:\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ok, so this is better, but there still quite a bit of repetitive code for the addition, subtraction, multiplcation and power operations - the only thing that changes there is which particular arithmetic operator we are delegating to."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, I'm going to use the `operator` module to simplify things even further."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import operator"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "6"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "operator.mul(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "5"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "operator.add(2, 3)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So, now I'm going to write a generic `_compute` that will perform the requested operation, and return either a new `Mod` object, or do the in-place calculation (I'll use an optional keyword-only arg for this).\n",
+ "\n",
+ "So, something like this:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def _perform_operation(self, other, op, *, in_place=False):\n",
+ " other_value = self._get_value(other)\n",
+ " new_value = op(self.value, other_value)\n",
+ " if in_place:\n",
+ " self.value = new_value % self.modulus\n",
+ " return self\n",
+ " else:\n",
+ " return Mod(new_value, self.modulus)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's add that to our class and refactor one more time:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from functools import total_ordering\n",
+ "\n",
+ "@total_ordering\n",
+ "class Mod:\n",
+ " def __init__(self, value, modulus):\n",
+ " if not isinstance(modulus, int):\n",
+ " raise TypeError('Unsupported type for modulus')\n",
+ " if not isinstance(value, int):\n",
+ " raise TypeError('Unsupported type for value')\n",
+ " if modulus <= 0:\n",
+ " raise ValueError('Modulus must be positive')\n",
+ "\n",
+ " self._modulus = modulus\n",
+ " self._value = value % modulus # store residue as the value\n",
+ " \n",
+ " @property\n",
+ " def modulus(self):\n",
+ " return self._modulus\n",
+ " \n",
+ " @property\n",
+ " def value(self):\n",
+ " return self._value\n",
+ " \n",
+ " @value.setter\n",
+ " def value(self, value):\n",
+ " self._value = value\n",
+ " \n",
+ " def __repr__(self):\n",
+ " return f'Mod({self._value}, {self._modulus})'\n",
+ " \n",
+ " def __int__(self):\n",
+ " # calculates the value (residue)\n",
+ " return self.value\n",
+ "\n",
+ " def _get_value(self, other):\n",
+ " if isinstance(other, int):\n",
+ " return other % self.modulus # return the residue\n",
+ " if isinstance(other, Mod) and self.modulus == other.modulus:\n",
+ " return other.value\n",
+ " raise TypeError('Incompatible types.')\n",
+ " \n",
+ " def _perform_operation(self, other, op, *, in_place=False):\n",
+ " other_value = self._get_value(other)\n",
+ " new_value = op(self.value, other_value)\n",
+ " if in_place:\n",
+ " self.value = new_value % self.modulus\n",
+ " return self\n",
+ " else:\n",
+ " return Mod(new_value, self.modulus)\n",
+ " \n",
+ " def __eq__(self, other):\n",
+ " # calculates congruence (same equivalence class)\n",
+ " other_value = self._get_value(other)\n",
+ " return other_value == self.value\n",
+ " \n",
+ " def __hash__(self):\n",
+ " return hash((self.value, self.modulus))\n",
+ " \n",
+ " def __neg__(self):\n",
+ " return Mod(-self.value, self.modulus)\n",
+ " \n",
+ " def __add__(self, other):\n",
+ " return self._perform_operation(other, operator.add)\n",
+ " \n",
+ " def __iadd__(self, other):\n",
+ " return self._perform_operation(other, operator.add, in_place=True)\n",
+ " \n",
+ " def __sub__(self, other):\n",
+ " return self._perform_operation(other, operator.sub)\n",
+ " \n",
+ " def __isub__(self, other):\n",
+ " return self._perform_operation(other, operator.sub, in_place=True)\n",
+ " \n",
+ " def __mul__(self, other):\n",
+ " return self._perform_operation(other, operator.mul)\n",
+ " \n",
+ " def __imul__(self, other):\n",
+ " return self._perform_operation(other, operator.mul, in_place=True)\n",
+ " \n",
+ " def __pow__(self, other):\n",
+ " return self._perform_operation(other, operator.pow)\n",
+ " \n",
+ " def __ipow__(self, other):\n",
+ " return self._perform_operation(other, operator.pow, in_place=True)\n",
+ " \n",
+ " def __lt__(self, other):\n",
+ " # here, raising a TypeError instead of returning NotImplemented\n",
+ " # would result in Python not trying the reflection - which we DO want\n",
+ " # although since we are using @total_ordering this does not really matter\n",
+ " try:\n",
+ " other_value = self._get_value(other)\n",
+ " return self.value < other_value\n",
+ " except TypeError:\n",
+ " return NotImplemented"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "OK, so if you had your unit tests set up, each refactor we did would only have needed re-running the unit tests to make sure we did not break anything!"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 06 - Single Inheritance/01 - Single Inheritance.ipynb b/Part 4/Section 06 - Single Inheritance/01 - Single Inheritance.ipynb
new file mode 100644
index 00000000..17b1b9fa
--- /dev/null
+++ b/Part 4/Section 06 - Single Inheritance/01 - Single Inheritance.ipynb
@@ -0,0 +1,500 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Single Inheritance"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For now we're just going to define classes that inherit from another class, but we aren't going to bother implementing any functionality or state for these classes.\n",
+ "\n",
+ "We just want to explore the relationships between objects created from classes that inherit from each other."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Shape:\n",
+ " pass\n",
+ "\n",
+ "class Ellipse(Shape):\n",
+ " pass\n",
+ "\n",
+ "class Circle(Ellipse):\n",
+ " pass\n",
+ "\n",
+ "class Polygon(Shape):\n",
+ " pass\n",
+ "\n",
+ "class Rectangle(Polygon):\n",
+ " pass\n",
+ "\n",
+ "class Square(Rectangle):\n",
+ " pass\n",
+ "\n",
+ "class Triangle(Polygon):\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see we created a single inheritance chain that looks something like this:\n",
+ "\n",
+ "```\n",
+ " Shape\n",
+ " Ellipse Polygon\n",
+ " \n",
+ " Circle Rectangle Triangle\n",
+ " Square\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It is important to understand that these **classes** are subclasses of each other - just remember that **subclass** contains the word **class** - so it defines a relationship between classes, not instances:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Ellipse, Shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But if we create instances of those two classes:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "issubclass() arg 1 must be a class\n"
+ ]
+ }
+ ],
+ "source": [
+ "s = Shape()\n",
+ "e = Ellipse()\n",
+ "try:\n",
+ " issubclass(e, s)\n",
+ "except TypeError as ex:\n",
+ " print(ex)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When we deal with instances of classes, we can instead use the `isinstance()` function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(e, Ellipse)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But, not only is `e` an instance of an `Ellipse`, since `Ellipse` IS-A `Shape`, i.e. `Ellipse` is a **subclass** of `Shape`, it tunrs out thet `e` is also considered an instance of `Shape`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(e, Shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Subclasses behave similarly in that a class may be a subclass of another class without being a **direct** subclass.\n",
+ "\n",
+ "In our example here, every class we defined is a subclass of `Shape` because the inheritance chains all go back up to the `Shape` class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Square, Shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And of course, the same works for instances when we look at `isinstance`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "sq = Square()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, Square)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, Rectangle)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, Polygon)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, Shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "But of course, a `Square` is not a subclass of `Ellipse` and `Square` instances are not instances of `Ellipse`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Square, Ellipse)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, Ellipse)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We'll come back to this later, but when we define a class in Python 3 that does not explicitly inherit from another class:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "it is actually implicitly inheriting from a class!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There is a class in Python called `object` - yes, it is a **class**, even though the name says `object` (but classes are objects - everything in Python is an object):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Person, object)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "p = Person()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(p, Person)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This means that our `Shape` class we created actually inherits from `object`, and therefore every other class we created also inherits from `object`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Square, object)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(sq, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "We'll look at the `object` class in the next lecture."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.6.7"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb b/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb
new file mode 100644
index 00000000..e73552eb
--- /dev/null
+++ b/Part 4/Section 06 - Single Inheritance/02 - The object Class.ipynb
@@ -0,0 +1,830 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### The `object` Class"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As we discussed earlier, `object` is a built-in Python **class**, and every class in Python inherits from that class."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "type"
+ ]
+ },
+ "execution_count": 1,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see the type of `object` is `type` - this means it is a class, just like `int`, `str`, `dict` are also classes (types):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(type, type, type)"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(int), type(str), type(dict)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When we create a class that does not explicitly inherit from anything, we are implicitly inheriting from `object`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Person:\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(Person, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And it's not just our custom classes that inherit from `object`, every type in Python does too:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(int, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Even modules, which are objects and instances of `module` are subclasses of `object`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "module"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(math)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So the `math` module is an instance of the `module` type:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "ty = type(math)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "type"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(ty)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(ty, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If you're wondering where the `module` type (class) lives, you can get a reference to it the way I did here, or you can look for it in the `types` module where you can it and the other built-in types."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import types"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['AsyncGeneratorType',\n",
+ " 'BuiltinFunctionType',\n",
+ " 'BuiltinMethodType',\n",
+ " 'CodeType',\n",
+ " 'CoroutineType',\n",
+ " 'DynamicClassAttribute',\n",
+ " 'FrameType',\n",
+ " 'FunctionType',\n",
+ " 'GeneratorType',\n",
+ " 'GetSetDescriptorType',\n",
+ " 'LambdaType',\n",
+ " 'MappingProxyType',\n",
+ " 'MemberDescriptorType',\n",
+ " 'MethodType',\n",
+ " 'ModuleType',\n",
+ " 'SimpleNamespace',\n",
+ " 'TracebackType',\n",
+ " '_GeneratorWrapper',\n",
+ " '__all__',\n",
+ " '__builtins__',\n",
+ " '__cached__',\n",
+ " '__doc__',\n",
+ " '__file__',\n",
+ " '__loader__',\n",
+ " '__name__',\n",
+ " '__package__',\n",
+ " '__spec__',\n",
+ " '_ag',\n",
+ " '_calculate_meta',\n",
+ " '_collections_abc',\n",
+ " '_functools',\n",
+ " 'coroutine',\n",
+ " 'new_class',\n",
+ " 'prepare_class']"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(types)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example, if we define a function:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def my_func():\n",
+ " pass"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "function"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "type(my_func)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "types.FunctionType is type(my_func)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And `FunctionType` inherits from `object`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "issubclass(types.FunctionType, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "and of course, instances of that type are therefore also instances of `object`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(my_func, object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "as well as being instances of `FunctionType`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "isinstance(my_func, types.FunctionType)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The `object` class implements a certain amount of base functionality.\n",
+ "\n",
+ "We can see some of them here:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "['__class__',\n",
+ " '__delattr__',\n",
+ " '__dir__',\n",
+ " '__doc__',\n",
+ " '__eq__',\n",
+ " '__format__',\n",
+ " '__ge__',\n",
+ " '__getattribute__',\n",
+ " '__gt__',\n",
+ " '__hash__',\n",
+ " '__init__',\n",
+ " '__init_subclass__',\n",
+ " '__le__',\n",
+ " '__lt__',\n",
+ " '__ne__',\n",
+ " '__new__',\n",
+ " '__reduce__',\n",
+ " '__reduce_ex__',\n",
+ " '__repr__',\n",
+ " '__setattr__',\n",
+ " '__sizeof__',\n",
+ " '__str__',\n",
+ " '__subclasshook__']"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "dir(object)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "So as you can see `object` implements methods such as `__eq__`, `__hash__`, `__repr__` and `__str__`."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's investigate some of those, starting with `__repr__` and `__str__`:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "o1 = object()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "' | | | | | |