<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python</title>
	<atom:link href="https://renanmf.com/category/python/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Software development, machine learning</description>
	<lastBuildDate>Sun, 16 Apr 2023 18:11:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://renanmf.com/wp-content/uploads/2020/03/cropped-android-chrome-512x512-2-32x32.png</url>
	<title>Python</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Subtracting years from a date in Python</title>
		<link>https://renanmf.com/subtracting-years-from-a-date-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 15 Feb 2022 11:35:15 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=4070</guid>

					<description><![CDATA[<p>The easiest way to subtract years from a date in Python is to use the dateutil extension. Install it with pip: pip install python-dateutil The relativedelta object from the dateutil.relativedelta module allows you to subtract any number of years from a date object. In this example I always take the current date using the date.today() [&#8230;]</p>
<p>The content <a href="https://renanmf.com/subtracting-years-from-a-date-in-python/">Subtracting years from a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The easiest way to subtract years from a date in Python is to use the <a href="https://dateutil.readthedocs.io/en/stable/">dateutil</a> extension.</p>
<p>Install it with pip:</p>
<pre><code>pip install python-dateutil</code></pre>
<p>The <code>relativedelta</code> object from the <code> dateutil.relativedelta</code> module allows you to subtract any number of years from a date object.</p>
<p>In this example I always take the current date using the <code>date.today()</code> method.</p>
<p>Then I set a <code>relativedelta</code> of 2 years and subtract it from <code>current_date</code>.</p>
<pre><code class="language-python">from datetime import date
from dateutil.relativedelta import relativedelta

current_date = date.today()

print(current_date)

future_date = current_date - relativedelta(years=2)

print(future_date)</code></pre>
<pre><code>2022-02-15
2020-02-15</code></pre>
<p>You can also check:</p>
<ul>
<li><a href="https://renanmf.com/subtract-days-from-date-python/">How to subtract days from a date in Python</a> </li>
<li><a href="https://renanmf.com/adding-days-to-a-date-python/">Adding days to a date in Python</a></li>
</ul>
<h2>Watch this on Youtube</h2>
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/TJt60C1HBbg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe></p>
<p>The content <a href="https://renanmf.com/subtracting-years-from-a-date-in-python/">Subtracting years from a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Adding years to a date in Python</title>
		<link>https://renanmf.com/adding-years-to-a-date-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 15 Feb 2022 11:30:17 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=4055</guid>

					<description><![CDATA[<p>The easiest way to add years to a date in Python is to use the dateutil extension. Install it with pip: pip install python-dateutil The relativedelta object from the dateutil.relativedelta module allows you to add any number of years to a date object. In this example I always take the current date using the date.today() [&#8230;]</p>
<p>The content <a href="https://renanmf.com/adding-years-to-a-date-in-python/">Adding years to a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The easiest way to add years to a date in Python is to use the <a href="https://dateutil.readthedocs.io/en/stable/">dateutil</a> extension.</p>
<p>Install it with pip:</p>
<pre><code>pip install python-dateutil</code></pre>
<p>The <code>relativedelta</code> object from the <code> dateutil.relativedelta</code> module allows you to add any number of years to a date object.</p>
<p>In this example I always take the current date using the <code>date.today()</code> method.</p>
<p>Then I set a <code>relativedelta</code> of 2 years and add it to the <code>current_date</code>.</p>
<pre><code class="language-python">from datetime import date
from dateutil.relativedelta import relativedelta

current_date = date.today()

print(current_date)

future_date = current_date + relativedelta(years=2)

print(future_date)</code></pre>
<pre><code>2022-02-15
2024-02-15</code></pre>
<p>You can also check:</p>
<ul>
<li><a href="https://renanmf.com/subtract-days-from-date-python/">How to subtract days from a date in Python</a> </li>
<li><a href="https://renanmf.com/adding-days-to-a-date-python/">Adding days to a date in Python</a></li>
</ul>
<p>The content <a href="https://renanmf.com/adding-years-to-a-date-in-python/">Adding years to a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to subtract months from a date in Python</title>
		<link>https://renanmf.com/how-to-subtract-months-from-a-date-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 15 Feb 2022 11:25:32 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=4064</guid>

					<description><![CDATA[<p>The easiest way to subtract months from a date in Python is to use the dateutil extension. Install it with pip: pip install python-dateutil The relativedelta object from the dateutil.relativedelta module allows you to subtract any number of months from a date object. In this example I always take the current date using the date.today() [&#8230;]</p>
<p>The content <a href="https://renanmf.com/how-to-subtract-months-from-a-date-in-python/">How to subtract months from a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The easiest way to subtract months from a date in Python is to use the <a href="https://dateutil.readthedocs.io/en/stable/">dateutil</a> extension.</p>
<p>Install it with pip:</p>
<pre><code>pip install python-dateutil</code></pre>
<p>The <code>relativedelta</code> object from the <code> dateutil.relativedelta</code> module allows you to subtract any number of months from a date object.</p>
<p>In this example I always take the current date using the <code>date.today()</code> method.</p>
<p>Then I set a <code>relativedelta</code> of 2 months and subtract it from <code>current_date</code>.</p>
<pre><code class="language-python">from datetime import date
from dateutil.relativedelta import relativedelta

current_date = date.today()

print(current_date)

future_date = current_date - relativedelta(months=2)

print(future_date)</code></pre>
<pre><code>2022-02-15
2021-12-15</code></pre>
<p>You can also check:</p>
<ul>
<li><a href="https://renanmf.com/subtract-days-from-date-python/">How to subtract days from a date in Python</a> </li>
<li><a href="https://renanmf.com/adding-days-to-a-date-python/">Adding days to a date in Python</a></li>
</ul>
<p>The content <a href="https://renanmf.com/how-to-subtract-months-from-a-date-in-python/">How to subtract months from a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Adding months to a date in Python</title>
		<link>https://renanmf.com/adding-months-to-a-date-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 15 Feb 2022 11:18:41 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=4053</guid>

					<description><![CDATA[<p>The easiest way to add months to a date in Python is to use the dateutil extension. Install it with pip: pip install python-dateutil The relativedelta object from the dateutil.relativedelta module allows you to add any number of months to a date object. In this example I always take the current date using the date.today() [&#8230;]</p>
<p>The content <a href="https://renanmf.com/adding-months-to-a-date-in-python/">Adding months to a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The easiest way to add months to a date in Python is to use the <a href="https://dateutil.readthedocs.io/en/stable/">dateutil</a> extension.</p>
<p>Install it with pip:</p>
<pre><code>pip install python-dateutil</code></pre>
<p>The <code>relativedelta</code> object from the <code> dateutil.relativedelta</code> module allows you to add any number of months to a date object.</p>
<p>In this example I always take the current date using the <code>date.today()</code> method.</p>
<p>Then I set a <code>relativedelta</code> of 2 months and add it to the <code>current_date</code>.</p>
<pre><code class="language-python">from datetime import date
from dateutil.relativedelta import relativedelta

current_date = date.today()

print(current_date)

future_date = current_date + relativedelta(months=2)

print(future_date)</code></pre>
<pre><code>2022-02-15
2022-04-15</code></pre>
<p>You can also check:</p>
<ul>
<li><a href="https://renanmf.com/subtract-days-from-date-python/">How to subtract days from a date in Python</a> </li>
<li><a href="https://renanmf.com/adding-days-to-a-date-python/">Adding days to a date in Python</a></li>
</ul>
<p>The content <a href="https://renanmf.com/adding-months-to-a-date-in-python/">Adding months to a date in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python list drop duplicates</title>
		<link>https://renanmf.com/python-list-drop-duplicates/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Thu, 02 Dec 2021 14:38:33 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3934</guid>

					<description><![CDATA[<p>Removing duplicates from a list is a task that might happen more often than you think. Maybe you are importing a bunch of rows from a CSV file and want to make sure you only have unique values. Or you are making sure to avoid repeated values for the sake of keeping your data sanitized. [&#8230;]</p>
<p>The content <a href="https://renanmf.com/python-list-drop-duplicates/">Python list drop duplicates</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Removing duplicates from a list is a task that might happen more often than you think.</p>
<p>Maybe you are importing a bunch of rows from a CSV file and want to make sure you only have unique values.</p>
<p>Or you are making sure to avoid repeated values for the sake of keeping your data sanitized.</p>
<p>Fortunately, you can drop duplicates from a list in Python with a single line.</p>
<p>This is one of those simple, but powerful features that Python gives us for free and can save you a lot of trouble by applying the Pythonic way of doing things.</p>
<h2>Removing duplicates with set</h2>
<p>In the code snippet below we are creating a list named <code>car_brands</code>.</p>
<p>Notice how <code>&#039;bmw&#039;</code> and <code>&#039;toyota&#039;</code> are repeated.</p>
<p><code>&#039;bmw&#039;</code> is included twice, while <code>&#039;toyota&#039;</code>  appears three times.</p>
<p>To drop these duplicates we just need to convert the list to a set and then convert the result back to a list.</p>
<pre><code class="language-python">car_brands = [&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;, &#039;toyota&#039;, &#039;bmw&#039;, &#039;toyota&#039;]

print(car_brands)

car_brands = list(set(car_brands))

print(car_brands)</code></pre>
<p>The output of the code above is:</p>
<pre><code>[&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;, &#039;toyota&#039;, &#039;bmw&#039;, &#039;toyota&#039;]

[&#039;toyota&#039;, &#039;mercedes&#039;, &#039;bmw&#039;, &#039;mclaren&#039;]</code></pre>
<p>This works because sets, by default, don&#8217;t allow duplicates, so converting the list to set will automatically remove the duplicates.</p>
<p>But there is a catch, sets don&#8217;t keep the order of your items, while lists do keep the order of the items</p>
<p>Notice how <code>&#039;toyota&#039;</code> appears as the first item in the final result, even though it was the third in the original list.</p>
<p>So, what to do if I want to remove the duplicates but keep the order of the items?</p>
<h2>Droping duplicates and keeping the order with dict</h2>
<p>The simple and &quot;straightforward&quot; (but not recommended) way would be to loop of the original list and add only new items to a new list.</p>
<p>The code below implements such logic.</p>
<pre><code class="language-python">car_brands = [&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;, &#039;toyota&#039;, &#039;bmw&#039;, &#039;toyota&#039;]
new_brands = []

for item in car_brands: 
    if item not in new_brands: 
        new_brands.append(item)

print(car_brands)
print(new_brands)</code></pre>
<p>The output is:</p>
<pre><code>[&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;, &#039;toyota&#039;, &#039;bmw&#039;, &#039;toyota&#039;]

[&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;]</code></pre>
<p>But, as always, there is a better way in Python!</p>
<p>As of Python 3.6, you can use the method <code>fromkeys</code> from <code>dict</code>.</p>
<p>It is slower than using sets to remove duplicates, but it is the best solution to drop duplicates <em>and</em> keep order.</p>
<p>It also takes only one line.</p>
<pre><code class="language-python">car_brands = [&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;, &#039;toyota&#039;, &#039;bmw&#039;, &#039;toyota&#039;]

car_brands = list(dict.fromkeys(car_brands))

print(car_brands)</code></pre>
<p>The output of the above is:</p>
<pre><code>[&#039;bmw&#039;, &#039;mercedes&#039;, &#039;toyota&#039;, &#039;mclaren&#039;]</code></pre>
<p>Since the solution with <code>dict</code> is slower, only use it if order is something you really need.</p>
<p>I recommend you to read <a href="https://renanmf.com/how-to-choose-data-structure-python/">How to choose a Data Structure in Python</a> to have a broad view of each one and when to use them.</p>
<p>The content <a href="https://renanmf.com/python-list-drop-duplicates/">Python list drop duplicates</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python for loop increment by 2</title>
		<link>https://renanmf.com/python-for-loop-increment-by-2/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Sun, 31 Oct 2021 20:40:08 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3906</guid>

					<description><![CDATA[<p>A regular for loop will increase its iteration counter by one in each iteration. But there are situations where you want to increment the iteration counter by 2. For some reason you might want to work with only even values. Let&#8217;s see a few solutions for this. range function The solution to increment a for [&#8230;]</p>
<p>The content <a href="https://renanmf.com/python-for-loop-increment-by-2/">Python for loop increment by 2</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>A regular <code>for</code> loop will increase its iteration counter by one in each iteration.</p>
<p>But there are situations where you want to increment the iteration counter by 2.</p>
<p>For some reason you might want to work with only even values.</p>
<p>Let&#8217;s see a few solutions for this.</p>
<h2>range function</h2>
<p>The solution to increment a for loop by 2 in Python is to use the <code>range()</code> function.</p>
<p>This function allows you to specify three parameters: <code>start</code>, <code>stop</code>, and <code>step</code>.</p>
<p><code>start</code> is the counter&#8217;s initial value, <code>step</code> is by how much you want to increment until you reach the value of <code>stop - 1</code>, because the value of stop is included.</p>
<p>The example bellow shows how to use <code>range()</code> with a step of 2 starting from 0.</p>
<pre><code class="language-python">for i in range(0,20,2):
    print(i)</code></pre>
<p>The output:</p>
<pre><code>0
2
4
6
8
10
12
14
16
18</code></pre>
<p>Of course, you can use <code>range()</code> to specify any step you would like, so if you want a step of 5, just do:</p>
<pre><code class="language-python">for i in range(0,20,5):
    print(i)</code></pre>
<p>The output is:</p>
<pre><code>0
5
10
15</code></pre>
<h2>Slicing</h2>
<p>If you never heard of slicing before, I recommend you to read <a href="https://renanmf.com/slicing-python/">Understanding Slicing in Python</a> first, there is also a video linked in the article if you prefer.</p>
<p>Slicing is useful when you want to apply a different step when working with a pre-defined list.</p>
<p>In this case I have a list <code>numbers</code> with the number from 1 to 16.</p>
<p>The logic is very similar to <code>range()</code>, since you also have a <code>start</code>, a <code>stop</code>, and a <code>step</code>.</p>
<p>In this case I&#8217;m starting on index 1, which is the number 2 in the list, remember lists are 0-indexed in Python.</p>
<p>I won&#8217;t put any <code>stop</code> value since I want to go until the last index.</p>
<p>Finally, I put a step of 2.</p>
<pre><code class="language-python">numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

for i in numbers[1::2]:
    print(i)</code></pre>
<p>The output will be:</p>
<pre><code>2
4
6
8
10
12
14
16</code></pre>
<p>Another way to implement the slicing from the code above is to combine <code>range()</code> with <a href="https://renanmf.com/get-number-elements-list-python/"><code>len()</code></a>:</p>
<pre><code class="language-python">numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

for i in range(1, len(numbers), 2):
   print(numbers[i])</code></pre>
<p>The output is the same:</p>
<pre><code>2
4
6
8
10
12
14
16</code></pre>
<p>Again, the same way we could use any step in <code>range()</code>, we can change the step in slicing to anything we would like.</p>
<h2>What about about float values?</h2>
<p>An extra trick is how to achieve the same thing with float values.</p>
<p>In this case you have to use the library numpy and its function <code>arange</code>.</p>
<p>This way you can use floats as <code>start</code>, <code>stop</code>, and <code>step</code>.</p>
<pre><code class="language-python">import numpy as np

for i in np.arange(1.5, 2.5, 0.1):
    print (i)</code></pre>
<p>The output is:</p>
<pre><code>1.5
1.6
1.7000000000000002
1.8000000000000003
1.9000000000000004
2.0000000000000004
2.1000000000000005
2.2000000000000006
2.3000000000000007
2.400000000000001</code></pre>
<h2>Watch this on Youtube:</h2>
<p><iframe width="560" height="315" src="https://www.youtube.com/embed/tlI_DUE2IPg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe></p>
<p>The content <a href="https://renanmf.com/python-for-loop-increment-by-2/">Python for loop increment by 2</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python 1 line for loop</title>
		<link>https://renanmf.com/python-1-line-for-loop/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 19 Oct 2021 21:43:25 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3896</guid>

					<description><![CDATA[<p>Instead of using the same old way of iterating through lists, we can make our code simpler by using list comprehensions, which allow us to make a 1 line for loop in Python. Basic syntax of a 1 line for loop To use a one line for loop to replace a regular for loop, we [&#8230;]</p>
<p>The content <a href="https://renanmf.com/python-1-line-for-loop/">Python 1 line for loop</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Instead of using the same old way of iterating through lists, we can make our code simpler by using list comprehensions, which allow us to make a 1 line for loop in Python.</p>
<h2>Basic syntax of a 1 line for loop</h2>
<p>To use a one line for loop to replace a regular for loop, we can make:</p>
<pre><code class="language-python">[statement for i in list]</code></pre>
<p>Which is the same as doing:</p>
<pre><code class="language-python">for i in list:
    expression</code></pre>
<p>If we want some conditional to apply the expression, we have:</p>
<pre><code class="language-python">[statement for i in list if condition ]</code></pre>
<p>Which translates to:</p>
<pre><code class="language-python">for i in list:
    if condition:
        statement</code></pre>
<h2>Example 1: calculating the cube of a number</h2>
<p><strong>Regular way</strong></p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]
new_list = []

for n in numbers:
    new_list.append(n**3)

print(new_list)</code></pre>
<pre><code>[1000, 8000, 27000, 64000, 125000]</code></pre>
<p><strong>Using 1 line for loop</strong></p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]
new_list = []

new_list = [n**3 for n in numbers]

print(new_list)</code></pre>
<pre><code>[1000, 8000, 27000, 64000, 125000]</code></pre>
<h2>Example 2: calculating the cube of a number only if it is greater than 30</h2>
<p>Using the conditional, we can filter only the values we want the expression to be applied to.</p>
<p><strong>Regular way</strong></p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]
new_list = []

for n in numbers:
    if(n &gt; 30):
        new_list.append(n**3)

print(new_list)</code></pre>
<pre><code>[64000, 125000]</code></pre>
<p><strong>Using 1 line for loop</strong></p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]
new_list = []

new_list = [n**3 for n in numbers if n &gt; 30]

print(new_list)</code></pre>
<pre><code>[64000, 125000]</code></pre>
<h2>Example 3: calling functions with a 1 line for loop</h2>
<p>We can also call functions using the list comprehension syntax:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]
new_list = []

def cube(number):
    return number**3

new_list = [cube(n) for n in numbers if n &gt; 30]

print(new_list)</code></pre>
<pre><code>[64000, 125000]</code></pre>
<p>To know more about loops, check these posts on <a href="https://renanmf.com/for-loops-python/">for Loops in Python</a> and <a href="https://renanmf.com/while-loops-python/">While Loops in Python</a>.</p>
<p>The content <a href="https://renanmf.com/python-1-line-for-loop/">Python 1 line for loop</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>JWT in Python</title>
		<link>https://renanmf.com/jwt-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Tue, 05 Oct 2021 23:45:49 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3825</guid>

					<description><![CDATA[<p>JWT stands for JSON Web Token, which is a standard that defines how to send JSON objects compactly. The data in a JWT can be validated at any given time since the token is digitally signed. The JWT has three parts separated by dots .: Header, Payload, and Signature. Header The Header defines the information [&#8230;]</p>
<p>The content <a href="https://renanmf.com/jwt-in-python/">JWT in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>JWT stands for JSON Web Token, which is a standard that defines how to send JSON objects compactly.</p>
<p>The data in a JWT can be validated at any given time since the token is digitally signed.</p>
<p>The JWT has three parts separated by dots <code>.</code>: Header, Payload, and Signature.</p>
<h2>Header</h2>
<p>The Header defines the information about the JSON object.</p>
<p>In this case, we are saying this is a JWT token and its signature algorithm, HS256.</p>
<pre><code>{
  &quot;alg&quot;: &quot;HS256&quot;,
  &quot;typ&quot;: &quot;JWT&quot;
}</code></pre>
<h2>Payload</h2>
<p>The Payload is a JSON object with information about the entity, usually used for the authenticated user info.</p>
<p>We can have three types of Claims: Registered, Public, and Private.</p>
<p>The most common Registered Claims are iss (issuer), exp (expiration time), and sub (subject).</p>
<p>The Public Claims are the ones we use in our applications and you can define them as you need.</p>
<p>Finallt, Private claims are for sharing info between applications.</p>
<p>DO NOT store sensitive information in your tokens.</p>
<p>Here is an example of a valid token:</p>
<pre><code>{
  &quot;sub&quot;: &quot;000000&quot;,
  &quot;name&quot;: &quot;Admin&quot;,
  &quot;admin&quot;: true
}</code></pre>
<h2>Signature</h2>
<p>The signature is simply the concatenation of both the Header and Payload, hashed using base64UrlEncode.</p>
<p>It&#8217;s important to notice the secret key to make it more secure.</p>
<pre><code>HMACSHA256(
  base64UrlEncode(header) + &quot;.&quot; +
  base64UrlEncode(payload),
  secret)</code></pre>
<h2>Final Result</h2>
<p>The final result is a token with three sections separated by a dot <code>.</code></p>
<p>The first section is the hashed header, then the payload, and finally the signature.</p>
<pre><code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</code></pre>
<h2>Implementing JWT in Python</h2>
<p>To implement JWT in Python we are going to use the lib <a href="https://pyjwt.readthedocs.io/en/stable/">PyJWT</a>.</p>
<p>Install it using pip as follows:</p>
<pre><code>pip install PyJWT==2.1.0</code></pre>
<p>Then we are going to import it as <code>jwt</code>.</p>
<p>As explained before, we are going to need a secret key, the more random the better as you can see defined in the variable <code>JWT_SECRET_KEY</code>.</p>
<p>Define the algorithm, as you can see in the <code>JWT_ALGORITHM</code> variable.</p>
<p>And finally, define for how long the token will be valid, in the example below it will last 2 days (60 minutes <em> 24 hours </em> 2 days).</p>
<p>The function <code>create_jwt_token</code> receives a username and role that will be assigned to <code>sub</code> and <code>role</code> in our token.</p>
<p>The <code>exp</code> value will be calculated by using the datetime and timedelta.</p>
<p>We can then call <code>jwt.encode</code> passing the <code>jwt_payload</code>, the secret key, and the algorithm of our choice.</p>
<p>The result will be a token that will expire in two days.</p>
<p>Then we create another function <code>check_jwt_token</code> that expects a token as a string.</p>
<p>We call <code>jwt.decode</code> from PyJWT, pass the token, the secret key, and the algorithm to have the info back in plain values (not hashed).</p>
<p>This way we can recover the values of <code>username</code>, <code>role</code>, and <code>expiration</code>.</p>
<p>Then we check <code>if time.time() &lt; expiration:</code>, this will return <code>true</code> if the token is not expired.</p>
<p>Then we make a second check to match the username with one we might have in our database.</p>
<p>The function <code>check_jwt_username(username)</code> is a generic function that simply takes the username and looks for it in a user table in a database, you could implement it in any way you need.</p>
<p>If the token is not valid, an <a href="https://renanmf.com/handling-exceptions-python/">Exception</a> will be thrown and the code will return <code>False</code>.</p>
<p>If the token has expired or if the username is not found in the database, the function will also return <code>False</code>.</p>
<pre><code class="language-python">import jwt
from datetime import datetime, timedelta
import time

JWT_SECRET_KEY = &quot;MY_SUPER_SECRET_KEY&quot;
JWT_ALGORITHM = &quot;HS256&quot;
JWT_EXPIRATION_TIME_MINUTES = 60 * 24 * 2

# Create access JWT token
def create_jwt_token(username, role):
    expiration = datetime.utcnow() + timedelta(minutes=JWT_EXPIRATION_TIME_MINUTES)
    jwt_payload = {&quot;sub&quot;: username, &quot;role&quot;: role, &quot;exp&quot;: expiration}
    jwt_token = jwt.encode(jwt_payload, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)

    return jwt_token

# Check whether JWT token is correct
def check_jwt_token(token):
    try:
        jwt_payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=JWT_ALGORITHM)
        username = jwt_payload.get(&quot;sub&quot;)
        role = jwt_payload.get(&quot;role&quot;)
        expiration = jwt_payload.get(&quot;exp&quot;)
        if time.time() &lt; expiration:
            is_valid = check_jwt_username(username)
            if is_valid:
                return True
            else:
                return False
        else:
            return False
    except Exception as e:
        return False
</code></pre>
<p>This is the most generic and simple way to work with JWT tokens in Python.</p>
<p>One could use this to implement JWT in any framework, like Flask or FastAPI.</p>
<p>The content <a href="https://renanmf.com/jwt-in-python/">JWT in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Single Responsibility Principle (SRP) in Python</title>
		<link>https://renanmf.com/single-responsibility-principle-in-python/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Mon, 06 Sep 2021 17:54:14 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3797</guid>

					<description><![CDATA[<p>If you need a refresher on Object-Oriented Programming before reading this article, here is all you need: Classes and Objects in Python Object-Oriented Programming: Encapsulation in Python Inheritance in Python Object-Oriented Programming: Polymorphism in Python The Single Responsibility Principle (SRP) is about making a class focus on its primary responsibility. Other responsibilities must be avoided. [&#8230;]</p>
<p>The content <a href="https://renanmf.com/single-responsibility-principle-in-python/">Single Responsibility Principle (SRP) in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>If you need a refresher on Object-Oriented Programming before reading this article, here is all you need:</p>
<ul>
<li><a href="https://renanmf.com/classes-objects-python/">Classes and Objects in Python</a></li>
<li><a href="https://renanmf.com/object-oriented-programming-encapsulation-in-python/">Object-Oriented Programming: Encapsulation in Python</a></li>
<li><a href="https://renanmf.com/inheritance-python/">Inheritance in Python</a></li>
<li><a href="https://renanmf.com/object-oriented-programming-polymorphism-in-python/">Object-Oriented Programming: Polymorphism in Python</a></li>
</ul>
<hr />
<p>The Single Responsibility Principle (SRP) is about making a class focus on its primary responsibility.</p>
<p>Other responsibilities must be avoided.</p>
<p>Letting your objects take too many responsibilities is the formula for future headaches and a bunch of code smells.</p>
<p>This can be better explained with code, so let&#8217;s see an example of this principle.</p>
<h2>Python Code Example</h2>
<p>Consider a class called <code>Vehicle</code> like the one below.</p>
<p>We can initialize a vehicle with some attributes like model and year.</p>
<p>We also have some methods like move and accelerate, which are actions a vehicle does.</p>
<p>We also have a <code>__str__(self)</code> to make it easy to print the object in a human-readable format.</p>
<pre><code class="language-python">class Vehicle:
    def __init__(self, year, model, plate_number, current_speed = 0):
        self.year = year
        self.model = model
        self.plate_number = plate_number
        self.current_speed = current_speed

    def move(self):
        self.current_speed += 1

    def accelerate(self, value):
        self.current_speed += value

    def stop(self):
        self.current_speed = 0

    def __str__(self):
        return f&#039;{self.model}-{self.year}-{self.plate_number}&#039;

my_car = Vehicle(2009, &#039;F8&#039;, &#039;ABC1234&#039;, 100)

my_car.move()

print(my_car.current_speed)

my_car.accelerate(10)

print(my_car.current_speed)

my_car.stop()

print(my_car)</code></pre>
<p>The output of the test above will be:</p>
<pre><code>101
111
F8-2009-ABC1234</code></pre>
<p>The class above follows the Single Responsibility Principle.</p>
<p>It only handles attributes and methods that concern itself, a Vehicle.</p>
<h3>Breaking the Single Responsibility Principle</h3>
<p>Let&#8217;s break the SRP.</p>
<p>Say you want to save the object in a file, to store the information in a persistent way.</p>
<p>Naively, a programmer can just add a <code>save(self, filename)</code> method.</p>
<p>This method will take the object it belongs to and save it in a file.</p>
<pre><code class="language-python">class Vehicle:
    def __init__(self, year, model, plate_number, current_speed = 0):
        self.year = year
        self.model = model
        self.plate_number = plate_number
        self.current_speed = current_speed

    def move(self):
        self.current_speed += 1

    def accelerate(self, value):
        self.current_speed += value

    def stop(self):
        self.current_speed = 0

    def __str__(self):
        return f&#039;{self.model}-{self.year}-{self.plate_number}&#039;

    def save(self, filename):
        file = open(filename, &quot;w&quot;)
        file.write(str(self))
        file.close()

my_car = Vehicle(2009, &#039;F8&#039;, &#039;ABC1234&#039;, 100)

print(my_car)

my_car.save(&quot;my_car.txt&quot;)

with open(&quot;my_car.txt&quot;) as f:
    print(f.read())</code></pre>
<p>The output for the code above is:</p>
<pre><code>F8-2009-ABC1234
F8-2009-ABC1234</code></pre>
<p>You can test the code and check it works.</p>
<p>But should a <code>Vehicle</code> class be able to write data to a file?</p>
<p>What does storing info have to do with a <code>Vehicle</code>?</p>
<p>Think about it in terms of a massive system with hundreds or thousands of classes.</p>
<p>Are you going to write a &quot;save file&quot; method for each class?</p>
<p>What happens when you need to make a change to the way your files are stored?</p>
<p>Maybe you want to check whether the path of the file exists to avoid errors and print a message for the user.</p>
<p>In this case, you would need to change every single file containing the &quot;save file&quot; method, which is prone to errors and it is bad practice.</p>
<p>How do we solve this then?</p>
<h3>Fixing the class</h3>
<p>The fixing, in this case, is as in the code below.</p>
<p>I created a new class called <code>DataService</code> and moved the <code>save</code> method from Vehicle to <code>DataService</code>.</p>
<p>Since <code>DataService</code> is a utility class meant to only save objects to a file, it doesn&#8217;t make sense to save itself.</p>
<p>So I annotated the <code>save</code> method with <code>@staticmethod</code>.</p>
<p>If you execute the code below you will notice the behavior is the same and the code still runs.</p>
<p>The difference is that now I can use <code>DataService</code> and <code>save(my_object, filename)</code> to store any kind of object.</p>
<p>And if I want to change the way I save my objects from files to a database, for instance, I just need to make a change in a single place.</p>
<p>Later I cans also implement methods to retrieve the data, update the data, or delete it, among other actions related to data management that are very common in any real-world system.</p>
<pre><code class="language-python">class Vehicle:
    def __init__(self, year, model, plate_number, current_speed = 0):
        self.year = year
        self.model = model
        self.plate_number = plate_number
        self.current_speed = current_speed

    def move(self):
        self.current_speed += 1

    def accelerate(self, value):
        self.current_speed += value

    def stop(self):
        self.current_speed = 0

    def __str__(self):
        return f&#039;{self.model}-{self.year}-{self.plate_number}&#039;

class DataService:
    @staticmethod
    def save(my_object, filename):
        file = open(filename, &quot;w&quot;)
        file.write(str(my_object))
        file.close()

my_car = Vehicle(2009, &#039;F8&#039;, &#039;ABC1234&#039;, 100)

print(my_car)

data_service = DataService()
data_service.save(my_car, &quot;my_car.txt&quot;)

with open(&quot;my_car.txt&quot;) as f:
    print(f.read())</code></pre>
<p>The output will be: </p>
<pre><code>F8-2009-ABC1234
F8-2009-ABC1234</code></pre>
<h2>Anti-Pattern: God Classes (God Object)</h2>
<p>For every pattern, there is an anti-pattern.</p>
<p>Classes with loads of responsibility are called God Classes.</p>
<p>God is omnipotent, omnipresent, and omniscient, and so it is a God Object.</p>
<p>It is everywhere, it can do everything and it knows everything.</p>
<p>This creates massive classes with thousands of lines of code that no one wants to touch in fear of breaking something.</p>
<p>Keep your classes cohesive, focus on their primary responsibility and avoid this bad practice.</p>
<p>Your future self (and your workmates) will thank you.</p>
<p>The content <a href="https://renanmf.com/single-responsibility-principle-in-python/">Single Responsibility Principle (SRP) in Python</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Why Python for Web Development</title>
		<link>https://renanmf.com/why-python-for-web-development/</link>
		
		<dc:creator><![CDATA[Renan Moura]]></dc:creator>
		<pubDate>Thu, 10 Jun 2021 14:50:34 +0000</pubDate>
				<category><![CDATA[FastAPI]]></category>
		<category><![CDATA[Flask]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[fastapi]]></category>
		<category><![CDATA[flask]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://renanmf.com/?p=3525</guid>

					<description><![CDATA[<p>The options to develop web apps these days are so many that it would take tens of thousands of words to list and describe each one of them. Languages like Java, JavaScript, C#, and Python are amongst the most famous for the purpose of developing web apps. In this article, I will discuss some of [&#8230;]</p>
<p>The content <a href="https://renanmf.com/why-python-for-web-development/">Why Python for Web Development</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The options to develop web apps these days are so many that it would take tens of thousands of words to list and describe each one of them.</p>
<p>Languages like Java, JavaScript, C#, and Python are amongst the most famous for the purpose of developing web apps.</p>
<p>In this article, I will discuss some of the benefits of using Python, specifically, for the development of web apps.</p>
<h2>Easy to learn</h2>
<p>Python is one of the easiest languages to learn.</p>
<p>If you are an experienced developer, you can learn enough Python in a week to be dangerous and do a lot.</p>
<p>If you are a complete newbie, Python is a great first language, with a clear syntax, and allows you to get started as quickly as one can be.</p>
<p>In any case, if you want a hand in starting out with Python, try my free <a href="https://renanmf.com/the-python-guide-for-beginners/">Python Guide For Beginners</a> to get you up to speed as fast as possible.</p>
<p>This image from <a href="https://xkcd.com/353/">xkcd</a> exemplifies this better than I ever could:</p>
<p><img decoding="async" src="https://renanmf.com/wp-content/uploads/2021/06/python_flying.png" alt="" /></p>
<h2>Ecosystem</h2>
<p>Libraries for everything.</p>
<p>Python has a library for every use case.</p>
<p>From web scraping and simple scripting tasks to machine learning.</p>
<p>The plethora of tools you can find in the Python ecosystem is so big that you can jump many levels of the heavy lifting in your app idea by just importing some super useful libraries.</p>
<p>There is no advantage in reinventing the wheel, the same way there is no benefit in rewriting code that has already been coded.</p>
<p>Especially considering how the most used libraries are battle-tested in levels a single developer could never do.</p>
<h2>Frameworks</h2>
<p>Python has lots of frameworks for web development.</p>
<p>By far, the most famous are <a href="https://www.djangoproject.com/">Django</a> and <a href="https://flask.palletsprojects.com/en/2.0.x/">Flask</a>, and as a recent new contender we have <a href="https://fastapi.tiangolo.com/">FastAPI</a>.</p>
<h3>Django</h3>
<p>Django is an interesting choice when you don&#8217;t want to think too much about all the pieces you are going to use.</p>
<p>Django has “Batteries Included”, which means a very good ORM, Authentication, Admin panel, template engine, and many other features most web apps use.</p>
<p>And if you need a REST API, <a href="https://renanmf.com/django-rest-framework-api-few-minutes/">Django REST Framework</a> is an easy-to-install plugin that makes full use of Django&#8217;s built-in structures.</p>
<h3>Flask</h3>
<p>Flask is minimalistic, known as a micro framework, it gives you the bare minimum to start coding.</p>
<p>For most things, you will need to add a plugin and integrate it into Flask.</p>
<p>SQLAlchemy for ORM for instance is a must if you don&#8217;t want to work with raw SQL (which I personally prefer).</p>
<p>On the other hand, Flask is good for those who want full control of their web app and choose the freedom to use whatever they want.</p>
<p>With its version 2.0, Flask now has full support for Async and WebSockets.</p>
<h3>FastAPI</h3>
<p>I have been using FastAPI for some time now and I have been really enjoying it.</p>
<p>It is very similar to Flask in the sense that is very lean and simple to get started.</p>
<p>At the same time, it comes with full support for Async right from the start and a variety of tools to develop APIs easily, like the auto-generation of documentation with Swagger.</p>
<p>And if you want to develop a standard web app, you can just make use of Jinja 2, the same way Flask does.</p>
<h2>Developer Time &gt; Execution Time</h2>
<p>When developing a new project, the time it takes to develop a new feature is the single most expensive item.</p>
<p>This is because the longer it takes to develop something, the more Developer Time it will take.</p>
<p>Being able to prototype something really fast is a huge advantage these days and Python and its ecosystem and frameworks are great tools to achieve things quickly.</p>
<p>This is the counterargument for people who say &quot;Python is slow&quot;.</p>
<p>Slow for what?</p>
<p>Many languages are faster in execution time, but, as I said in the title <strong>&quot;Developer Time &gt; Execution Time&quot;</strong>.</p>
<p>Another thing to notice is that I/O operations are by far the slowest thing in an app, so good caching strategies ( by using <a href="https://redis.io/">Redis</a> for example) and a better database design will give you better ROI than switching languages in many situations.</p>
<p>And finally, think in terms of Pareto&#8217;s 80/20, roughly 80% of consequences come from 20% of the causes</p>
<p>I remember in college when studying in this class of Computer Architecture and there was this chapter about optimization.</p>
<p>In one of the examples, there was a program written in C++, which is an extremely fast language for most purposes.</p>
<p>There was a small part of this program responsible for a huge part of the performance problems, simply because it was heavily used, more than other parts of the code.</p>
<p>What did they do?</p>
<p>They rewrote that single part in pure Assembly.</p>
<p>By Pareto&#8217;s logic, this small implementation was responsible for a good boost in performance.</p>
<p>For Python, you can follow the same logic.</p>
<p>In most cases, pure Python is more than enough and gives you the extra speed in development time.</p>
<p>When performance is a must, there are tons of Python libraries that are simply wrappers around C++ or C that are very performatic, which is the case for <a href="https://pandas.pydata.org/">Pandas</a> and <a href="https://www.tensorflow.org/">Tensorflow</a>.</p>
<p>And, if you have a specific use case, you can always implement the solution yourself in any other language and simply call it from Python.</p>
<p>There are many ways to do that, either by direct calls or by using another intermediate system like a message broker (Kafka for instance) to make the communication between systems even more transparent.</p>
<p>The content <a href="https://renanmf.com/why-python-for-web-development/">Why Python for Web Development</a> is from <a href="https://renanmf.com">Renan Moura - Software Engineering</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
