<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valeria Aynbinder on Medium]]></title>
        <description><![CDATA[Stories by Valeria Aynbinder on Medium]]></description>
        <link>https://medium.com/@valeria.aynbinder.edu?source=rss-e81c9a5bca0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6cPtiK3lRFPsiL-c0wL3HA.jpeg</url>
            <title>Stories by Valeria Aynbinder on Medium</title>
            <link>https://medium.com/@valeria.aynbinder.edu?source=rss-e81c9a5bca0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:15:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valeria.aynbinder.edu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Google Colab — a tool every Python Developer and Data Scientist should add to their toolbox]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/google-colab-a-tool-every-python-developer-and-data-scientist-should-add-to-their-toolbox-186b01534402?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/186b01534402</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 12:19:14 GMT</pubDate>
            <atom:updated>2022-06-14T13:47:05.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Colab — a tool every Python Developer and Data Scientist should add to their toolbox</h3><h4>11 amazing features and usage tips + 2 bonus features.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2zaPVAuAzfDjWliHwhLOg.jpeg" /><figcaption>Credits to maxpixel.net</figcaption></figure><h3>What is Google Colab?</h3><blockquote><a href="https://colab.research.google.com/">Colaboratory</a>, or “Colab” for short, is a product from Google Research. Colab <strong>allows anybody to write and execute arbitrary python code through the browser</strong>, and is especially well suited to machine learning, data analysis and education.</blockquote><p><a href="https://colab.research.google.com/">Google Colab</a> is based on <a href="https://jupyter.org/try">Jupyter Notebook</a>, a web application for creating “computational documents” (according to Jupyter Notebook creators). In simple words, Jupyter Notebook allows you to write a kind of streamlined document (or notebook) that includes code snippets, outputs, texts, images and many more, but in addition to being able to read and write this beautifully formatted document, you can also execute its code parts and examine the inputs in the same document.</p><p>If you are unfamiliar with Jupyter Notebooks, please take a look at a <a href="https://jupyter.org/try-jupyter/retro/notebooks/?path=notebooks/Intro.ipynb">Jupyter Notebook example</a> (a picture is worth a thousand words…)</p><p>For those who are familiar with Jupyter Notebook, I would define Google Colab as: “hosted Jupyter Notebook on steroids” 💪</p><h4><a href="https://colab.research.google.com/">Google Colab</a> is a 🆓 web application that is available to you with you regular Google account (just like Google Drive or Gmail)</h4><h3>Use cases — when you should consider using Google Colab</h3><ul><li><strong>Educational</strong>: if you are new to Python, and you are looking for a quick start to follow some tutorial, or to write and try simple python code, Colab is a great option! All you need to do is to open your browser and start coding — no installations needed!</li><li><strong>Sandbox</strong>: even if you are an experienced developer, and you are working on a complex project, you may find Google Colab extremely useful if you just want to try unknown (and potentially heavy) packages without the need to install them on your local environment!</li><li><strong>Presentations / talks</strong>: if you need to give a talk on a topic that requires you to present and / or run Python code, Google Colab is your best friend! First of all, it allows you to write and run your code during your talk seamlessly, and in a very presentational way (check out my tips below).<br>In addition, if you happen to give some kind of hands-on session/course for corporate companies, you probably know what a headache 🤕 it is to convince them to install something on their company’s laptops. Now imagine what it takes to convince corporate IT to install all the stuff needed for one-day seminar in deep learning, for example. Installation requirements will probably include: python, pip, dozen of python packages, jupyter, etc… There is a great chance they will give up on your session rather than investing dozens of IT hours to install everything on personal laptops of 30 employees. <br>Since Colab allows running all the needed stuff for deep learning on the cloud using your browser and the only thing you need is Google account, I was able to conduct my courses easily in many big corporate companies (and their IT was happy and endlessly grateful)</li><li><strong>Data Science</strong>: if you are a data scientist, or if you are working on a personal project that involves data analysis and/or machine learning, not only will Google Colab provide you a convenient and interactive environment with all the most popular packages pre-installed, but it will also provide you with free GPU to train your models!</li></ul><h3>Main advantages</h3><ul><li><strong>No downloads or installations needed!</strong> <br>Really, not at all! Google Colab is based on Python 3 and comes with main data science, machine learning, deep learning, image processing and NLP packages pre-installed: <strong><em>numpy, pandas, sklearn, scipy, matplotlib, seaborn, tensorflow, pytorch, nltk, spacy, </em></strong>and many more are instantly available to you.</li><li><strong>You get compute resources available to you free of charge! <br></strong>The resources you get are as follows:<strong><br></strong>— 12 GB RAM<br> — 100GB of disk space<br> — GPU/TPU ❗️<br>Let’s admit, not many of us have GPU installed on their personal laptops, so if you are working with heavy models, an ability to use GPU is an incredibly important advantage!</li><li><strong>Collaboration </strong><br>Google Colab allows you to write code in an interactive and convenient way, share it with others and collaborate on it, just like if it was a regular document.</li></ul><h3>13 amazing features and usage tips</h3><p>1. <strong>Files upload / download</strong></p><p>Just click the folder 📁 icon on the left menu pane and you’ll get an access to current runtime session files, from here you can upload and download files as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kw5P5omsdjAPsG8sOeO4GQ.png" /></figure><p>After simple drag-and-drop you can access your uploaded files from the Python code as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfTYu8Z8fboaPMMHmpmOoA.png" /></figure><ul><li><em>** Note that all the uploaded files are only available as long as current session is active. After the session disconnects, all the files will be lost. Hence I suggest mounting your Google Drive to Colab. It will guarantee that all the files you are creating from your python code are safely stored in your drive.</em></li></ul><p><strong>2. Mounting your Google Drive</strong></p><p>Open the left-pane menu and click the Drive icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8qFG5MyTPWKyq5WYEnz1A.png" /></figure><p>Follow the instructions and authenticate your drive, and in 2 seconds all the files from your Google drive will be instantly and seamlessly available to your python code without the need to upload or download them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*167DqfBIZmJ4mhVpOR-xMA.png" /></figure><p><strong>3. Interactive tables for data analysis</strong></p><p>Interactive tables allow you to view / filter / sort your tabular data not only from code, but also using interactive user-friendly UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXV7nEP0ZyKkZOj5Kl4zPA.png" /></figure><p>Just click on the icon under the table, and you’ll get a full search, filter and sort functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0xWcOwCKRD0xYCjLmDVWw.png" /></figure><p><strong>4. Variable Inspector</strong></p><p>Give a try to Colab Variable Inspector (click the {x} icon in the left-pane menu). It displays all the variables currently defined in your notebook and allows you to examine them more closely. <br>The variables are automatically updated, added and removed as you execute your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeKwFZEm1lTIOLpQUNJWbw.png" /></figure><p><strong>5. Notebook collaboration with comments</strong></p><p>Comments are available for each code cell in Colab notebook, and the functionality is similar to this of a regular Google Doc. Great collaboration feature!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8oXG7z2xV3i41mVmss4MQ.png" /></figure><p><strong>6. Playground Mode 🤾‍♀</strong></p><p>In Playground Mode changes you make to the notebook will not be saved. Very useful for presentations and playing with the code! Access Playground mode from the upper menu:</p><p>File =&gt;Open in playground mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIZUYKRiUVDFNMERuVgl4Q.png" /></figure><p>Now you can safely play with your code without changing the original notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIdzZx92Ua3-MR0Q4huwDQ.png" /></figure><p><strong>7. Table of contents</strong></p><p>Use automatically created table of contents for your notebook, and you’ll never get lost as the notebook get longer and longer. Click on the upper icon in the left pane menu, and you’ll get a navigable table of contents for your notebook based on section and titles you wrote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfirnPvg9-Rochg_842uSQ.png" /></figure><p><strong>8. Forms</strong></p><p>Forms allow you to get inputs from users in an interactive and user-friendly way, store their input values in variables and continue working with these variables in your code. The input forms in your notebook will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OS-SXd3PF2F_tWIJNJtQzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLQHAVHThwsv9Jc6RbVCnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hf0-_RylCDpdUZf3eTCyyA.png" /></figure><p>The following code will create the first form presented above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZKuXpjvpziZDEu4JSrKRw.png" /></figure><p>Check out the <a href="https://colab.research.google.com/notebooks/forms.ipynb">official Forms Colab</a> for more options and code snippets.</p><p><strong>9. GitHub integration</strong></p><p>You can easily save all your notebooks to your GitHub account. In the upper menu navigate to File =&gt; Save a copy in GitHub, and after short authentication process you will be able to sync your Colab notebooks with your GitHub:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_EvJLT3IwjUolyajKlIzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQAtNT946EkTuC9aLLJDqQ.png" /></figure><p><strong>10. Running regular terminal commands</strong></p><p>If you need to run an old good terminal command like ls, or cp, or pip install, or whatnot, you can do it just from a regular cell code, appending exclamation mark <strong>!</strong> before the command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qp1NnHzOZWTX8oVCta7-oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YopEiw6r3kJWTqjeK_BRlA.png" /></figure><p><strong>11. Commands Palette</strong></p><p>There are many more great features and options in Google Colab. Check them out in Commands Palette.</p><p>In the top menu, go to: Tools =&gt;Commands Palette, and continue exploring!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*797k51ZGP1SLhJr-oJfhYQ.png" /></figure><h3>2 Bous Google Colab Features are waiting for you</h3><p>Explore more features <a href="https://edulabs.co.il/p6-Google-Colab-a-must-have-tool-for-Developer-and-Data-Scientist.html">here</a></p><ul><li>How to use Magic commands</li><li>How to speed up all process with a FREE GPU</li></ul><p>I hope you found something new and useful in this article.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=186b01534402" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Regular Expressions —  cheat sheet]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/python-regular-expressions-cheat-sheet-cd0992c36f6f?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0992c36f6f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[regex]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 22:08:18 GMT</pubDate>
            <atom:updated>2022-06-15T09:48:04.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Regular Expressions — cheat sheet</h3><h4>Many code examples + useful tips. Bonus added to the end of the post.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqnV3n7n371wRQzkM3zljw.jpeg" /><figcaption>Credits to maxpixel.net</figcaption></figure><p>Regular expressions is an extremely useful tool, and like any developer, I use it a lot when working with texts. Since I always forget the syntax related to regular expressions, I thought creating a simple cheat sheet might help me and maybe others as well :)</p><h3>Python’s re most useful methods and differences between them</h3><p>Reminder: <strong>re</strong> module implements Regular Expressions functionality in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMzH2fXPwSySDQ2THkkFHA.png" /></figure><ul><li><strong>re.match</strong>: <em>matches</em> a regex pattern to the<strong> </strong><em>beginning</em><strong> </strong>of a string (returned: re.Match)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uivf801YsgV4aehtmzGmGA.png" /></figure><ul><li><strong>re.fullmatch</strong>: <em>matches</em> a regex pattern to the<strong> </strong><em>whole</em><strong> </strong>string (returned: re.Match)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZmKg4EZkiX1zKGxW1kX_Q.png" /></figure><ul><li><strong>re.search:</strong> <em>searches</em> a string for the presence of a regex pattern (returned: re.Match )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRLybpyhrAhLCyT2297rrw.png" /></figure><ul><li><strong>re.sub:</strong> <em>substitutes</em> occurrences of a regex pattern found in a string, searches for the pattern like in re.search (returned: string)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybNpotsGSvgd-0Rel5JSVw.png" /></figure><ul><li><strong>re.findall</strong>: searches for <em>all</em> occurrences of a regex pattern in a string, searches for the pattern like in<strong> </strong>re.search (returned: list of strings)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqZ7m8mt_vCJ4CFOly7fCw.png" /></figure><ul><li><strong>re.split: </strong><em>splits</em> a string by the occurrences of a regex pattern (returned: list of strings). ❗️note the empty strings returned ❗️</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EN8wII5acO9PDPpkbxU6kw.png" /></figure><h3>Special meta-characters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCxFImZeC0g_H4-3gMeTUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFVMV1JGb8maS-q2H-wquw.png" /></figure><h3>Repetition meta-characters</h3><p>A table below summarizes the amount of matches of (greedy) repetitions <strong>re</strong> module performs for the preceding Regular Expression. Greedy means that <strong>re</strong> module will match as many repetitions as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*fvt5hSOevksC-EpP2j3bsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkZpm59spSxFDGXg7PQuBQ.png" /></figure><h3>Useful characters classes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLlijUoMDk-iHYslMvITkw.png" /></figure><h3>Extremely useful tip: grouping and groups extraction</h3><p>Grouping allows you not only to match text sequences inside strings but also to extract sub-sequences according to groups you define in a pattern.</p><p>You can define groups in a pattern by using round brackets — (), and you can extract the groups from the matched sequences by calling group() method on re.Match object.</p><p>For example, let’s say we want to match an email in a text, but we also want to easily extract the username, the domain, and the extension out of the email. So if we get the following text: “abc@gmail.com”, we want (1) to detect that this is an email (according to a pattern) and (2) to detect that the username in this email is “abc”, domain name is “gmail”, and the extension in “com”. First, let’s define a simple pattern that will detect this email. Note, I will use a simplified pattern that assumes that there are solely alphanumeric chars in each of the email component, which is not true in a real life, but it will work for our grouping example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1QqYFXNGjzLmJL5-s4GRA.png" /></figure><p>Now, I will add groups to the pattern. Technically, I will just add brackets around different parts of my pattern: username, domain, extension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHbPmTOHFh39RXomIPMt6g.png" /></figure><p>We are now ready to match our pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSNcwN9xbpHFOdPS-UTTkA.png" /></figure><p>And here comes the magic of groups! We can not only get the matched text, but also extract separate groups by group index as it has been defined in the pattern, just like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bn3iVyMkVHDF10GeQfRAyA.png" /></figure><p>Nice, ah?</p><p>By the way, group(0) will return string that represents the whole match. In our case: “your_name@gmail.com”</p><h3>Bonus</h3><p>Sometimes you want to play with all these methods and you need it quick, so we organized them in a Google Colab file which is extremely simple to play with. You can find the file on <a href="https://edulabs.co.il/p5-Python-Regular-Expressions-Cheat-Sheet.html">this page.</a></p><p>That’s all for now, folks. Happy programming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0992c36f6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Decorators — Deep Dive in 4 Parts (2/4)]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-2-4-74abde491fcd?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/74abde491fcd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-decorators]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 20:58:35 GMT</pubDate>
            <atom:updated>2022-03-16T21:25:34.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Decorators — Deep Dive in 4 Parts (2/4)</h3><h4>Decorators for functions that receive parameters and return values, decorators that receive arguments, decorators in classes + advanced exercises with solutions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QL-rz9HLKGMwSpV7cckkw.jpeg" /><figcaption>Credits to <a href="https://www.maxpixel.net/">https://www.maxpixel.net/</a></figcaption></figure><p>This is a 4 parts series:</p><ul><li><a href="https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-47c8a328f3fa">Part 1 : Intro + build your first decorator</a></li><li>Part 2 (current): Decorators for functions that receive parameters and return values, decorators that receive arguments, decorators in classes + advanced exercises with solutions</li><li>Part 3: Concatenating decorators (TBD)</li><li>Part 4: Property decorator (TBD)</li></ul><p>This article is Part 2 in series about Python Decorators, and it assumes you have basic knowledge in decorators. If you don’t, or if you haven’t read the first article in the series, feel free to do so <a href="https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-47c8a328f3fa">here.</a></p><p>In this article we will discuss implementing more advanced decorators, in particular:</p><ul><li>Implementing decorators for any function, including functions that receive parameters and return values</li><li>Implementing decorators that receive arguments by themselves (i.e. modifying decorators behavior)</li><li>Implementing decorators inside classes</li><li><strong>Exercises to improve your skills + solutions</strong></li></ul><p>If you prefer watching and listening, feel free to check out my video explaining these topics:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCUZqICabccw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCUZqICabccw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCUZqICabccw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d488e24fe1746d1f805b7039a4c960/href">https://medium.com/media/39d488e24fe1746d1f805b7039a4c960/href</a></iframe><h3>1. Recap</h3><p>Let’s start from a short recap of what decorator is and what we learned in a <a href="https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-47c8a328f3fa">previous part</a> of this series. Below is an implementation of a simple <strong><em>greeting_decorator</em></strong> that prints out beautiful messages before and after running the function it decorates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6db319b409ba22cb28553857ff64c52b/href">https://medium.com/media/6db319b409ba22cb28553857ff64c52b/href</a></iframe><p>Since we defined <strong><em>sum_of_digits</em></strong> decorated with <strong><em>greeting_decorator</em></strong>, the actual <strong><em>sum_of_digits</em></strong> that was stored by Python interpreter is a function returned by <strong><em>greeting_decorator</em></strong>. In other words, the actual code that was stored with identifier <strong><em>sum_of_digits</em></strong> is a return value of:</p><pre>greeting_decorator(sum_of_digits)</pre><p>Hence, when running the following line:</p><pre>sum_of_digits()</pre><p>Python interpreter executes decorator code, that in turn displays welcome and goodbye messages and executes the original <strong><em>sum_of_digits</em></strong> code, so the output for this line will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcQRe6PBqeO6ztvSgML1Lw.png" /></figure><p>You might noticed that I chose to implement <strong><em>sum_of_digits</em></strong> in a bit weird way: instead of passing a number as argument and returning the sum of its digits as return value, I intentionally chose to get a number as an input and print the result inside the function. It has been done to simplify the implementation of our decorator. But now, after we have basic knowledge in decorators, we can move further.</p><h3>2. Decorating functions that receive parameters and return values</h3><p>Let’s change our <strong><em>sum_of_digits</em></strong> function to a standard implementation that makes more sense. Now our function will receive a number as a parameter and return the sum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a62ee3b1e3f8a18e800b9ff5e8d96bdb/href">https://medium.com/media/a62ee3b1e3f8a18e800b9ff5e8d96bdb/href</a></iframe><p>If we’ll try running:</p><pre>sum_of_digits(235)</pre><p>with <strong><em>greeting_decorator</em></strong> left as is, we’ll get an exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaXLDUCqdGFy_BU5Z3PBpg.png" /></figure><p>It happens because our <strong><em>greeting_func</em></strong> implemented inside <strong><em>greeting_decorator</em></strong> indeed takes no arguments, and as we already know — what will really get called when running <strong><em>sum_of_digits(235)</em></strong>, is:</p><pre>greeting_decorator(sum_of_digits)(235)</pre><p>It means that we have to change <strong><em>greeting_func</em></strong> returned from <strong><em>greeting_decorator</em></strong> to get an argument and to return a value, as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/719cf95e9140b6182aa388afeed22cf0/href">https://medium.com/media/719cf95e9140b6182aa388afeed22cf0/href</a></iframe><p>Now, when calling:</p><pre>ret_sum = sum_of_digits(345)<br>print(f&quot;Sum of digits for 345 is: {ret_sum}&quot;)</pre><p>we will get an expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUOYYhcP14CieQuftAwiuA.png" /></figure><p>Though our <strong><em>greeting_decorator</em></strong> works as expected now, the way it handles function arguments is not generic enough. What will happen if we’ll try to use <strong><em>greeting_decorator</em></strong> for function that takes more than one argument? Or if the decorated function will include both required and keyword arguments? Or if the function takes no arguments? Of course, it will again raise an exception for all these cases, since now we require that the decorated function takes exactly one required argument.</p><p>Happily, in Python we can easily rewrite our decorator to support all the cases described above and even more, by using <a href="https://gist.github.com/valeria-aynbinder-edu/bb708f44f215bca78ee27d5cb2f0277b">*args and **kwargs </a>signature:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8936dede5680fba8f3d19983964d55d1/href">https://medium.com/media/8936dede5680fba8f3d19983964d55d1/href</a></iframe><p>Now, we can use our greeting_decorator with any function!</p><p><strong>To summarize: when implementing a decorator, you should work according to the following template:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3320c846ef14fb7528a7fa61f9f4deb/href">https://medium.com/media/d3320c846ef14fb7528a7fa61f9f4deb/href</a></iframe><p>Now it’s time for an exercise. I encourage you to try solving it by yourself 💪 before looking at my solution.</p><h4>Exercise 1: Implement a decorator that logs execution time of a function</h4><blockquote>Implement a decorator performance_log that prints amount of time (in seconds) that it takes to a function to complete execution. It can be very useful for debugging and profiling purposes.</blockquote><blockquote>Test your decorator with the functions provided below.</blockquote><blockquote>Hint: try using <a href="https://docs.python.org/3/library/time.html#time.perf_counter">time.perf_counter()</a> to measure time</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8578ba7a6ec3543eb463cb4d4a111319/href">https://medium.com/media/8578ba7a6ec3543eb463cb4d4a111319/href</a></iframe><p>Below are example outputs that you should get when calling <strong><em>long_running_func</em></strong> after you implement the decorator:</p><pre>res = long_running_func(17, 1000)<br>print(f&quot;The result is: {res}&quot;)</pre><p>Expected output:</p><pre>Execution time is: 0.00027704099989023234<br>The result is 281139182902740093173255193460516433570993900889613439277903794687196783510046951084......</pre><p><em>An optional solution for this exercise can be found </em><a href="https://gist.github.com/valeria-aynbinder-edu/8325c52963de33ae2132d3ee5c0f4c34"><em>here</em></a><em>, but I’m sure you don’t need it because you solved it by yourself</em> 😅</p><p>Spoiler alert⚠️: Next section is based on the decorator <strong><em>performance_log</em></strong></p><h3>3. Passing parameters to decorators</h3><p>After we implemented <strong><em>performance_log</em></strong> decorator that logs function execution time in seconds, we want to add more flexibility to it by allowing us to choose time unit we want to display execution time in: seconds, mili-seconds or nano-seconds! In other words, we want to implement <strong><em>performance_log</em></strong> decorator in a way that will allow us to pass it as a parameter one of: “s”, “ms”, “ns”, like this:</p><pre>@performance_log(time_units=&quot;ms&quot;)<br>def some_function():<br>    pass</pre><p>How can we achieve this? Let’s start from the original <strong><em>performance_log</em></strong> decorator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee635e4ffd7196ff352c96bdbb01ec85/href">https://medium.com/media/ee635e4ffd7196ff352c96bdbb01ec85/href</a></iframe><p>We know that when Python interpreter sees the following lines:</p><pre>@performance_log<br>def some_function():<br>    pass</pre><p>it does the following:</p><pre>some_function = performance_log(some_function)</pre><p>And it is expected that the return type of the line <strong><em>performance_log(some_function)</em></strong> will be a function that receives another function as parameter and returns a decorated function.</p><p>So now, similarly, we need to update our <strong><em>performance_log</em></strong> such that</p><pre>performance_log(some_function)(time_units=&quot;ms&quot;)</pre><p>will return a function (the same one as before). Let’s try implementing one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a3ed65170e318ecfa28bbfd7282012f/href">https://medium.com/media/1a3ed65170e318ecfa28bbfd7282012f/href</a></iframe><p>So far so good. We only need to add an implementation to this returned <strong><em>wrapper</em></strong> function. According to the requirement we mentioned above, this <strong><em>wrapper</em></strong> function should receive a function as parameter, and return its decorated function. Ok, let’s do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35595000073993fe3fb12a3c283ef697/href">https://medium.com/media/35595000073993fe3fb12a3c283ef697/href</a></iframe><p>We are almost there! It’s only left to complete the implementation of the actual decorator (it will be very similar to the original implementation, but will also take into account provided time_units parameter)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734bf26aefff92d6f22b0e5317062100/href">https://medium.com/media/734bf26aefff92d6f22b0e5317062100/href</a></iframe><p>As you probably noticed, implementing a decorator that is able to receive parameters required us to add another “layer” of function definition, but as long as you understand the process behind the scenes, you won’t experience any difficulties implementing stuff like this.</p><h3>4. Implementing decorators inside a class</h3><p>Until now we used to implement decorators as separate functions, but in fact it is possible and even recommended to implement them inside classes, especially if a decorator you implement is related to the code logic of the class.</p><p>Let’s look at the example. We have the following <strong><em>Bank</em></strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b9e8afb753eaa3f025e9a6a9d14de5/href">https://medium.com/media/74b9e8afb753eaa3f025e9a6a9d14de5/href</a></iframe><p>As you can see, it implements 3 main methods: <strong><em>withdraw()</em></strong>, <strong><em>deposit()</em></strong> and <strong><em>feedback()</em></strong>. The first two are critical, hence we want to make sure they are not called outside working hours of the bank. The <strong><em>feedback()</em></strong> method is not critical, hence it can be called anytime. We want to implement a decorator <strong><em>working_hours_only</em></strong> that will decorate critical methods that should be called only during working hours of the bank. Since this decorator is tightly coupled with our <strong><em>Bank</em></strong> class logic, and is actually an inseparable part of it, it makes sense to implement this decorator inside a class.</p><p>One ❗️ important ❗️technical detail you should remember when defining decorator inside a class is that decorator signature inside a class should not contain <strong>self</strong> parameter, since it’s not passed to the decorator by Python interpreter. And if you think about it, it totally makes sense. Why? Because defining class methods, including “replacing” original methods with decorated ones is happening during class definition stage, when there is no class instance present in the picture. You can think about decorators as of static methods defined inside a class. That’s why we don’t expect and don’t need <strong>self</strong> parameter passed there.</p><p>After we discussed implementing decorators inside a class, you are ready to implement this <strong><em>working_hours_only</em></strong> decorator.</p><h4>Exercise 2: Implement working_hours_only decorator inside Bank class</h4><blockquote>Implement decorator <strong>working_hours_only</strong> that validates that method is called during working hours only (Sun - Thu, 09:00 - 17:00). For example, calling <strong>feedback()</strong> method on Saturday should reach <strong>feedback()</strong> method and “Called feedback” should be printed out. Calling <strong>withdraw()</strong> method on Saturday should not reach actual <strong>withdraw() </strong>method and should raise an exception.</blockquote><p><a href="https://gist.github.com/valeria-aynbinder-edu/1c08ff03b64f1b45be319278d3a829fd"><em>Here</em></a><em> you can check out my solution for this exercise.</em></p><h4>Exercise 3: Change your implementation of working_hours_only decorator to receive bank working days and hours as parameters.</h4><p><em>I’m not publishing a solution for this exercise, but I encourage you to solve it and publish your own solutions in the comments. I’ll be happy to mention the best solution here including credits for the author </em>😄</p><p>I hope you enjoyed this article. The next one will be published soon, stay tuned and subscribe to my channel to get notified as soon as it comes out!</p><p>All the code in Google Colab can be found <a href="https://colab.research.google.com/drive/1Mz8GSM04K1fEz6TKTUe9qlpfiWZy1rAO?usp=sharing">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74abde491fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Decorators — Deep Dive in 4 Parts]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-47c8a328f3fa?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c8a328f3fa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[function]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 22:12:02 GMT</pubDate>
            <atom:updated>2022-03-16T21:24:53.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Decorators — Deep Dive in 4 Parts (1/4)</h3><h4>Intro + build your first decorator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*BUVa43CgZUiaMn2K.jpg" /></figure><p>This is a 4 parts series:</p><ul><li>Part 1 (current): Intro + build your first decorator</li><li><a href="https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-2-4-74abde491fcd">Part 2: Decorators for functions that receive parameters and return values, decorators that receive arguments, decorators in classes + advanced exercises with solutions</a></li><li>Part 3: Concatenating decorators (TBD)</li><li>Part 4: Property decorator (TBD)</li></ul><p>Decorator is a very special python creature that allows to change behavior of existing functions without changing their code. Yes-yes, you read it correctly — <strong>changing functions without changing their code</strong>. WOW! Let’s start our deep dive into this genius python feature.</p><p>In this part you will get familiar with decorators, you will learn what decorator is and how it works, and eventually you will implement your first decorator. On the way you will probably discover a thing or two about functions, consider it a bonus ☺</p><blockquote>Watch my video about Python Decorators with code examples for better understanding</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH9hUwWAilAg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH9hUwWAilAg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH9hUwWAilAg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d312c1b4f2eb837be08c1a4e957cdf/href">https://medium.com/media/69d312c1b4f2eb837be08c1a4e957cdf/href</a></iframe><h4>Motivating task</h4><p>Let’s start from a motivating task.</p><p>I’ve implemented a small python package <strong><em>various_functions.py</em></strong> with various useful functions: there are functions for factorial calculation, name capitalizing and temperature conversions. Each function receives an input from a user, performs some calculations, and prints out the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFUIgtLnRXucqRiFF1IDTA.png" /><figcaption>various_functions.py module</figcaption></figure><p>If we’ll run these functions we’ll get output as follows:</p><figure><img alt="calling functions with output" src="https://cdn-images-1.medium.com/max/1024/1*D4onRK9IqMqLusLBEJMfRg.png" /><figcaption>main.py — calling functions with output</figcaption></figure><p>Though this module works fine, I decided to update <strong>all</strong> of its functions in the following way: when a function starts running, it should first print a beautiful welcome message, then it should perform whatever it performs now, and in the end it should print some nice “good-bye&quot; message before returning.</p><p>The naïve way to perform this task would be changing the actual code of <strong>all</strong> the functions in the module, adding a great chunk of quite annoying work for the developer, as well as introducing a lot of code duplication in the module. And if this is not enough, next time I will add a new function to my module, I will have to remember adding all the messages as needed again.</p><p>Quite a mess.</p><p>But the good news are that python <strong>decorator </strong>solves this issue in an efficient and elegant way, just by adding one single line before each function we want to change. So defining my functions as follows will add the exact piece of messaging functionality we need (note the <strong>@greeting_decorator</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TPMVWIKOugyXTdU44UBnQ.png" /><figcaption>various_functions.py with decorators</figcaption></figure><p>Now, when running the same <strong><em>main.py</em></strong><em> </em>as before, the output will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfVBR-1_4jqBMYYohdzGQA.png" /><figcaption>main.py — calling functions after adding decorator</figcaption></figure><p>As you can see, adding this magic <strong>@greeting_decorator </strong>before every function definition did the job!</p><p>In this article you will learn what is this <strong>@greeting_decorator</strong>, how it works and how to implement one.</p><h4>Function object understanding</h4><p>Let’s start from a deeper understanding of function object. Yes, I’m talking about the old good function like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4LM66OA9VR1t_pBBrt_BXg.png" /><figcaption>greet function definition</figcaption></figure><p>Let’s discuss some properties of function objects.</p><p><strong>Function can be called</strong><br>The most straightforward usage of a function is of course calling it, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY0fCCnAUXrcst9nyxBLAg.png" /><figcaption>calling greet function + output</figcaption></figure><p><em>Note that function call is executed when you provide round brackets after the function identifier: </em><strong><em>greet()</em></strong></p><p><strong>Function is a regular python object</strong><br>In addition to actually calling the function and running it’s code, we can also access the function object itself, print it, check it’s type, and even access it’s unique properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlEcWfC45r7ItUKZPnrajg.png" /><figcaption>printing greet function attributes</figcaption></figure><p><em>Note that when we access function as an object, we do not put round brackets </em><strong><em>()</em></strong><em> after the function identifier! Also note some useful function attributes used in the snippet above.</em></p><p><strong>Function can be passed as a parameter</strong><br>Since function is a regular object, it can be passed as a parameter to another function, like any other object. The following code snippet demonstrates this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boX3bYzk1kJRqPxZmy8FbA.png" /><figcaption>passing greet function as parameter to wrapper function</figcaption></figure><p><em>Here we define a new function </em><strong><em>wrapper </em></strong><em>that receives as parameter another function </em><strong><em>other_function</em></strong><em> and calls this </em><strong><em>other_function</em></strong><em> (which is actually our </em><strong><em>greet</em></strong><em> function - hence you see “Hello All!” displayed)!</em></p><p><strong>Function can create another function and return it.</strong></p><p>Only one step left before we implement our first decorator. Since we saw that function is actually a regular python object, it can be defined inside a function (just like you define any other variable inside a function). And in addition, function that has been defined inside another function can also be returned from that function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAjsaTZqREFndkIiQl4XNA.png" /><figcaption>display_quote is defined inside create_quote and returned</figcaption></figure><p><em>In the code snipped above we define an “internal” function </em><strong><em>display_quote</em></strong><em> inside a function </em><strong><em>create_quote</em></strong><em>. After its creation, </em><strong><em>display_quote</em></strong><em> function is returned to the caller.</em></p><p>So, <strong><em>create_quote</em></strong> is a function that receives no parameters and returns a function that displays a very nice quote. Examine the code snippet below and note that return value of <strong><em>create_quote</em></strong> is function! Also note that calling <strong><em>create_quote</em></strong> <strong>does not</strong> print the quote, it only <strong>creates a function</strong> that will print the quote the moment it will be called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0wZlFNvrugfPC5ZoGOGXg.png" /><figcaption>object returned from create_quote() is a function</figcaption></figure><p>Now, since <strong><em>created_function</em></strong> variable is a <strong><em>function</em></strong> object (that knows how to print a nice quote once its called), we can call it, and the output will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16REryOV5WQqE_sKqti9vg.png" /><figcaption>Calling create_function that has been returned from create_quote function</figcaption></figure><p>OK, now you are ready to implement your first python decorator! In fact we will implement <strong>greeting_decorator</strong> that you saw in our motivating example.</p><h4>Decorator implementation</h4><p>So what is decorator? Decorator is a function that receives as parameter another function. Then decorator defines an inner function that performs various actions, among which it calls the function that has been received as a parameter. Then the inner function is returned to the caller.</p><p>In order to implement the logic for our motivating example, we need to create some kind of “wrapper” function that will receive as parameter one of our original functions and will perform the following:</p><ol><li>Print Welcome message</li><li>Call the original function</li><li>Print Good-Bye message</li></ol><p>After we have this new “wrapper” function created, we would like to replace the original function with the new “wrapper” function, such that not the original, but the “wrapper” function will be called when needed. In this way, instead of running our original function (that does not display welcome and good-bye messages), we will run an enriched “wrapper” function that not only runs the original code, but also prints beautiful messaging at the beginning and in the end.</p><p>Decorator is a function which task is to create this “wrapper” function and return in to the caller (python interpreter), that in turn will replace the definition of the original function with the “wrapper” function definition returned from the decorator.</p><p>So our <strong><em>greeting_decorator</em></strong> will be defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N62FvXye0ZjXonp_w8gsgg.png" /><figcaption>greeting_decorator definition</figcaption></figure><p><em>As you can see, </em><strong><em>greeting_decorator</em></strong><em> creates a function </em><strong><em>wrapper_func</em></strong><em> that performs 3 steps discussed above. After definition, </em><strong><em>wrapper_func</em></strong><em> is returned from the </em><strong><em>greeting_decorator</em></strong><em>.</em></p><p>Then, in order to use this decorator you can decorate any function with our <strong><em>greeting_decorator</em></strong> like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UH8Wt1Px72kIkomRJr4bvA.png" /><figcaption>Decorating factorial function</figcaption></figure><p>This special <strong><em>@greeting_decorator</em></strong> syntax signals python interpreter that <strong><em>factorial </em></strong>identifier should be defined as follows:</p><pre># pseudo-code<br>factorial = greeting_decorator(factorial)</pre><p>So instead of storing <strong><em>factorial</em></strong> as an identifier that points to the code defined inside it, <strong><em>factorial</em></strong> is assigned to another function, our “wrapper” function that is returned by our <strong><em>greeting_decorator</em></strong>. And since <strong><em>factorial</em></strong> identifier now points to the “wrapper” function, each time <strong><em>factorial()</em></strong><em> </em>will be called, it will actually run our enriched code implemented in the “wrapper” function.</p><p>That’s why after decorating our <strong><em>factorial</em></strong> function with <strong><em>@greeting_decorator</em></strong>, the original <strong><em>factorial</em></strong> behavior will be changed so it will print messages before and after running the original <strong><em>factorial</em></strong> code.</p><p>Python decorator secrets are now revealed to you!</p><p>I hope now you have a better and deeper understanding of python decorators.</p><p>I encourage you to run code from this article by yourself to make sure everything is clear. You can take the code from my <a href="https://github.com/valeria-aynbinder-edu/video-lessons/tree/main/decorators_examples">GitHub</a> and <a href="https://colab.research.google.com/drive/1jLUaabe68P6SIeskAiz9yI5TkUOzfMOW?usp=sharing">Google Colab</a>.</p><p><a href="https://medium.com/@valeria.aynbinder.edu/python-decorators-deep-dive-in-4-parts-2-4-74abde491fcd"><strong>Continue learning Python decorators in part 2</strong></a></p><p>Subscribe to my channel to get notified when the following parts of this Decorators Deep Dive Series will be published (it will happen very soon).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c8a328f3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Manage Commands Cheat Sheet]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/django-manage-commands-cheat-sheet-45dffc4f3b1e?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/45dffc4f3b1e</guid>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Mon, 31 Jan 2022 21:07:53 GMT</pubDate>
            <atom:updated>2022-02-01T11:59:17.202Z</atom:updated>
            <content:encoded><![CDATA[<h4>A short cheat sheet for those who are familiar with Django, and need some reminder for useful Django commands</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IFJpinKLqDsG80zrzUzqg.jpeg" /></figure><h3>Installations</h3><p>In order to get started with Django, all you need to do is install Django package using pip:</p><pre>pip install django</pre><p>After the installation is complete, you can move forward and create your Django application.</p><h3>Django Application creation</h3><p>Creating a new Django web application consists of two stages:</p><p>First, you need to create a new Django project:</p><pre>django-admin startproject <strong><em>my_project</em></strong></pre><p><em>Note: </em><strong><em>my_project</em></strong><em> is a custom name for your project</em></p><p>After running this command, a new folder tree similar to the following will be created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*DAYdx_c8szDrdj-g--ikBg.png" /><figcaption>Project tree after running startproject</figcaption></figure><p>Second, you need to create a new Django application that will sit inside the newly created project. In order to do this, you need to change directory to <em>my_project</em> (the one where manage.py file resides):</p><pre>cd my_project<br>python manage.py startapp <strong><em>my_app</em></strong></pre><p><em>Note: </em><strong><em>my_app</em></strong><em> is a custom name for your application</em></p><p>After running this command your project tree will look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*hPF5R2JtOUHonhR_WJbjtA.png" /><figcaption>Project folder after running startapp command</figcaption></figure><h3>DB management</h3><h4>Create migration</h4><p><em>(this should be run after you make changes to your models.py):</em></p><pre>python manage.py makemigrations</pre><p>This command will result in creating a new migration file in your migrations folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*-26lugacyDM1m42vRToDbA.png" /><figcaption>Migration files inside migrations folder</figcaption></figure><h4>SQL Migrate</h4><p><em>(Review SQL queries that will actually run on your DB server during migrate)</em></p><pre>python manage.py sqlmigrate <strong><em>my_app</em></strong> <strong><em>0001</em></strong></pre><p><em>Note: </em><strong><em>my_app</em></strong><em> and </em><strong><em>0001</em></strong><em> are your app name and migration name respectively</em></p><h4>Migrate</h4><p><em>(this should be run when you want to apply changes in your migration files on your DB)</em></p><pre>python manage.py migrate</pre><h3>Other useful commands</h3><h4>Create superuser</h4><p><em>Use this command in order to create superuser that will allow you to login into Django Admin App</em></p><pre>python manage.py createsuperuser</pre><h4>Django Shell</h4><p><em>Use this command to start Django Shell with your application and models loaded (very useful when you want to play with Django models a bit)</em></p><pre>python manage.py shell</pre><p>Django has loaded your Django application for you, so now you can play with your Django models in Python shell!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utFFaH997b405rDybXsDZQ.png" /><figcaption>Playing with Django Models in Django Shell</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45dffc4f3b1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python set — a powerful collection every developer should use in 2022]]></title>
            <link>https://medium.com/@valeria.aynbinder.edu/python-set-a-powerful-collection-every-developer-should-use-in-2022-1591cc09caca?source=rss-e81c9a5bca0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1591cc09caca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[high-tech]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Valeria Aynbinder]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 17:36:02 GMT</pubDate>
            <atom:updated>2022-01-29T19:02:16.939Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python set — a powerful collection every developer should use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UQKo0WwOkSdylo70YEbFg.jpeg" /><figcaption>Python Set. Data set Intersection, Union, Difference.</figcaption></figure><h3>INTRO</h3><p>There are three basic python collections: <strong>list</strong>, <strong>dictionary</strong> and <strong>set</strong>. While <strong>list</strong> and <strong>dictionary</strong> are widely used in almost every piece of existing python code, <strong>set</strong> sometimes feels a bit underrated, though it shouldn’t!</p><p>Python<strong> set</strong> is an incredibly useful collection that allows you to write very efficient and beautiful code thanks to its special properties and functionalities.</p><p>If you master your knowledge in <strong>sets</strong>, it will significantly improve your code and shorten development time. So, let’s deep dive into <strong>python<em> </em>sets</strong> without further ado!</p><blockquote>Feel free to watch my video on <strong><em>python sets</em> </strong>with<strong> </strong>code examples for better understanding.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEHBpGKKihw8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEHBpGKKihw8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEHBpGKKihw8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2ba1d08e8b4b8de374f012ecbc703e9/href">https://medium.com/media/c2ba1d08e8b4b8de374f012ecbc703e9/href</a></iframe><p>Let’s start from a motivating task. How to get <strong>unique</strong> values from a <strong>list </strong>that might contain duplicates?</p><p>Well, using <strong>python<em> </em>set</strong> you can do it with a single line of code! Just create a <strong>set</strong> from the given <strong>list</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DMMQHP4r7POmfrdVSRQfQ.png" /><figcaption>How to create a python set from list.</figcaption></figure><p>Note that now our <em>unique_names</em> <strong>set</strong> does not contain duplicates. So what happened here? You just saw in action one of two main properties of <strong>set</strong>:</p><p><strong>Set elements are unique.</strong></p><p>This leads us to a short discussion about two main <strong>set</strong> properties.</p><h3>Set Properties</h3><p>Set implements two main properties that significantly distinguishes it from list:</p><ul><li><strong>Set elements are unique</strong></li><li><strong>Set elements are unordered.</strong></li></ul><p>At the first glance it might seem weird — why would someone use a collection that does not support order and does not allow duplicates when we have python <strong>list </strong>that does not have these limitations?</p><p>The answer is that these are actually not limitations, but important properties that save us from potential bugs and allow very special functionality.</p><p>Let me show you a couple of examples.</p><p><strong>Example 1.</strong> Let’s say you want to store all the cities that have ever hosted Olympic games 🏊 💃 🎿. It makes perfect sense to store these cities in set rather than in list.</p><ul><li>We want to make sure that even if some cities hosted olympics more than once since 1986, it will only appear once in our collection.</li><li>There is no sense in ordering these cities, it’s not that some cities are better than others 😅</li></ul><p><strong>Example 2.</strong> We want to store all the fruits that grow in Israel 🍊 🍋 🍏. The same principles apply here:</p><ul><li>We don’t want any duplicates in our fruits collection.</li><li>No special order should be presented here, it simply does not exist.</li></ul><p>Now let’s see the implementation of <strong>uniqueness</strong> and <strong>absence of order </strong>properties in action:</p><h4><strong>Uniqueness</strong></h4><p>In the following code snippet we have a <strong>list</strong> of rainy months in Israel from the last 3 years. Since there are some winter months when Israel usually gets some water from the sky, there are duplicates in the <em>rainy_months_list</em>.</p><p>If we want to get a unique set of rainfall months in Israel, the only thing we need to do is create a <strong>set</strong> and initialize it from <em>rainy_months_list.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqEISzueKzOSOL_1ABMKPw.png" /><figcaption>Python code to demonstrate uniqueness of elements in set</figcaption></figure><p>In addition to the fact that <strong>set</strong> automatically removes all the duplicates from the collection it has been initialized with, <strong>set</strong> also maintains the uniqueness of its elements and saves us from potential mistakes. In the following code snippet you see an attempt to add duplicate element to the <strong>set</strong>. After this attempt the <strong>set</strong> remains unchanged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-w50NfQq7UXjiadDtA56Rw.png" /><figcaption>Python code — it is impossible to add duplicates to set</figcaption></figure><p>After we saw <strong>set</strong> behavior that maintains its <strong>uniqueness</strong> property, let’s move forward to the second <strong>set</strong> property — its elements are <strong>unordered</strong>.</p><h4><strong>Absence of order</strong></h4><p>Since set elements don’t support any special ordering between them, it won’t make sense to try and access an element at specific index in set. Hence, an attempt to do so will raise an exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiL2GZGoY2eRYIBbFH_Vdw.png" /><figcaption>Python code — set does not support indexing</figcaption></figure><p>But, of course, we always can iterate set elements just like we can iterate over any collection, though the order of elements returned during iteration is not necessarily will be preserved, and can potentially be changed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-9uXfn6nBsjcLfpGF1PZg.png" /><figcaption>Python code — iteration over set</figcaption></figure><h3>Set special functionality</h3><p>After we saw <strong>set</strong> properties, let’s take a look at the powerful functionality <strong>python</strong> <strong>set</strong> implements:</p><ol><li>Intersection</li><li>Union</li><li>Difference</li></ol><p>If you are familiar with <a href="https://en.wikipedia.org/wiki/Set_theory">Set Theory</a>, these are the exact actions defined there. If you never heard about Set Theory, this diagram will help you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r71-PzZt6dgNLDSBjRyttQ.png" /><figcaption>Intersection, Union and Difference</figcaption></figure><p>Now let’s look at these operations in action with code examples.</p><p>First of all, we’ll create 3 <strong>sets</strong> to work with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbQ6hoOKlB1Cn-jkr2OWlg.png" /><figcaption>Create 3 sets. Python.</figcaption></figure><ul><li><em>weekdays</em> contains all the 7 existing weekdays</li><li><em>sport_days</em> describes days in which I do my workouts</li><li><em>lecture_days</em> are weekdays when I teach my students</li></ul><p>We are going to use <strong>set</strong> operations to get some insights from these three <strong>sets</strong>.</p><h4>Intersection</h4><p><em>What are the days in which I give lectures in the morning </em><strong><em>AND</em></strong><em> do my workouts in the evening?</em></p><p>To answer this question, we need to get elements that appear <strong>both</strong> in <em>sport_days</em> <strong>and</strong> <em>lecture_days</em>, i.e, we need to get an <strong>intersection</strong> of these two sets. Happily, we can do it with just one line of code using <em>intersection</em> method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A46Vc_5NqNdi6sq7uSyFA.png" /><figcaption>Intersection example. Python.</figcaption></figure><h4>Union</h4><p><em>On which days do I have something on my schedule, i.e, what are my busy days?</em></p><p>Well, these are the days that appear <strong>either</strong> in<em> sport_days</em> <strong>or</strong> in <em>lecture_days</em>, which is exactly the definition of <strong>union</strong>. Let’s store these days as <em>busy_days</em>. Happily, u<strong>nion</strong> method is also supported in <strong>set</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8z-WP-ukJ6FlPjdFIVKYuA.png" /><figcaption>Union example. Python.</figcaption></figure><h3><strong>Difference</strong></h3><p><em>I’m planning a short one-day hike with my friends. What are those days when I am totally free and have nothing on my schedule?</em></p><p>Probably by now you already see that these free days are exactly the <strong>difference</strong> between <em>weekdays</em> and <em>busy_days</em>. In other words, we are looking for days that <strong>appear</strong> in <em>weekdays</em>, but <strong>don’t appear</strong> in<em> busy_days</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkkgQTQ1NmXYgcmtC_6Aqg.png" /><figcaption>Difference example. Python.</figcaption></figure><h3>Epilog</h3><p>Congrats! You added a great tool into your Python toolbox!</p><p>Now it’s time for you to apply a knowledge you just acquired. Consider your latest python projects. Was there any data that had <strong>set</strong> properties, but have been implemented using <strong>lists</strong> or other collections? If so, try to rewrite your code to use <strong>set</strong> whenever is suitable.</p><p>You can find all the code presented here in my <a href="https://github.com/valeria-aynbinder-edu/video-lessons/tree/main/sets">github</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1591cc09caca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>