<?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>Francisco R Porrata &#8211; Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/franciscoporrata/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com</link>
	<description></description>
	<lastBuildDate>Sun, 04 Sep 2022 17:58:45 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Francisco R Porrata &#8211; Be on the Right Side of Change</title>
	<link>https://blog.finxter.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Overriding in Python</title>
		<link>https://blog.finxter.com/overriding-in-python/</link>
		
		<dc:creator><![CDATA[Francisco R Porrata]]></dc:creator>
		<pubDate>Wed, 28 Oct 2020 13:50:50 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=15834</guid>

					<description><![CDATA[In this article, we are going to explore the concept of overriding in Python. We are also going to explore what are magic methods and abstract classes. Introduction Overriding is an interesting concept in object-oriented programming.  When the method definitions of a Base Class are changed in a Subclass (Derived) Class this is called a ... <a title="Overriding in Python" class="read-more" href="https://blog.finxter.com/overriding-in-python/" aria-label="Read more about Overriding in Python">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this article, we are going to explore the concept of overriding in Python. We are also going to explore what are magic methods and abstract classes.</p>



<h2 class="wp-block-heading">Introduction</h2>



<p class="wp-block-paragraph">Overriding is an interesting concept in <a href="https://blog.finxter.com/object-oriented-programming-terminology-cheat-sheet/" target="_blank" rel="noreferrer noopener" title="[Python OOP Cheat Sheet] A Simple Overview of Object-Oriented Programming">object-oriented programming</a>.  When the method definitions of a Base Class are changed in a Subclass (Derived) Class this is called a method override.  You are keeping the same signature of the method but changing the definition or implementation of a method defined by one of the ancestors.  There is no special syntax or additional keywords needed to do method overriding in Python.  It is a very important object-oriented programming concept since it makes inheritance exploit its full power.  In essence, you are not duplicating code, thus following the programming principle of DRY (do not repeat yourself), and you can enhance the method in the subclass.</p>



<p class="wp-block-paragraph">To understand the concept of overrides, you must know the basic concepts of object-oriented programming such as classes and inheritance.  There are many resources on the internet about OOP.  A really good resource is Finxter Academy’s object-oriented Python class: <a href="https://academy.finxter.com/university/object-oriented-python/">https://academy.finxter.com/university/object-oriented-python/</a></p>



<h2 class="wp-block-heading">Need for Overrides</h2>



<p class="wp-block-paragraph">In the following example, you see how inheritance works and the problem of not overriding a method in the subclass.  The Parent class has a method <code>whoami</code> that displays <code>“I am a parent”</code>.  This method is inherited by the <code>Child</code> class.  Calling the <code>whoami </code>method from the Child class, calls the inherited method from the Parent class and thus displays <code>“I am a parent”</code> which is wrong.</p>



<p class="wp-block-paragraph">Inheritance example with no method overriding:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Parent():
    def whoami(self):
        print("I am a parent")

class Child(Parent):
    def play(self):
        print(" I am playing")

child = Child()
child.whoami()

# Output:
# I am a parent
</pre>



<h2 class="wp-block-heading">Basic Override</h2>



<p class="wp-block-paragraph">The next example, shows how basic overriding works.  In this example the <code>Child</code> class has a definition of the <code>whoami</code> method that overrides the method from the <code>Parent</code> class. Calling the <code>whoami</code> method from the <code>Child</code> class now displays <code>“I am a child”</code>.</p>



<p class="wp-block-paragraph">Basic Overriding example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#Overriding
class Parent():
    def whoami(self):
        print("I am a parent")

class Child(Parent):
    def play(self):
        print(" I am playing")

    def whoami(self):
        print("I am a child")
        
parent = Parent()
parent.whoami()
print()
child = Child()
child.whoami()

# Output:
# I am a parent
# I am a child
</pre>



<h2 class="wp-block-heading">Extending a Method Through Overrides</h2>



<p class="wp-block-paragraph">The third example shows how you can <strong>extend</strong> a method in a Base Class by overriding the method in the Subclass.  To do that we use the <code>super()</code> built-in function.  It returns a proxy object that allows us to access methods of the base class.  We can refer to the base class from the subclass without having to call the base class name explicitly.</p>



<p class="wp-block-paragraph">The <code>Employee</code> class has the following details for the employee: employee number, employee name, salary and, department number.  This information is passed to the instantiated object in the <code><a href="https://blog.finxter.com/python-init/" target="_blank" rel="noreferrer noopener" title="What is __init__ in Python?">__init__</a></code> method.  The <code>showEmployee</code> method of the class then displays this information formatted using new lines.</p>



<p class="wp-block-paragraph">The <code>Salesman</code> class inherits from the <code>Employee</code> class.  By default, it inherits the <code>showEmployee</code> method as-is from the <code>Employee</code> class.  The only problem is that we want to display the commission that the salesman receives as part of the printed information.  Here is where overriding is needed.  We want to reuse the <code>showEmployee</code> method from the <code>Employee</code> class but we want to extend it to add the commission information.  This is accomplished by using the <code>super()</code> built-in function.  In the example below you see that in the <code>Salesman</code> class, <code>super()</code> is used twice.  The <code>__init__</code> method uses it to call the <code>__init__</code> method of the Employee base class and the <code>showEmployee</code> uses it to override the <code>showEmployee</code> method of the <code>Employee</code> base class.  In it, we display the employee information for the salesman plus the commission for the salesman.</p>



<p class="wp-block-paragraph">A third class called <code>CEO</code> uses the same logic as before.  The <code>showEmployee</code> method in this case displays the employee information plus the stock options for the <code>CEO</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Employee():
    def __init__(self, empno, ename, salary, deptno):
        self.Empno = empno
        self.Ename = ename
        self.Salary = salary
        self.Deptno = deptno
    
    def showEmployee(self):
        print("Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format(self.Empno, self.Ename, self.Salary, self.Deptno))
              
class Salesman(Employee):
    def __init__(self, empno, ename, salary, deptno, comm):
        self.Commission = comm
        super().__init__(empno, ename, salary, deptno)
              
    def showEmployee(self):
        print("Salesman Profile")       
        super().showEmployee()      
        print("Commision : ", self.Commission)

class CEO(Employee):
    def __init__(self, empno, ename, salary, deptno, stock):
        self.Stock = stock
        super().__init__(empno, ename, salary, deptno)
              
    def showEmployee(self):
        print("CEO Profile")      
        super().showEmployee()      
        print("Stock Options : ", self.Stock)

              
salesman = Salesman(200, "John Doe", 67000, "Sales", 100)
salesman.showEmployee()
print("")
ceo = CEO(40, "Jennifer Smith", 300000, "Director", 1000000)
ceo.showEmployee()              </pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Salesman Profile
Employee # : 200
Employee Name : John Doe
Salary : 67000
Department : Sales
Commision :  100

CEO Profile
Employee # : 40
Employee Name : Jennifer Smith
Salary : 300000
Department : Director
Stock Options :  1000000
</pre>



<h2 class="wp-block-heading">Multiple Inheritance Overriding</h2>



<p class="wp-block-paragraph">Understanding <strong><em>multiple inheritance</em></strong> has its own challenges.  One of them is the use of <code>super()</code>.  Here is a link to an article about this issue: <a href="https://www.datacamp.com/community/tutorials/super-multiple-inheritance-diamond-problem">https://www.datacamp.com/community/tutorials/super-multiple-inheritance-diamond-problem</a></p>



<p class="wp-block-paragraph">In the example below, I wanted to show a way to override a method from a subclass with multiple inheritance.  The example consists of three classes: <code>Account</code>, <code>Customer</code>, and <code>Orders</code>.  </p>



<ul class="wp-block-list"><li>The <code>Account</code> class has its name and number and a display method which displays this information.  </li><li>The <code>Customer</code> class has also its name and number and a display method that displays this information.  </li><li>The <code>Orders</code> class displays the orders information for a customer in a specific account.  It inherits from both the <code>Account</code> and Orders class.  The display method in this class overrides the display methods of the base classes.  The display method prints the Account information, the Customer information, and the Orders information</li></ul>



<p class="wp-block-paragraph">Here&#8217;s an example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Account():
    def __init__(self, name, number):
        self.Name = name
        self.Number = number
    
    def display(self):
        print("Account # : {}\nAccount Name : {}".format(self.Number, self.Name))
              
class Customer():
    def __init__(self, name, number):
        self.Name = name
        self.Number = number
              
    def display(self):
        print("Customer # : {}\nCustomer Name : {}".format(self.Number, self.Name))

class Orders(Account, Customer):
    def __init__(self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty):
        self.OrdNumber = ordnumber
        self.Product = product
        self.Qty = qty
        self.OrdName = ordnamename
        self.acct = Account(acctname, acctnumber)
        self.cust = Customer(custname, custnumber)
              
    def display(self):
        print("Order Information")
        self.acct.display()
        self.cust.display() 
        print("Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format(self.OrdNumber, self.OrdName, self.Product, self.Qty))

acct = Account("AB Enterprise", 12345)
acct.display()
print("")
cust = Customer("John Smith", 45678)
cust.display()
print("")
order = Orders(12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, )
order.display()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Account # : 12345
Account Name : AB Enterprise

Customer # : 45678
Customer Name : John Smith

Order Information
Account # : 12345
Account Name : AB Enterprise
Customer # : 45678
Customer Name : John Smith
Order # : 1
Order Name : Order 1
Product : Widget
Quantiy : 5
</pre>



<h2 class="wp-block-heading">Different Overriding Scenarios</h2>



<h3 class="wp-block-heading">1 &#8211; Class Methods</h3>



<p class="wp-block-paragraph">Class methods are special in the sense that they can be called on a class by itself or by instances of a class.&nbsp; They bind to a class so this means that the first argument passed to the method is a class rather than an instance.</p>



<p class="wp-block-paragraph">Class methods are written similarly to regular instance methods.  One difference is the use of the <a href="https://blog.finxter.com/closures-and-decorators-in-python/" target="_blank" rel="noreferrer noopener" title="Closures and Decorators in Python">decorator </a><code>@classmethod</code> to identify that the method is a class method.  Also, by convention, instead of using self to reference the instance of a class, <code>cls</code> is using to reference the class.  For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Account():
    @classmethod
    def getClassVersion(cls):
        print("Account class version is 1.0”)
</pre>



<p class="wp-block-paragraph">For more information about class methods check <a href="https://www.geeksforgeeks.org/classmethod-in-python" target="_blank" rel="noreferrer noopener" title="https://www.geeksforgeeks.org/classmethod-in-python">this </a>website.</p>



<p class="wp-block-paragraph"> </p>



<p class="wp-block-paragraph">Here is an example of the problem you will encounter when overriding a class method:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class ParentClass:
    @classmethod
    def display(cls, arg):
        print("ParentClass")
        
class SubClass(ParentClass):
    @classmethod
    def display(cls, arg):
        ret = ParentClass.create(cls, arg)
        print("Subclass")
        return ret
    
SubClass.display("test")
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">create() takes 2 positional arguments but 3 were given</pre>



<p class="wp-block-paragraph">In the <code>Subclass</code>, the call to the <code>ParentClass</code> create method is not an unbound call the way it happens with a normal instance method.  The outcome of this call is a <a href="https://blog.finxter.com/how-to-solve-python-typeerror-int-object-is-not-iterable/" target="_blank" rel="noreferrer noopener" title="How to Solve Python “TypeError: ‘int’ object is not iterable”?">TypeError </a>because the method received too many arguments.</p>



<p class="wp-block-paragraph">The solution is to use <code>super()</code> in order to successfully use the parent implementation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class ParentClass:
    @classmethod
    def display(cls, arg):
        print("ParentClass")
        
        
        
class SubClass(ParentClass):
    @classmethod
    def display(cls, arg):
        ret = super(SubClass, cls).create(arg)
        print("Subclass")
        return ret
    
SubClass.display("test")
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ParentClass
Subclass</pre>



<p class="wp-block-paragraph"></p>



<h3 class="wp-block-heading">2 &#8211; Magic Methods</h3>



<p class="wp-block-paragraph"><strong>What are magic methods?</strong></p>



<p class="wp-block-paragraph">Magic methods are a set of methods that Python automatically associates with every class definition. Your classes can override these magic methods to implement different behaviors and make them act just like Python&#8217;s built-in classes. Below you will see examples of two of the most common ones: <code>__str__</code> and <code>__repl__</code>. Using these two methods, you can implement how your objects are displayed as strings, which will be of importance while debugging and presenting the information to the user.  Overriding these methods adds to the flexibility and power of Python.  </p>



<p class="wp-block-paragraph">The <code>__str__</code> method of a class is used when Python prints an object. This magic method is called by the <code>str</code> built-in function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class DemoMagic():
    def display(self):
        print("Demo Magic class")
       
varDemo = DemoMagic()
varDemo.display()
str(varDemo)  
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Demo Magic class
'&lt;__main__.DemoMagic object at 0x000002A7A7F64408>'

class DemoMagic():
def display(self):
        print("Demo Magic class")
        
def __str__(self):
        return "Override of str function"
        
varDemo = DemoMagic()
varDemo.display()
str(varDemo)     
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Demo Magic class
'Override of str function'
</pre>



<p class="wp-block-paragraph">The <code>__repr__</code> method of a class is used to display the details of an object&#8217;s values. This magic method is called by the built-in the <code>repr</code> function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Person(object):
    def __init__(self, firstname, lastname):
         self.first = firstname
         self.last = lastname

    def __repr__(self):
        return "%s %s" % (self.first, self.last)
    
Tom = Person("Tom", "Sawyer")
repr(Tom)
</pre>



<p class="wp-block-paragraph">Output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">'Tom Sawyer'</pre>



<p class="wp-block-paragraph">Here is a list of magic methods.&nbsp; You can learn more about them here (<a href="https://www.tutorialsteacher.com/python/magic-methods-in-python">https://www.tutorialsteacher.com/python/magic-methods-in-python</a>) and think how to override them to fit your needs:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">'__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__'</pre>



<h3 class="wp-block-heading">3 &#8211; Abstract Classes  </h3>



<p class="wp-block-paragraph">An abstract class is a blueprint that subclasses must follow. &nbsp;It can be viewed as a contract between the abstract class and the subclass.&nbsp; The abstract class tells you what to do by providing an empty abstract method and the subclass must implement it.&nbsp; By default, you must override the abstract methods defined by the abstract class.&nbsp; In other terms, we are providing a common interface for different implementations of a class.&nbsp; This is very useful for large projects where certain functionality must be implemented.</p>



<p class="wp-block-paragraph">Here is an example of an abstract class and the overrriden methods in the subclasses.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from abc import ABC, abstractmethod 
class Animal(ABC): 
       @abstractmethod
    def whoami(self): 
        pass

class Dog(Animal): 
  
    def move(self): 
        print("I am a dog") 

class Cat(Animal): 
  
    def move(self): 
        print("I am a cat") 
</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">Overriding is a basic concept used in many places in object-oriented programming.&nbsp; You must understand it to be able to implement better classes and modify their behavior.&nbsp; This article shows you some examples where you can use overrides in Python.&nbsp; Other concepts mentioned that are worth learning more about are: magic method and abstract classes.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Closures and Decorators in Python</title>
		<link>https://blog.finxter.com/closures-and-decorators-in-python/</link>
		
		<dc:creator><![CDATA[Francisco R Porrata]]></dc:creator>
		<pubDate>Sun, 16 Aug 2020 10:14:50 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=11909</guid>

					<description><![CDATA[This tutorial teaches you two advanced Python skills: closures and decorators. Mastering them will make you a better coder today&#8212;so, let&#8217;s dive right into them! Closures Every function in Python is first class, because they can be passed around like any other object. Usually, when a programming language creates a function just like other data ... <a title="Closures and Decorators in Python" class="read-more" href="https://blog.finxter.com/closures-and-decorators-in-python/" aria-label="Read more about Closures and Decorators in Python">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This tutorial teaches you two advanced Python skills: closures and decorators. Mastering them will make you a better coder today&#8212;so, let&#8217;s dive right into them!</p>



<h2 class="wp-block-heading">Closures</h2>



<p class="wp-block-paragraph">Every function in Python is first class, because they can be passed around like any other object. Usually, when a programming language creates a function just like other data types, that programming language supports something called Closures.</p>



<p class="wp-block-paragraph">A closure is a nested function. It is defined within an outer function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def outer_hello_fn():
    def hello():
        print("Hello Finxter!")
        
    hello()
</pre>



<p class="wp-block-paragraph">Here, we have an outer function called <code>outer_ hello_ fn</code>, it has no input arguments. The function <code>hello</code> is a nested function defined within the outer function. The <code>hello</code> function is a closure.</p>



<p class="wp-block-paragraph"><strong>Try It Yourself:</strong></p>




<iframe src="https://trinket.io/embed/python/c24797587b" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>




<p class="wp-block-paragraph"><em><strong>Exercise</strong>: What&#8217;s the output of this code snippet? Run the code to test if you&#8217;re correct. </em></p>



<p class="wp-block-paragraph">When the outer function is called, the <code>hello</code> function within it will be defined and then invoked. Here is the function call and output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">outer_hello_fn()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello Finxter!</pre>



<p class="wp-block-paragraph">hello has been defined within <code>outer_hello_fn</code>, which means if you try and invoke the <code>hello</code> function, it will not work.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hello()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">NameError: name 'hello' is not defined</pre>



<p class="wp-block-paragraph">If you want access to a function that is defined within another function, return the function object itself. Here is how.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def get_hello_fn():
    def hello():
        print("Hello Finxter!")

    return hello
</pre>



<p class="wp-block-paragraph">The outer function is called <code>get_hello_fn</code>. <code>hello</code>, is an inner function, or closure. Instead of invoking this hello function, simply return the <code>hello</code> function to whoever calls <code>get_hello_fn</code>. For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hello_fn = get_hello_fn()</pre>



<p class="wp-block-paragraph">Invoking <code>get_hello_fn</code> stores the return function object in the <code>hello_fn </code>variable. If you explore the contents of this <code>hello_fn </code>variable, you will see that it is a function object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hello_fn</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;function __main__.get_hello_fn.&lt;locals>.hello></pre>



<p class="wp-block-paragraph">As you can see in the structure, it is a locally defined function within <code>get_hello_fn</code>, that is, a function defined within another function, that is a closure. Now, this closure can be invoked by using the hello_fn variable.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">hello_fn()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello Finxter!</pre>



<p class="wp-block-paragraph">Invoke <code>hello_fn()</code> will print out <code>Hello Finxter!</code> to screen. A closure is something more than just an inner function defined within an outer function. There is more to it. Here is another example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def hello_by_name(name):
    
    def hello():
        print("Hello!", name)
        
    hello()
    
    return hello
</pre>



<p class="wp-block-paragraph">Here, the outer function is called <code>hello_by_name</code>, which takes in one input argument, the name of an individual. Within this outer function, there is the <code>hello</code> inner function. It prints to the screen <code>Hello!</code>, and the value of the name.</p>



<p class="wp-block-paragraph">The name variable is an input argument to the outer function. It is also accessible within the inner hello function. The name variable here can be thought of as a variable that is local to the outer function. Local variables in the outer function can be accessed by closures. Here is an example of passing an argument to the outside function:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">greet_hello_fn = hello_by_name("Chris")</pre>



<p class="wp-block-paragraph">The function hello is returned and it is stored in the <code>greet_hello_fn </code>variable.</p>



<p class="wp-block-paragraph">Executing this prints out <code>Hello! Chris</code> to screen. That is because we invoked the closure from within the outer function. We have a reference to the closure that was defined by the outer function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">greet_hello_fn()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hello! Chris</pre>



<p class="wp-block-paragraph">Notice something interesting here. Chris is available in the variable name which is local to the <code>hello_by_name </code>function.</p>



<p class="wp-block-paragraph">Now, we have already invoked and exited <code>hello_by_name </code>but the value in the name variable is still available to our closure. And this is another important concept about closures in Python. They hold the reference to the local state even after the outer function that has defined the local state has executed and no longer exists. Here is another slightly different example illustrating this concept.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def greet_by_name(name):
    
    greeting_msg = "Hi there!"

    def greeting():
        print(greeting_msg, name)
        
    return greeting
</pre>



<p class="wp-block-paragraph">The outer function, <code>greet_by_name</code>, takes in one input argument, name. Within the outer function, a local variable called <code>greeting_msg </code>is defined which says, <code>“Hi there!”</code>. A closure called greeting is defined within the outer function. It accesses the local variable <code>greeting_msg </code>as well as the input argument name. A reference to this greeting closure is returned from the outer <code>greet_by_name </code>function.</p>



<p class="wp-block-paragraph">Let&#8217;s go ahead and invoke greet_by_name and store the function object that it returns in the greet_fn variable. We will use this function object to greet Ray by name. Go ahead and invoke the greet_fn() by specifying parentheses. And it should say, Hi there! Ray. Observe how the closure has access not just to the name Ray but also to the greeting message, even after we have executed and exited the outer function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">greet_fn = greet_by_name("Ray")
greet_fn()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hi there! Ray</pre>



<p class="wp-block-paragraph">Closures carry around information about the local state. Let&#8217;s see what happens when the greet_by_name function is deleted,&nbsp;so you no longer have access to the outer function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">del greet_by_name</pre>



<p class="wp-block-paragraph">Now, remember that name and greeting message are both variables that were defined in the outer function. What happens to them? Now if you try to invoke greet by name.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">greet_by_name("Ray")</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">NameError: name 'greet_by_name' is not defined</pre>



<p class="wp-block-paragraph">What about the greet_fn?</p>



<p class="wp-block-paragraph">Remember that greet_fn is a reference to our closure. Does this still work?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">greet_fn()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Hi there! Ray</pre>



<p class="wp-block-paragraph">Not only does it work, but it still has access to the local variables that were defined in the outer function. The outer function no longer exists in Python memory, but the local variables are still available along with our closure.</p>



<h2 class="wp-block-heading">Decorators &#8211; Code Modification</h2>



<p class="wp-block-paragraph">Decorators help to add functionality to existing code without having to modify the code itself. Decorators are so-called because they decorate code, they do not modify the code, but they make the code do different things using decoration. Now that we have understood closures, we can work our way step by step to understanding and using decorators.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def print_message():
    print("Decorators are cool!")
</pre>



<p class="wp-block-paragraph">Here is a simple function that prints a message to screen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_message()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Decorators are cool!</pre>



<p class="wp-block-paragraph">Each time you invoke this function it will always print the same message. I want to use a few characters to decorate the original message, and I do this using the highlight function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random

def highlight():
    
    annotations = ['-', '*', '+', ':', '^']
    annotate = random.choice(annotations)
    
    print(annotate * 50)
    
    print_message()
    
    print(annotate * 50)
</pre>



<p class="wp-block-paragraph">The outer function highlight has no input arguments. Within the highlight function, a random choice of annotations is used to decorate the original message. The message will be highlighted with a random choice between the dash, the asterisk, the plus, the colon, and the caret.  The output will have an annotation of 50 characters before and after the message which is inside the print_message function.</p>



<p class="wp-block-paragraph"><strong>Try It Yourself:</strong></p>




<iframe src="https://trinket.io/embed/python/c616622162" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>




<p class="wp-block-paragraph"><em><strong>Exercise</strong>: What&#8217;s the output of this code snippet? Run the code to test your understanding!</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">highlight()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">::::::::::::::::::::::::::::::::::::::::::::::::::
Decorators are cool!
::::::::::::::::::::::::::::::::::::::::::::::::::
</pre>



<p class="wp-block-paragraph">Here is another function with a different message, print_another_message.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def print_another_message():
    print("Decorators use closures.")
</pre>



<p class="wp-block-paragraph">Now if I want to highlight this message as well, the existing highlight function will not work because it has been hardcoded to invoke the print_message function. So how do I change this highlight function so that it is capable of highlighting any message that I want printed out to screen? Remember that functions are first-class citizens in Python, which means whatever print function you have, you can pass it as an input argument to the highlight function. Here is a redefined highlight function, make_highlighted.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def make_highlighted(func):
    
    annotations = ['-', '*', '+', ':', '^']
    annotate = random.choice(annotations)
    
    def highlight():
        print(annotate * 50)
        func()
        print(annotate * 50)            
    
    return highlight
</pre>



<p class="wp-block-paragraph">The only difference here is that make_highlighted takes in an input argument that is a function. This function is what will print out the message to be displayed. The next change is that within the highlight closure, the function object that was passed in is invoked. That is the function object that will print out the message. Now we have two print functions so far.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_message()
print_another_message()
</pre>



<p class="wp-block-paragraph">And now with the help of  make_highlighted function, any printed message can be highlighted. For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">highlight_and_print_message = make_highlighted(print_message)

highlight_and_print_message()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">++++++++++++++++++++++++++++++++++++++++++++++++++
Decorators are cool!
++++++++++++++++++++++++++++++++++++++++++++++++++
</pre>



<p class="wp-block-paragraph">To print a different message and have it highlighted, simply pass a different function object to the make_highlighted function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">highlight_and_print_another_message = make_highlighted(print_another_message)

highlight_and_print_another_message()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Decorators use closures.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</pre>



<p class="wp-block-paragraph">It is clear that the make_highlighted function is very generic, you can use it to highlight any message that you want printed to screen. The function make_highlighted is a decorator.</p>



<p class="wp-block-paragraph">Why is it a decorator? Well, it takes in a function object and decorates it and changes it. In this example, it highlights the function with random characters. Decorators are a standard design pattern, and in Python, you can use decorators more easily. Instead of passing in a function object to make_highlighted, accessing the closure, and then invoking the closure, you can simply decorate any function by using @ and placing the decorator before the function to decorate.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@make_highlighted
def print_a_third_message():
    print("This is how decorators are used")
</pre>



<p class="wp-block-paragraph">The use of the decorator @make_highlighted will automatically pass the function print_a_third_message as an input to make_highlighted and highlight the message.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_a_third_message()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is how decorators are used
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</pre>



<p class="wp-block-paragraph">Now you can use the decorator to highlight any messages.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@make_highlighted
def print_any_message():
    print("This message is highlighted!")
</pre>



<p class="wp-block-paragraph">And now if you invoke print_any_message, you will find that the result that is displayed to screen is highlighted.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_any_message()</pre>



<p class="wp-block-paragraph">Output: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">++++++++++++++++++++++++++++++++++++++++++++++++++
This message is highlighted!
++++++++++++++++++++++++++++++++++++++++++++++++++
</pre>



<h2 class="wp-block-heading">Decorators &#8211; Customization</h2>



<p class="wp-block-paragraph">Let&#8217;s see another example of a Decorator that will do some work. It will do some error checking for us.</p>



<p class="wp-block-paragraph">Here are two functions that will be the input to our decorator</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def square_area(length):
    
    return length**2

def square_perimeter(length):
    
    return 4 * length
</pre>



<p class="wp-block-paragraph">We assume that the value of the radius passed in is positive and correct.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_area(5)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">25</pre>



<p class="wp-block-paragraph">What if I invoke the square_area and pass in -1?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_area(-1)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">-4</pre>



<p class="wp-block-paragraph">The input -1 doesn&#8217;t make sense as a value for the length. The function should have thrown an error or told us in some way that negative values of length are not valid. Now, if you were to perform an error check for each of these functions, we would have to do it individually. We would have to have an if statement within the area function as well as the perimeter function. Instead of that, let&#8217;s write a decorator that will perform this error checking for us. The decorator safe_calculate takes in one input argument that is a function object.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def safe_calculate(func):
    
    def calculate(length):
        if length &lt;= 0:
            raise ValueError("Length cannot be negative or zero")
        
        return func(length)
    
    return calculate
</pre>



<p class="wp-block-paragraph">This is the function object that will perform the calculation. Within the safe_calculate outer function, the inner function called calculate is the closure. calculate takes in one input argument, the length. It checks to see whether length is less than or equal to 0. If yes, it throws an error. And the way it throws an error is by simply calling a raise ValueError, “Length cannot be negative or zero”. Once we raise this error, Python will stop the execution. But if length is positive, it will invoke func and pass in length as an input argument. The safe_calculate is our decorator, which takes as its input a function object and returns a closure that will perform the safe calculation.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_area_safe = safe_calculate(square_area)</pre>



<p class="wp-block-paragraph">Let’s test it first:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_area_safe(5)</pre>



<p class="wp-block-paragraph">This is safe and I get the result here on the screen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">25</pre>



<p class="wp-block-paragraph">Invoking it with a negative number will raise an error</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_area_safe(-1)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: Length cannot be negative or zero</pre>



<p class="wp-block-paragraph">Let&#8217;s decorate the perimeter function as well with the safe_calculate.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_perimeter_safe = safe_calculate(square_perimeter)

square_perimeter(10)
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">40</pre>



<p class="wp-block-paragraph">But if you were to call square_perimeter_safe with a negative value for length well, that is a ValueError.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_perimeter_safe(-10)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: Length cannot be negative or zero</pre>



<p class="wp-block-paragraph">Now that you have a decorator, you should decorate your functions rather than use the way that we have been using so far.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@safe_calculate
def square_area(length):
    return length**2

@safe_calculate
def square_perimeter(length):
    return 4 * length
</pre>



<p class="wp-block-paragraph">Now, the next time square_area or the square_perimeter is called, the safety check will be performed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_perimeter(3)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">12</pre>



<p class="wp-block-paragraph">If you try to calculate the perimeter for a negative value of the length, you will get a ValueError. The safe_calculate function that we set up earlier has a limitation, and&nbsp;you will see what it in a future example.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">square_perimeter(-3)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: Length cannot be negative or zero</pre>



<p class="wp-block-paragraph">What happens when you have more than one input? Here is a function that calculates the area of a rectangle.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@safe_calculate
def rectangle_area(length, width):
    return length * width
</pre>



<p class="wp-block-paragraph">Within our safe_calculate function, we had invoked the func object which performs the calculation with just one input argument, with just the variable length. This is going to cause a problem when we use the safe_calculate decorator for the rectangle_area function.</p>



<p class="wp-block-paragraph">Once I have decorated this function, I&#8217;m going to invoke it with 4, 5.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">rectangle_area(4, 5)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TypeError: calculate() takes 1 positional argument but 2 were given</pre>



<p class="wp-block-paragraph">The problem is with the way we had defined the closure inside the safe_calculate function.</p>



<p class="wp-block-paragraph">The calculate closure takes in just one input argument. If a function has multiple input arguments, then safe_calculate cannot be used. A redefined safe_calculate_all function is shown below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def safe_calculate_all(func):
    
    def calculate(*args):
        
        for arg in args:
            if arg &lt;= 0:
                raise ValueError("Argument cannot be negative or zero")
        
        return func(*args)
    
    return calculate. 
</pre>



<p class="wp-block-paragraph">It takes in one input argument that is the function object that is to be decorated. The main change is in the input arguments that are passed into the calculate closure. The function calculate now takes in variable length arguments, *args.  The function iterates over all of the arguments that were passed in, and checks to see whether the argument is less than or equal to 0. If any of the arguments are less than or equal to 0, a ValueError will be raised. Remember, *args will unpack the original arguments so that the elements of the tuple are passed in individually to the function object, func. You can now use this safe_calculate_all decorator with functions that have any number of arguments.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@safe_calculate_all
def rectangle_area(length, width):
    return length * width
rectangle_area(10, 3)
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">30</pre>



<p class="wp-block-paragraph">Let&#8217;s try invoking the same function, but this time one of the arguments is negative. Width is negative and&nbsp;that gives me a ValueError, thanks to our safe_calculate_all decorator.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">rectangle_area(10, -3)</pre>



<p class="wp-block-paragraph">When you invoke this function, it will check all arguments.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: Argument cannot be negative or zero</pre>



<p class="wp-block-paragraph">It doesn&#8217;t matter which argument is negative, you still get the ValueError. Here the length is negative:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">rectangle_area(-10, 3)</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: Argument cannot be negative or zero</pre>



<h2 class="wp-block-heading">Chaining Decorators</h2>



<p class="wp-block-paragraph">You can have a function decorated using multiple decorators. And these decorators will be chained together.</p>



<p class="wp-block-paragraph">Here are two decorators, one prints asterisks and the other plus signs</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def asterisk_highlight(func):
    
    def highlight():
        print("*" * 50)

        func()

        print("*" * 50)            
    
    return highlight

def plus_highlight(func):
    
    def highlight():
        print("+" * 50)

        func()

        print("+" * 50)            
    
    return highlight
</pre>



<p class="wp-block-paragraph">The print_message_one is decorated with the asterisk_highlight.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@asterisk_highlight
def print_message_one():
    print("Decorators are cool!") 
print_message_one()
</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">**************************************************
Decorators are cool!
**************************************************
</pre>



<p class="wp-block-paragraph">Now let&#8217;s define another print function, but this time we will decorate it using two decorators, the plus_highlight and the asterisk_highlight.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@plus_highlight
@asterisk_highlight
def print_message_one():
    print("Decorators are cool!")
</pre>



<p class="wp-block-paragraph">What you see here is an example of chaining decorators together. But how are they chained? Which decoration comes first, the asterisk_highlight, or the plus_highlight? Whichever decorator is the closest to the function definition is what is executed first, and then the decorator which is further away from the function definition. This means that the message will be first highlighted with the asterisk, then the plus.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_message_one()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">++++++++++++++++++++++++++++++++++++++++++++++++++
**************************************************
Decorators are cool!
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++
</pre>



<p class="wp-block-paragraph">If you change the order of the decorators, the decorations order will change as well.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@asterisk_highlight
@plus_highlight
def print_message_one():
    print("Decorators are cool!") 
</pre>



<p class="wp-block-paragraph">You will have the same function print_message_one, but the decorator that is closest to the function definition is the plus_highlight and then the asterisk_highlight.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print_message_one()</pre>



<p class="wp-block-paragraph">Output:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++
Decorators are cool!
++++++++++++++++++++++++++++++++++++++++++++++++++
**************************************************
</pre>



<h2 class="wp-block-heading">Use of kwargs in Decorators</h2>



<p class="wp-block-paragraph">In this example we are using kwargs to display different messages for a decorator that times the execution of a function</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def timeit(func):
        def timed(*args, **kw):
            if 'start_timeit_desc' in kw:
                print(kw.get('start_timeit_desc'))
            ts = time.time()
            result = func(*args, **kw)
            te = time.time()
            if 'end_timeit_desc' in kw:
                print('Running time for {} is {} ms'.format(kw.get('end_timeit_desc'), (te - ts) * 1000))
            return result
        return timed 
</pre>



<p class="wp-block-paragraph">The timeit decorator is used for the test function.  Three parameters are passed to the function test: a, b and, **kwargs. The parameters a and b are handled in the decorator with *args as we have seen before.  The **kwargs parameter is used to pass descriptions for the function.  These parameters are start_timeit_desc and end_timeit_desc.  These two parameters are checked inside the timed closure and will display the messages that are in them.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@timeit
def test(a,b, **kwargs):
    return a * b


result = test(10,20, start_timeit_desc = "Start of test(10,20)...", end_timeit_desc = "End of test(10,20)")
print("result of test(10,20) = " + str(result))
Output:
Start of test(10,20)...
Running time for End of test(10,20) is 0.0 ms
result of test(10,20) = 200
</pre>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Create a Database Table with pyodbc in Python</title>
		<link>https://blog.finxter.com/creating-a-database-table-using-the-package-pyodbc-in-python/</link>
		
		<dc:creator><![CDATA[Francisco R Porrata]]></dc:creator>
		<pubDate>Sun, 02 Aug 2020 10:30:45 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=11636</guid>

					<description><![CDATA[In this article, you will get the necessary information on how to create a table in SQLite using the package pyodbc in Python.&#160; Example code is included and a link to a Github repo will be provided in the references section. Prerequisites To use pyodbc in this article some prerequisites need to be met. ODBC ... <a title="How to Create a Database Table with pyodbc in Python" class="read-more" href="https://blog.finxter.com/creating-a-database-table-using-the-package-pyodbc-in-python/" aria-label="Read more about How to Create a Database Table with pyodbc in Python">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this article, you will get the necessary information on how to <strong>create a table in SQLite</strong> using the package pyodbc in Python.&nbsp; Example code is included and a link to a Github repo will be provided in the references section.</p>



<h2 class="wp-block-heading">Prerequisites</h2>



<p class="wp-block-paragraph">To use <code><a href="https://pypi.org/project/pyodbc/" target="_blank" rel="noreferrer noopener" title="https://pypi.org/project/pyodbc/">pyodbc</a></code> in this article some prerequisites need to be met.</p>



<ol class="wp-block-list"><li><strong>ODBC Driver</strong> – you need to download and install the ODBC driver for the database provider you are using. In this article, I am using SQLite.&nbsp; Downloaded an ODCB driver for sqlite3 from<a href="http://www.ch-werner.de/sqliteodbc/"> http://www.ch-werner.de/sqliteodbc/</a>,</li><li><strong>SQLite3 </strong>&#8211; this article assumes that you have SQLite3 in your system and have created a database called <code>testDB.db</code>.</li><li><strong>Database DDL</strong> – different database providers use different data definition languages.&nbsp; DDL is the language needed to create tables in a database.&nbsp; You must be familiar with this syntax to successfully create your table.&nbsp; Creating tables in SQLite can be found here:<a href="https://sqlite.org/lang_createtable.html"> https://sqlite.org/lang_createtable.html</a></li><li><strong>Design your table</strong> – This is the table that will be implemented in the example below:</li></ol>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>Column</td><td>Data Type</td><td>Constraint</td><td>Default Value</td></tr><tr><td>PersonId</td><td>Integer</td><td>PRIMARY KEY</td><td>&nbsp;</td></tr><tr><td>FirstName</td><td>Text</td><td>NOT NULL</td><td>&nbsp;</td></tr><tr><td>LastName</td><td>Text</td><td>NOT NULL</td><td>&nbsp;</td></tr><tr><td>Age</td><td>Ineger</td><td>NULL</td><td>&nbsp;</td></tr><tr><td>CreatedAt</td><td>Text</td><td>NOT NULL</td><td>Now</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Here is an example of why you need to know the <strong><em>Data Definition Language</em></strong> of your database.&nbsp; The following information was taken from<a href="https://www.sqlite.org/datatype3.html"> https://www.sqlite.org/datatype3.html</a></p>



<hr class="wp-block-separator has-css-opacity"/>



<p class="wp-block-paragraph">“SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in<a href="https://www.sqlite.org/lang_datefunc.html"> Date And Time Functions</a> of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:</p>



<ul class="wp-block-list"><li><strong>TEXT</strong> as ISO8601 strings (<code>"YYYY-MM-DD HH:MM:SS.SSS"</code>).</li><li><strong>REAL</strong> as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.</li><li><strong>INTEGER</strong> as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.</li></ul>



<p class="wp-block-paragraph">Applications can choose to store dates and times in any of these formats and freely convert between formats using the built-in<a href="https://www.sqlite.org/lang_datefunc.html"> date and time functions</a>.”</p>



<hr class="wp-block-separator has-css-opacity"/>



<p class="wp-block-paragraph">SQLite Create Table Data Definition Language for the PeopleInfo table:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">CREATE TABLE PeopleInfo (
        PersonId INTEGER PRIMARY KEY,
        FirstName TEXT NOT NULL,
        LastName  TEXT NOT NULL,
        Age INTEGER NULL,
        CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL
 
);
</pre>



<p class="wp-block-paragraph">Let&#8217;s dive into the steps to create a table in SQLite using pyodbc in Python.</p>



<h2 class="wp-block-heading">Step 1: Install the pyodbc Package</h2>



<p class="wp-block-paragraph"><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-pyodbc-in-python/" data-type="post" data-id="457108" target="_blank">Install</a> the<a rel="noreferrer noopener" href="https://github.com/mkleehammer/pyodbc/wiki" target="_blank"> Pyodbc</a> package using the following command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install pyodbc</pre>



<p class="wp-block-paragraph">For Anaconda use the following command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">conda install -c anaconda pyodbc</pre>



<h2 class="wp-block-heading">Step 2: Connect Your Python Script to SQLite</h2>



<p class="wp-block-paragraph">Next, you will need to connect your script to SQLite.</p>



<p class="wp-block-paragraph">You may use this template to perform the connection:</p>



<p class="wp-block-paragraph">Remember to import the <code>pyodbc</code> package first. Connect to the database using the connect method with the ODBC connection string for SQLite.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pyodbc
conn = pyodbc.connect('Driver={SQLite3 ODBC Driver};'
                      'Server=server_name;'
                      'Database=database_name;'
                      'Trusted_Connection=yes;')
</pre>



<h2 class="wp-block-heading">Step 3: Create Cursor from Your Connection</h2>



<p class="wp-block-paragraph">The cursor object created by <code>cursor()</code> allows you to execute queries.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cursor = conn.cursor()</pre>



<h2 class="wp-block-heading">Step 4: Create the Table in SQLite</h2>



<p class="wp-block-paragraph">Now you will be able to create your table in SQLite</p>



<p class="wp-block-paragraph">For our example, here is the code that I used to create the table in SQL Server using Python:&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cursor.execute('''
 CREATE TABLE PeopleInfo (
        PersonId INTEGER PRIMARY KEY,
        FirstName TEXT NOT NULL,
        LastName  TEXT NOT NULL,
        Age INTEGER NULL,
        CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL
 
);

               ''')
</pre>



<h2 class="wp-block-heading">Step 5: Commit the Transaction</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">conn.commit()</pre>



<p class="wp-block-paragraph">Committing the transaction is an important topic to discuss.&nbsp; The statement above explicitly commits the transaction.&nbsp; If you do not commit the transaction, the database will not create the table.&nbsp; The transaction will be rolled back.</p>



<p class="wp-block-paragraph">&nbsp;Other options to consider are:</p>



<p class="wp-block-paragraph">&nbsp;1 &#8211; Add the autocommit parameter to connect.&nbsp; This will not require a manual commit.&nbsp; For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">con = pyodbc.connect(your_connection_string, autocommit = True)</pre>



<p class="wp-block-paragraph">2 – Use a <code><a href="https://blog.finxter.com/python-one-line-with-statement/" title="Python One Line With Statement">with</a></code> block and anything will be committed before the connection is terminated at the end of the <code>with</code> block.&nbsp; For example:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with pyodbc.connect(your_connection_string) as con:
    CREATE_TABLE_CODE</pre>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Step 6: Insert Records to Verify Your Table is Configured Correctly.</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cursor.execute('''
                INSERT INTO PeopleInfo (PersonId, FirstName, LastName, Age)
                VALUES
                (1,'Bob','Smith', 55),
                (2, 'Jenny','Smith', 66)
                ''')
conn.commit()
</pre>



<h2 class="wp-block-heading">Step 7: Run a SELECT Query to Retrieve the Records.</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cursor.execute('SELECT * FROM PeopleInfo')
for row in cursor:
    print(row)
</pre>



<h2 class="wp-block-heading">Step 8: Close Your Connection If It Isn&#8217;t Needed.</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">conn.close()</pre>



<p class="wp-block-paragraph">Database connections are an expensive resource and there might be limited connections available to your database.&nbsp; Remember to close your connection explicitly if you are not using a “with“ block as explained in Step 5.</p>



<p class="wp-block-paragraph"><strong>Complete code:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pyodbc
conn = pyodbc.connect('Driver={SQLite3 ODBC Driver};'
                      'Server=localhost;'
                      'Database=testDB.db;'
                      'Trusted_Connection=yes;')
cursor = conn.cursor()
cursor.execute('''
 CREATE TABLE PeopleInfo (
        PersonId INTEGER PRIMARY KEY,
        FirstName TEXT NOT NULL,
        LastName  TEXT NOT NULL,
        Age INTEGER NULL,
        CreatedAt TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL
 
);

               ''')
conn.commit()

cursor.execute('''
                INSERT INTO PeopleInfo (PersonId, FirstName, LastName, Age)
                VALUES
                (1,'Bob','Smith', 55),
                (2, 'Jenny','Smith', 66)
                ''')
conn.commit()

cursor.execute('SELECT * FROM PeopleInfo ')
for row in cursor:
    print(row)

conn.close()
</pre>



<p class="wp-block-paragraph"><strong>Output:</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">(1, 'Bob', 'Smith', 55, '2020-08-01 20:37:04')
(2, 'Jenny', 'Smith', 66, '2020-08-01 20:37:04')</pre>



<h2 class="wp-block-heading">References</h2>



<p class="wp-block-paragraph">1 &#8211; Pyodbc Github repo: <a href="https://github.com/mkleehammer/pyodbc" target="_blank" rel="noreferrer noopener">https://github.com/mkleehammer/pyodbc</a></p>



<p class="wp-block-paragraph">2 &#8211; Pyodbc Getting Started: <a href="https://code.google.com/archive/p/pyodbc/wikis/GettingStarted.wiki" target="_blank" rel="noreferrer noopener">https://code.google.com/archive/p/pyodbc/wikis/GettingStarted.wiki</a></p>



<p class="wp-block-paragraph">3 &#8211; Create tables with SQLite: <a rel="noreferrer noopener" href="https://www.sqlitetutorial.net/sqlite-create-table/" target="_blank">https://www.sqlitetutorial.net/sqlite-create-table/</a></p>



<p class="wp-block-paragraph">4 &#8211; Write table into a CSV file: <a href="https://blog.finxter.com/how-to-convert-access-accdb-table-to-a-csv-in-python/" target="_blank" rel="noreferrer noopener">https://blog.finxter.com/how-to-convert-access-accdb-table-to-a-csv-in-python/</a></p>



<h2 class="wp-block-heading">Programming Humor</h2>



<p class="has-global-color-8-background-color has-background wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.</p>



<p class="wp-block-paragraph">~~~</p>



<ul class="has-global-color-8-background-color has-background wp-block-list"><li><strong>Question</strong>: Why do Java programmers wear glasses?</li><li><strong>Answer</strong>: Because they cannot C# &#8230;!</li></ul>



<p class="wp-block-paragraph">Feel free to check out <a href="https://blog.finxter.com/what-is-the-geekiest-joke/" data-type="post" data-id="617" target="_blank" rel="noreferrer noopener">our blog article</a> with more coding jokes. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-11-10 07:14:53 by W3 Total Cache
-->