Search

Series List Filter

How to Implement a Python Stack

Whether you want to reverse a string or create a language processing application, stacks are very useful. It can be used to solve a wide variety of problems. In fact most of the programming languages including the operating systems are dependent on stack to function.The name Stack data structure totally resembles a pile of objects, stack of papers, or a tower of blocks, where adding and removing of items occur only at the top of the pile. It is similar to removing a quarter in the middle of a stack of coins without destroying the entire thing. In this article we will understand stack operations and look into the various ways to implement stack in Python. You may also get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is a Stack?A Stack is an abstract linear data type that serves as a collection of objects. Unlike queues, they use the Last In First Out or LIFO  technique to insert and delete elements. The insert and delete operations are referred to as push and pop in stack.Stacks and Queues are both linear collections of items. However, in a queue, the least recently added item is removed first, following the First In First Out or FIFO  manner. On the other hand, in a stack, the most recently added item is removed in the beginning following the LIFO. Stack stores the data elements in a similar fashion as a bunch of plates that are kept one above the other in a kitchen. It allows operations (push or pop) only from one end, often called as top. You can add or remove elements only from the top of the stack.A real-life example of a stack is a pile of heavy and precious plates, all kept on top of the other. If you wish to add a plate or remove one, you can do that only from the top. However, if you want to remove a lower plate from the stack, you have to remove the topmost plates one by one, in order to remove the desired one. Other examples are a deck of cards or a pile of books etc.What are the basic operations performed in Stack?Basic Operations performed in Stack - Push, POP, PeekThe basic operations which are performed in the stack are mentioned below:Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.Peek or Top: Returns top element of stack.isEmpty: Returns true if stack is empty, else false.Applications of StackStacks are considered as the backbone of Data Structures. Most of the algorithms and applications are implemented using stacks.Some of the key applications of stacks are—They are used to reverse a string. Each of the characters are pushed in and then popped off, which results in a reversed string.It is used in Expression Evaluation and Expression Conversion (infix to postfix, infix to prefix, postfix to infix, prefix to infix).It is used for forward and backward features in web browsers.It is used for recursive parsing in Natural Language Processing.It is used in syntax parsing and parenthesis checking.It is used for Backtracking like finding paths to a maze or exhaustive searching.It is used in Algorithms like Tower of Hanoi, tree traversals, histogram problem and also in graph algorithms like Topological Sorting.Understanding Stack OperationsThere are mainly two types of primitive stack operations:Push: It is performed to insert and store an element in the stack. However, when you try to insert an element in a stack which is full, the Overflow condition occurs.Pop: It is used to remove an element from the stack. However, when the stack is empty, the Underflow condition occurs.PushLet’s consider editing a Python file using the undo feature in your editor so you can have a clear understanding of the stack operations. At first, a new function called Insert is added. The push operation adds the Insert function into the stack:Now, a word Delete is removed from any of the comments. This word also gets added to the stack:The Delete is added to the top of the stack. Finally, let us indent a Comment to align things appropriately which is also inserted into the stack:Note that the commands entered are all stored in the stack just like a pile with each command on top of the other. This operation of adding new elements into the stack is called push.PopNow to perform the pop operations, let us make use of the undo feature. When we first hit the undo, it removes the top-most element of the stack (here, which is Comment):The editor removes the indented Comment and the stack is now left with two commands. When the next undo is hit again, the next command is removed from the stack:Now Delete is also removed and the stack is left with only one operation. When the undo is hit again, the last element remaining in the stack is also popped off and the stack becomes empty as it was in the first place:Since the stack is now empty, if we again hit undo, it will result into an Underflow condition causing no effect.Implementing Stack in PythonPython gives you a lot of options for implementing a Python stack. You can do so by using lists, tuples or by using third-party modules or packages. However, there are some basic implementations of Python stack that will fulfil most of your needs.Some of those implementations are as follows:listcollections.dequequeue.LifoQueueUsing ListList is a built-in structure that can be used as stack in Python. We use lists often to write Python programs. They are implemented as internal dynamic arrays in Python which means whenever elements are added or removed, the storage area is resized every time accordingly.You can use .append() to add elements and .pop() to remove them:>>> my_first_stack = [] >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack ['Alex', 'Bob', 'Charlie'] >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> my_first_stack.pop() Traceback (most recent call last):   File "<#pyshell>", line 1, in <module> IndexError: pop from empty listNotice that an IndexError is raised. This is because .pop() is called on an empty stack.Though lists work very efficiently in implementing stacks, yet it comes with some drawbacks. There might be situations where your stack might grow bigger than the current block of memory  it holds. Since lists are used for faster access to random elements, in such situations, speed issues occur. Python starts allocating memory implicitly which leads to longer .append() calls.Speed issues also occur when you use .insert() to add elements in your stack.Using ArrayIt is quite easy to implement stack using Python Lists. However, you can implement stack using arrays as well if you assume that lists are like arrays. You can follow the algorithm mentioned below to understand how it works.Algorithm:Declare a list and an integer MaxSize, and denote the maximum size of the StackInitially set the Top to 0.Push operation:Check if the MaxSize of the Stack is greater than TopIf yes, append data to stack and increase top by 1If no, print stack full messagePop operation:Check if Top is greater than 0:If yes, pop the last element from the list and decrement top by 1If no, print stack empty messageSize operation: The size of the Stack is the value of the Top pointer.class Stack:     #Constructor     def __init__(self):         self.stack = list()         self.maxSize = 8         self.top = 0     #Adds element to the Stack     def push(self,data):         if self.top>=self.maxSize:             return ("Stack Full!")         self.stack.append(data)         self.top += 1         return True     #Removes element from the stack     def pop(self):         if self.top<=0:             return ("Stack Empty!")         item = self.stack.pop()         self.top -= 1         return item             #Size of the stack     def size(self):         return self.top s = Stack() print(s.push(1))#prints True print(s.push(2))#prints True print(s.push(3))#prints True print(s.push(4))#prints True print(s.push(5))#prints True print(s.push(6))#prints True print(s.push(7))#prints True print(s.push(8))#prints True print(s.push(9))#prints Stack Full! print(s.size())#prints 8       print(s.pop())#prints 8 print(s.pop())#prints 7 print(s.pop())#prints 6 print(s.pop())#prints 5 print(s.pop())#prints 4 print(s.pop())#prints 3 print(s.pop())#prints 2 print(s.pop())#prints 1 print(s.pop())#prints Stack Empty!Note: Element 9 was not added and hence size remains 8.Using collections.dequePython contains a module named collections. This comprises of the deque class which is a double-ended queue that supports inserting and removing elements from either ends.The method of deque is similar to the lists:>>> from collections import deque >>> my_first_stack = deque() >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack deque(['Alex', 'Bob', 'Charlie']) >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> myStack.pop() Traceback (most recent call last):   File "<#pyshell>", line 1, in <module> IndexError: pop from an empty dequeThe objects of the deque class has a consistent performance because they are implemented in the form of doubly linked lists.Using queue.LifoQueueThe Python Standard Library comprises of another class called queue.LifoQueue class to implement stack. It supports multiple simultaneous producers and consumers.Python Threading is used for executing multiple tasks and function calls at the same time and independently of other codes. If your program involves threads, it is recommended not to use list and deque because they behave very differently in such cases.list is not thread-safe. On the other hand, though, .append() and .pop() are atomic in nature, it is nearly impossible to build a Python stack using deque that is fully thread-safe. This is because of the reason that in a threaded environment, there are other deque class methods that are neither atomic nor they are thread-safe and might lead to race conditions.So the last option we’re left with is the queue.LifoQueue class that is specially designed to be fully thread-free.Adding and removing elements are performed in this class are using .put() and .get():>>> from queue import LifoQueue >>> my_first_stack = LifoQueue() >>>my_first_stack.put('Alex') >>>my_first_stack.put('Bob') >>>my_first_stack.put('Charlie') >>> my_first_stack <queue.LifoQueue object at 0x0000026E4C69DFD0> >>> my_first_stack.get() 'Charlie' >>> my_first_stack.get() 'Bob' >>> my_first_stack.get() 'Alex' >>> my_first_stack.get_nowait() Traceback (most recent call last):   File "<pyshell#8>", line 1, in <module>     my.get_nowait() _queue.Empty >>> my_first_stack.get()  # Waits foreverThe queue module might be helpful when you are working with multiple threads or with parallel computing. However, for general purpose stack implementation, it is recommended to use lists or deque.deque: An excellent choice for implementing a Python StackIf you’re not interested in handling explicit locking and unlocking and also not looking for parallel processing support, then your choice for choosing the right Python stack implementation narrows down to list and deque. However, they both have different implementations of data structures in their working.Operations like indexing and slicing work very well with lists because it is built upon contiguous blocks of memory. The elements in the list are stored in a dynamic array system making it easier for Python to find any element in the memory.However, this type of layout system raises speed issues in situations like when the contiguous block is full, it needs to get another block which in turn increases the execution time.On the other hand, deque is a doubly linked list in which each entry is linked to both the previous and next entry in the list. This allows adding elements to both the ends of the list. In this type of linked list, each memory has its own memory block. Thus, combining all these reasons, deque is a much better choice than list when implementing stacks in Python.ConclusionLet us sum up what we’ve learnt in this article so far:What is a Stack and what are its applications.What do Stack operations look like.When should a data structure like Stack be used.Different ways of implementing Stack in Python.How to select the right implementation depending upon your problem.Stacks are simple data structures that allows us to store and retrieve data in a sequential fashion. They are very useful in real world cases. Having a clear understanding of stacks would help us in solving data storage problems in an efficient manner.If you wish to know more about data structures and other aspects of Python, you can go through the Python tutorial. You may also join the certification course on Python.
Rated 4.5/5 based on 1 customer reviews

How to Implement a Python Stack

7637
How to Implement a Python Stack

Whether you want to reverse a string or create a language processing application, stacks are very useful. It can be used to solve a wide variety of problems. In fact most of the programming languages including the operating systems are dependent on stack to function.

The name Stack data structure totally resembles a pile of objects, stack of papers, or a tower of blocks, where adding and removing of items occur only at the top of the pile. It is similar to removing a quarter in the middle of a stack of coins without destroying the entire thing. In this article we will understand stack operations and look into the various ways to implement stack in Python. You may also get certified and learn more about Python Programming and apply those skills and knowledge in the real world.

What is a Stack?

A Stack is an abstract linear data type that serves as a collection of objects. Unlike queues, they use the Last In First Out or LIFO  technique to insert and delete elements. The insert and delete operations are referred to as push and pop in stack.

Stacks and Queues are both linear collections of items. However, in a queue, the least recently added item is removed first, following the First In First Out or FIFO  manner. On the other hand, in a stack, the most recently added item is removed in the beginning following the LIFO

Stack stores the data elements in a similar fashion as a bunch of plates that are kept one above the other in a kitchen. It allows operations (push or pop) only from one end, often called as top. You can add or remove elements only from the top of the stack.

A real-life example of a stack is a pile of heavy and precious plates, all kept on top of the other. If you wish to add a plate or remove one, you can do that only from the top. However, if you want to remove a lower plate from the stack, you have to remove the topmost plates one by one, in order to remove the desired one. Other examples are a deck of cards or a pile of books etc.

What are the basic operations performed in Stack?

The basic operations performed in Stack are Push, POP and PeekBasic Operations performed in Stack - Push, POP, Peek

The basic operations which are performed in the stack are mentioned below:

  • Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.
  • Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.
  • Peek or Top: Returns top element of stack.
  • isEmpty: Returns true if stack is empty, else false.

Applications of Stack

Stacks are considered as the backbone of Data Structures. Most of the algorithms and applications are implemented using stacks.

Some of the key applications of stacks are—

  • They are used to reverse a string. Each of the characters are pushed in and then popped off, which results in a reversed string.
  • It is used in Expression Evaluation and Expression Conversion (infix to postfix, infix to prefix, postfix to infix, prefix to infix).
  • It is used for forward and backward features in web browsers.
  • It is used for recursive parsing in Natural Language Processing.
  • It is used in syntax parsing and parenthesis checking.
  • It is used for Backtracking like finding paths to a maze or exhaustive searching.
  • It is used in Algorithms like Tower of Hanoi, tree traversals, histogram problem and also in graph algorithms like Topological Sorting.

Understanding Stack Operations

There are mainly two types of primitive stack operations:

  • Push: It is performed to insert and store an element in the stack. However, when you try to insert an element in a stack which is full, the Overflow condition occurs.
  • Pop: It is used to remove an element from the stack. However, when the stack is empty, the Underflow condition occurs.

Push

Let’s consider editing a Python file using the undo feature in your editor so you can have a clear understanding of the stack operations. At first, a new function called Insert is added. The push operation adds the Insert function into the stack:

Insert function into the stack using push operation

Now, a word Delete is removed from any of the comments. This word also gets added to the stack:

adding delete word to the stack by push operation

The Delete is added to the top of the stack. Finally, let us indent a Comment to align things appropriately which is also inserted into the stack:

Indenting "comment" to the stack using Push operation

Note that the commands entered are all stored in the stack just like a pile with each command on top of the other. This operation of adding new elements into the stack is called push.

Pop

Now to perform the pop operations, let us make use of the undo feature. When we first hit the undo, it removes the top-most element of the stack (here, which is Comment):

First undo removes the top-most element of the stack

The editor removes the indented Comment and the stack is now left with two commands. When the next undo is hit again, the next command is removed from the stack:

The next undo will remove the next command from the stack, which is called POP operation

Now Delete is also removed and the stack is left with only one operation. When the undo is hit again, the last element remaining in the stack is also popped off and the stack becomes empty as it was in the first place:

The last undo will remove the last element of the stack and the stack becomes empty. This removal of elements from a stack is called POP operation

Since the stack is now empty, if we again hit undo, it will result into an Underflow condition causing no effect.

Implementing Stack in Python

Python gives you a lot of options for implementing a Python stack. You can do so by using lists, tuples or by using third-party modules or packages. However, there are some basic implementations of Python stack that will fulfil most of your needs.

Some of those implementations are as follows:

  • list
  • collections.deque
  • queue.LifoQueue

Using List

List is a built-in structure that can be used as stack in Python. We use lists often to write Python programs. They are implemented as internal dynamic arrays in Python which means whenever elements are added or removed, the storage area is resized every time accordingly.

You can use .append() to add elements and .pop() to remove them:

>>> my_first_stack = []
>>> my_first_stack.append('Alex')
>>> my_first_stack.append('Bob')
>>> my_first_stack.append('Charlie')
>>> my_first_stack
['Alex', 'Bob', 'Charlie']
>>> my_first_stack.pop()
'Charlie'
>>> my_first_stack.pop()
'Bob'
>>> my_first_stack.pop()
'Alex'
>>> my_first_stack.pop()
Traceback (most recent call last):
  File "<#pyshell>", line 1, in <module>
IndexError: pop from empty list

Notice that an IndexError is raised. This is because .pop() is called on an empty stack.

Though lists work very efficiently in implementing stacks, yet it comes with some drawbacks. There might be situations where your stack might grow bigger than the current block of memory  it holds. Since lists are used for faster access to random elements, in such situations, speed issues occur. Python starts allocating memory implicitly which leads to longer .append() calls.

Speed issues also occur when you use .insert() to add elements in your stack.

Using Array

It is quite easy to implement stack using Python Lists. However, you can implement stack using arrays as well if you assume that lists are like arrays. You can follow the algorithm mentioned below to understand how it works.

Algorithm:

  1. Declare a list and an integer MaxSize, and denote the maximum size of the Stack
  2. Initially set the Top to 0.
  3. Push operation:
    • Check if the MaxSize of the Stack is greater than Top
      • If yes, append data to stack and increase top by 1
      • If no, print stack full message
  4. Pop operation:
    • Check if Top is greater than 0:
      • If yes, pop the last element from the list and decrement top by 1
      • If no, print stack empty message
  5. Size operation: The size of the Stack is the value of the Top pointer.
class Stack:
    #Constructor
    def __init__(self):
        self.stack = list()
        self.maxSize = 8
        self.top = 0
    #Adds element to the Stack
    def push(self,data):
        if self.top>=self.maxSize:
            return ("Stack Full!")
        self.stack.append(data)
        self.top += 1
        return True
    #Removes element from the stack
    def pop(self):
        if self.top<=0:
            return ("Stack Empty!")
        item = self.stack.pop()
        self.top -= 1
        return item
       
    #Size of the stack
    def size(self):
        return self.top

s = Stack()
print(s.push(1))#prints True
print(s.push(2))#prints True
print(s.push(3))#prints True
print(s.push(4))#prints True
print(s.push(5))#prints True
print(s.push(6))#prints True
print(s.push(7))#prints True
print(s.push(8))#prints True
print(s.push(9))#prints Stack Full!
print(s.size())#prints 8      
print(s.pop())#prints 8
print(s.pop())#prints 7
print(s.pop())#prints 6
print(s.pop())#prints 5
print(s.pop())#prints 4
print(s.pop())#prints 3
print(s.pop())#prints 2
print(s.pop())#prints 1
print(s.pop())#prints Stack Empty!

Note: Element 9 was not added and hence size remains 8.

Using collections.deque

Python contains a module named collections. This comprises of the deque class which is a double-ended queue that supports inserting and removing elements from either ends.

The method of deque is similar to the lists:

>>> from collections import deque
>>> my_first_stack = deque()
>>> my_first_stack.append('Alex')
>>> my_first_stack.append('Bob')
>>> my_first_stack.append('Charlie')
>>> my_first_stack
deque(['Alex', 'Bob', 'Charlie'])
>>> my_first_stack.pop()
'Charlie'
>>> my_first_stack.pop()
'Bob'
>>> my_first_stack.pop()
'Alex'
>>> myStack.pop()
Traceback (most recent call last):
  File "<#pyshell>", line 1, in <module>
IndexError: pop from an empty deque

The objects of the deque class has a consistent performance because they are implemented in the form of doubly linked lists.

Using queue.LifoQueue

The Python Standard Library comprises of another class called queue.LifoQueue class to implement stack. It supports multiple simultaneous producers and consumers.

Python Threading is used for executing multiple tasks and function calls at the same time and independently of other codes. If your program involves threads, it is recommended not to use list and deque because they behave very differently in such cases.

list is not thread-safe. On the other hand, though, .append() and .pop() are atomic in nature, it is nearly impossible to build a Python stack using deque that is fully thread-safe. This is because of the reason that in a threaded environment, there are other deque class methods that are neither atomic nor they are thread-safe and might lead to race conditions.

So the last option we’re left with is the queue.LifoQueue class that is specially designed to be fully thread-free.

Adding and removing elements are performed in this class are using .put() and .get():

>>> from queue import LifoQueue
>>> my_first_stack = LifoQueue()
>>>my_first_stack.put('Alex')
>>>my_first_stack.put('Bob')
>>>my_first_stack.put('Charlie')
>>> my_first_stack
<queue.LifoQueue object at 0x0000026E4C69DFD0>
>>> my_first_stack.get()
'Charlie'
>>> my_first_stack.get()
'Bob'
>>> my_first_stack.get()
'Alex'
>>> my_first_stack.get_nowait()
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    my.get_nowait()
_queue.Empty
>>> my_first_stack.get()  # Waits forever

The queue module might be helpful when you are working with multiple threads or with parallel computing. However, for general purpose stack implementation, it is recommended to use lists or deque.

deque: An excellent choice for implementing a Python Stack

If you’re not interested in handling explicit locking and unlocking and also not looking for parallel processing support, then your choice for choosing the right Python stack implementation narrows down to list and deque. However, they both have different implementations of data structures in their working.

Operations like indexing and slicing work very well with lists because it is built upon contiguous blocks of memory. The elements in the list are stored in a dynamic array system making it easier for Python to find any element in the memory.

However, this type of layout system raises speed issues in situations like when the contiguous block is full, it needs to get another block which in turn increases the execution time.

On the other hand, deque is a doubly linked list in which each entry is linked to both the previous and next entry in the list. This allows adding elements to both the ends of the list. In this type of linked list, each memory has its own memory block. Thus, combining all these reasons, deque is a much better choice than list when implementing stacks in Python.

Conclusion

Let us sum up what we’ve learnt in this article so far:

  • What is a Stack and what are its applications.
  • What do Stack operations look like.
  • When should a data structure like Stack be used.
  • Different ways of implementing Stack in Python.
  • How to select the right implementation depending upon your problem.

Stacks are simple data structures that allows us to store and retrieve data in a sequential fashion. They are very useful in real world cases. Having a clear understanding of stacks would help us in solving data storage problems in an efficient manner.

If you wish to know more about data structures and other aspects of Python, you can go through the Python tutorial. You may also join the certification course on Python.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

1 comments

Nilesh 16 Aug 2019

Excellent article on how to implement a python stack thanks for the useful information.

Suggested Blogs

How to Build a Python GUI Application With wxPython

A Graphical User Interface or GUI is a user interface that includes graphical elements that enable a person to communicate with electronic devices like computers, hand-held devices, and other appliances. It displays information using icons, menus, and graphics. They are handled with the help of a pointing device such as a mouse, trackball or a stylus.A GUI is basically an application that has windows, buttons and lots of other widgets that allows a user to interact with your application. A web browser is a common example of a GUI that has buttons, tabs, and the main window and where the content is displayed.It was developed by the Xerox Palo Alto research laboratory in the late 1970s. Today, every OS has its own GUI. Software applications make use of these and develop their own GUIs.Python contains many GUI toolkits, out which Tkinter, wxPython, and PyQt are the important ones. All these toolkits have the ability to work with Windows, macOS, and Linux with the additional quality of working on mobile phones.How to get started with wxPython?wxPython was first released in the year 1998. It is an open-source cross-platform Python GUI toolkit used as a wrapper class around a C++ library called wxWidgets. The main feature of wxPython which distinguishes itself from other toolkits like PyQt and Tkinter is that it uses actual widgets on the native platform where required. This allows the wxPython applications to look native to the operating system in which it is running.The wxPython toolkit contains a lot of core widgets along with many custom widgets which you can download from the Extra Files section of the wxPython official page.Here, there is a download of the wxPython demo package which is an application demonstrating the robustness of the widgets included with wxPython. The main advantage of this demo is that you can view it one tab and run it in another and it also allows to edit and re-run the code to observe the changes.Installing wxPythonYou will be using the latest wxPython release, wxPython 4, which is also called the wxPython’s Project Phoenix. It is a new implementation of wxPython that aims at improving the speed, maintainability, and extensibility of wxPython. The wxPython 3 and wxPython 2 were built only for Python 2. The maintainer of wxPython rejected a lot of aliases and cleaned up a lot of code to make wxPython more easy and Pythonic.If you are migrating from an older version of wxPython to wxPython 4, take a look at the following references:Classic version vs project PhoenixPhoenix Migration GuideThe Phoenix version is compatible with both Python 2.7 and Python 3. You can use pip to install wxPython 4:$ pip install wxpythonYou will get a prerequisites section on the Github page of wxPython which will provide information to install wxPython on Linux systems.You can also look into the Extras Linux section to learn about the Python wheels for both GTK2 and GTK3 versions. To install one of the wheels, use the command below:$ pip install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04/ wxPythonRemember to modify the command to match with the version of Linux.Components of GUIAs mentioned earlier, GUI is nothing but an interface that allows user interaction.Common components of the user interfaces:Main Window.Menu.Toolbar.Buttons.Text Entry.Labels.These items are generally known as widgets. wxPython supports many other common widgets and many custom widgets that are arranged in a logical manner by a developer to allow user interaction.Event LoopsA GUI works by waiting for the user to perform an action. This is known as an event. An event occurs when something is typed by the user or when the user uses their mouse to press a button or some widget while the application is in focus.The GUI toolkit runs an infinite loop called an event loop underneath the covers. The task of the event loop is to act on occurred events on the basis of what the developer has coded the application to do. The application ignores the event when it is not able to catch it.When you are programming a graphical user interface, make sure to attach the widgets to event handlers in order to make your application do something.You can also block an event loop to make the GUI unresponsive which will appear to freeze to the user. This is a special consideration for you to keep in mind while working with event loops. Launch a special thread or process whenever a GUI takes longer than a quarter of a second to launch a process.The frameworks of wxPython contain special thread-safe methods that you can use to communicate back to your application. This informs the thread is finished or given an update.How to create a Skeleton Application?An application skeleton is basically used for prototyping. It is a user interface comprising of widgets that do not contain event handlers. You just need to create the GUI and show it to the stakeholders for signing off and avoid spending time on the backend logic.An example of creating a Hello World application with Python:import wx   application = wx.App() framework = wx.Frame(parent=None, title='Hello World') framework.Show() app.MainLoop()In the example above, there are two parts of the program – wx.App and wx.Frame. The former one is wxPython’s application object which is basically required for running the GUI. It initiates the .MainLoop() which is the event loop you have learned earlier.The latter part creates a window for user interaction. It informs wxPython that the frame has no parent and its title is Hello World. If you run the code above, this is how it will look like:The application will look different if you execute it in Mac or Linux.Note: Mac users may get the following message: This program needs access to the screen. Please run with a Framework build of Python, and only when you are logged in on the main display of your Mac. If you see this message and you are not running in a virtualenv, then you need to run your application with pythonw instead of python. If you are running wxPython from within a virtualenv, then see the wxPython wiki for the solution.The minimize, maximize and exit will be included in the wx.Frame by default. However, most wxPython code will require you to make the wx.Frame as a subclass and other widgets in order to grab the full power of the toolkit.Let us rewrite the code using class:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World') self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()This code can be used as a template for your application.Widgets in wxPythonThe wxPython toolkit allows you to create rich applications from more than one hundred widgets. But it can be very daunting to choose the perfect widget from such a large number, so wxPython has included a wxPython Demo which contains a search filter which will help you to find the right widget from the list.Now, let us add a button and allow the user to enter some text by adding a text field:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)   self.text_ctrl = wx.TextCtrl(panel, pos=(5, 5)) my_button = wx.Button(panel, label='Press Me', pos=(5, 55))   self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()When you run the code, the application will look like this:The first widget that is recommended on Windows is wx.Panel. It makes the background color of the frame as the right shade of gray. Tab traversal is disabled without a Panel on Windows.If the panel is the sole child of the frame, it will be expanded automatically to fill the frame with itself. The next thing you need to do is to add a wx.TextCtrl to the panel. The first argument is always that which parent the widget should go to for almost all widgets. So if you are willing to keep the text control and the button on the top of the panel, it is the parent you need to specify.You also need to inform wxPython about the position of the widget. You can do it using the pos parameter. The default location is (0,0) which is actually at the upper left corner of the parent. So to change the text control, you can change the position of the frame, you can shift its left corner 5 pixels from the left(x) and 5 pixels from the top(y). Finally, you can add your button to the panel and label it. You can also set the y-coordinate to 55 to prevent the overlapping of widgets.Absolute PositioningAbsolute positioning is the technique found in most GUI toolkits by which you can provide the exact coordinates for your widget’s position.There might be situations when you need to keep track of all your widgets and relocate the widgets in case of a complex application. This can be a really difficult thing to do. However, most modern-day toolkits provide a solution for this, which we’ll study next.Sizers (Dynamic Sizing)Sizers are methods to define the control layout in dialogs in wxPython. They have the ability to create dialogs that are not dependent on the platform. They manage the positioning of the widgets and adjust them when the user resizes the application window.Some of the primary types of sizers that are commonly used are:wx.BoxSizerwx.GridSizerwx.FlexGridSizerAn example code to add wx.BoxSizer to the previous code:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5)         my_button = wx.Button(panel, label='Press Me') my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)         panel.SetSizer(my_sizer)         self.Show()   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop() In the example above, an instance of wx.BoxSixer is created and passed to wx.VERTICAL which is actually the orientation that widgets are included in the sizer. The widgets will be added in a vertical manner from top to bottom. You can also set the BoxSizer’s orientation to wx.HORIZONTAL. In this case, the widgets are added from left to right.  You can use .Add() to a widget to a sizer which takes maximum five arguments as follows: window ( the widget )- This is the widget that is added to the sizer. proportion - It sets how much space corresponding to other widgets in the sizer will the widget should take. By default, the proportion is zero which leaves the wxPython to its original proportion. flag - It allows you to pass in multiple flags by separating them with a pipe character: |. The text control is added using wx.ALL and wx.EXPAND flags. The wx.ALL flag adds a border on all sides of the widget. On the other hand, wx.EXPAND expands the widgets as much as the sizer can be expanded. border - This parameter informs wxPython about the number of pixels of border needed around the widget.  userData - It is a rare argument that is used for resizing in case of complex applications. However, in this example, the wx.EXPAND flag is replaced with wx.CENTER to display the button in the center on-screen. When you run the code, your application will look something like this:Adding an event using wxPython Though your application looks cool, but it really does nothing. The button you have created does nothing on pressing it. Let us give the button a job:import wx   class MyFramework(wx.Frame):     def frame(self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl, 0, wx.ALL | wx.EXPAND, 5)         my_button = wx.Button(panel, label='Press Me') my_button.Bind(wx.EVT_BUTTON, self.on_press) my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)         panel.SetSizer(my_sizer)         self.Show()   def button_press(self, event):         value = self.text_ctrl.GetValue()         if not value:             print("You didn't enter anything!")        else:             print(f'You typed: "{value}"')   if __name__ == '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop() You can attach event bindings to the widgets in wxPython. This allows them to respond to certain types of events.If you want the button to do something, you can do it using the button’s .Bind() method. It takes the events you want to bind to, the handler to call an event, an optional source, and a number of optional ids. In the example above, the button object is binded to wx.EVT_BUTTON and told to call button_press when the event gets fired..button_press also accepts a second argument by convention that is called event. The event parameter suggests that the second argument should be an event object.You can get the text control’s contents with the help of GetValue() method within .button_press.How to create a Working Application?Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.If you make a Google search for Python mp3 tag editor, you will find several options as below:mp3 -taggereyeD3mutagenOut of these, eyeD3 is a better choice than the other two since it has a pretty nice API that can be used without getting bogged down with MP3’s ID3 specification.You can install eyeD3 using pip from your terminal:pip install eyed3If you want to install eyeD3 in macOS, you have to install libmagic using brew. Linux and Windows users can easily install using the command mentioned above.Designing the User Interface using wxPythonThe very first thing you must do before designing an interface is to sketch out how you think the interface should look.The user interface should perform the following tasks:Open up one or more MP3 files.Display the current MP3 tags.Edit an MP3 tag.If you want to open a file or a folder, you need to have a menu or a button in your user interface. You can do that with a File menu. You will also need a widget to see the tags for multiple MP3 files. A tabular structure consisting of columns and rows would be perfect for this case since you can have labeled columns for the MP3 tags. wxPython toolkit consists of afew widgets to perform this task:wx.grid.Gridwx.ListCtrlwx.ListCtrl would be a better option of these two since the Grid widget is overkill and complex in nature. Finally, you can use a button to perform the editing tasks.Below is an illustration of what the application should look like:Creating the User Interface You can refer to a lot of approaches when you are creating a user interface. You can follow the Model-View-Controller design pattern that is used for developing user interfaces which divides the program logic into three interconnected elements. You should know how to split up classes and how many classes should be included in a single file and so on.However, in this case, you need only two classes which are as follows:wx.Panel classwx.Frame class Let’s start with imports and the panel class:import eyed3 import glob import wx   class Mp3Panel(wx.Panel):     def frame(self, parent):         super().__init__(parent) main_sizer = wx.BoxSizer(wx.VERTICAL) self.row_obj_dict = {}   self.list_ctrl = wx.ListCtrl(             self, size=(-1, 100),               style=wx.LC_REPORT | wx.BORDER_SUNKEN         ) self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) main_sizer.Add(self.list_ctrl, 0, wx.ALL | wx.EXPAND, 0)         edit_button = wx.Button(self, label='Edit') edit_button.Bind(wx.EVT_BUTTON, self.on_edit) main_sizer.Add(edit_button, 0, wx.ALL | wx.CENTER, 5)         self.SetSizer(main_sizer)   def on_edit(self, event):         print('in on_edit')   def update_mp3_listing(self, folder_path):         print(folder_path)In this example above, the eyed3 package, glob package, and the wx package are imported. Then, the user interface is created by making wx.Panel a subclass. A dictionary row_obj_dict is created for storing data about the MP3s. The next thing you do is create a wx.ListCtrl and set it to report mode, i.e. wx.LC_REPORT. This report flag is the most popular among all but you can also choose your own depending upon the style flag that you pass in. Now you need to call .InsertColumn() to make the ListCtrl have the correct headers and then provide the index of the column, its label and the width of the column pixels. Finally, you need to add your Edit button, an event handler, and a method. The code for the frame is as follows:class Mp3Frame(wx.Frame):     def__init__(self):         super().__init__(parent=None,                          title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.Show()   if __name__ == '__main__':     app = wx.App(False)     frame = Mp3Frame() app.MainLoop()This class function is a better and simpler approach than the previous one because you just need to set the title of the frame and instantiate the panel class, MP3Panel. The user interface will look like this after all the implementations:The next thing we will do is add a File menu to add MP3s to the application and also edit their tags.Make a Functioning ApplicationThe very first thing you need to do to make your application work is to update the wx.Frame class to include the File menu which will allow you to add MP3 files.Code to add a menu bar to our application:class Mp3Frame(wx.Frame):   def__init__(self):         wx.Frame.__init__(self, parent=None,                             title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.create_menu() self.Show()   def create_menu(self): menu_bar = wx.MenuBar() file_menu = wx.Menu() open_folder_menu_item = file_menu.Append( wx.ID_ANY, 'Open Folder',   'Open a folder with MP3s'         ) menu_bar.Append(file_menu, '&File') self.Bind(             event=wx.EVT_MENU,               handler=self.on_open_folder,             source=open_folder_menu_item,         ) self.SetMenuBar(menu_bar)   def on_open_folder(self, event):         title = "Choose a directory:" dlg = wx.DirDialog(self, title,                              style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK:             self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy() In the example code above, .create_menu() is called within the class’s constructor and then two instances – wx.MenuBar and wx.Menu are created.Now, if you’re willing to add an item to the menu, you need to call the menu instance’s .Append() and pass the following things:A unique identifierLabelA help stringAfter that call the menubar’s .Append() to add the menu to the menubar. It will take the menu instance and the label for menu. The label is called as &File so that a keyboard shortcut is created to open the File menu using just the keyboard.Now self.Bind() is called to bind the frame to wx.EVT_MENU. This informs wxPython about which handler should be used and which source to bind the handler to. Lastly, call the frame’s .SetMenuBar and pass it the menubar instance. Your menu is now added to the frame.Now let’s come back to the menu item’s event handler:def on_open_folder(self, event):     title = "Choose a directory:" dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK:         self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()You can use wxPython’s wx.DirDialog to choose the directories of the correct MP3 folder. To display the dialog, use .ShowModal(). This will display the dialog modally but will disallow the user to interact with the main application.  You can get to the user’s choice of path using .GetPath() whenever the user presses the OK button. This path has to be added to the panel class and this can be done by the panel’s .update_mp3_listing().Finally, you will have to close the dialog and the best method is using .Destroy().  There are methods to close the dialog like .Close() which will just dialog but will not destroy it, so .Destroy() is the most effective option to prevent such situation.Now let’s update the MP3Panel class starting with .update_mp3_listing():def update_mp3_listing(self, folder_path): self.current_folder_path = folder_path self.list_ctrl.ClearAll()   self.list_ctrl.InsertColumn(0, 'Artist', width=140) self.list_ctrl.InsertColumn(1, 'Album', width=140) self.list_ctrl.InsertColumn(2, 'Title', width=200) self.list_ctrl.InsertColumn(3, 'Year', width=200)       mp3s = glob.glob(folder_path + '/*.mp3')     mp3_objects = []     index = 0 for mp3 in mp3s:         mp3_object = eyed3.load(mp3) self.list_ctrl.InsertItem(index,               mp3_object.tag.artist) self.list_ctrl.SetItem(index, 1,               mp3_object.tag.album) self.list_ctrl.SetItem(index, 2,               mp3_object.tag.title)         mp3_objects.append(mp3_object) self.row_obj_dict[index] = mp3_object         index += 1In the example above, the current directory is set to the specified folder and the list control is cleared. The list controls stay fresh and shows the MP3s you’re currently working with. Next, the folder is taken and Python’s globmoduleis used to search for the MP3 files. Then, the MP3s are looped over and converted into eyed3 objects. This is done by calling the .load() of eyed3. After that, you can add the artist, album, and the title of the Mp3 to the control list given that the MP3s have the appropriate tags..InsertItem() is used to add a new row to a list control for the first time and SetItem()  is used to add rows to the subsequent columns. The last step is to save your MP3 object to your Python dictionary row_obj_dict.Now to edit an MP3’s tags, you need to update the .on_edit() event handler:def on_edit(self, event):     selection = self.list_ctrl.GetFocusedItem() if selection >= 0:         mp3 = self.row_obj_dict[selection] dlg = EditDialog(mp3) dlg.ShowModal()         self.update_mp3_listing(self.current_folder_path) dlg.Destroy()The user’s selection is taken by calling the list control’s .GetFocusedItem(). It will return -1 if the user will not select anything in the list control. However, if you want to extract the MP3 obj3ct from the dictionary, the user have to select something. You can then open the MP3 tag editor dialog which will be a custom dialog. As before, the dialog is shown modally, then the last two lines in .on_edit() will execute what will eventually display the current MP3 tag information. SummaryLet us sum up what we have learned in this article so far – Installing wxPython and Working with wxPython’s widgets Working of events in wxPython Comparing absolute positioning with sizers Creating a skeleton application and a working application The main feature of the wxPython Graphical User Interface is its robustness and a large collection of widgets that you can use to build cross-platform applications. Since you have now learned how to create a working application, that is an MP3 tag editor, you can try your hand to enhance this application to a more beautiful one with lots of new features or you can perhaps create your own wonderful application. To gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.
Rated 4.5/5 based on 2 customer reviews
5957
How to Build a Python GUI Application With wxPytho...

A Graphical User Interface or GUI is a user interf... Read More

How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python scripts and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not.Python, being one of the leading programming languages, has relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is the difference between Code, Script and Modules?In computing, the code is a language that is converted from a human language into a set of ‘words’ which the computer can understand. It is also referred to as a piece of statements together which forms a program. A simple function or a statement can also be considered a code.On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.In simple terms, a script is a simple program, stored in a plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file. A module is an object in Python with random attributes that you can bind and reference.Is Python a Programming Language or a Scripting Language?Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted. Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.However, considering the historical relationship between the general purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language which works nicely as a scripting language too.The Python InterpreterThe Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application which is responsible for running Python scripts.The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.Reads the command.Evaluates the command.Prints the result.Loops back and process gets repeated.The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.A Python Interpreter runs code in two ways— In the form of a script or module.In the form of a piece of code written in an interactive session.Starting the Python InterpreterThe simplest way to start the interpreter is to open the terminal and then use the interpreter from the command-line.To open the command-line interpreter:On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu → Run and type cmd.On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal. Running Python Code InteractivelyRunning Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.An example of how to do this on Windows:C:\users>python Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>>The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.The statements you write when working with an interactive session are evaluated and executed immediately:print('HELLO WORLD!') HELLO WORLD! 2 + 3 5 print('Welcome to the world of PYTHON') Welcome to the world of PYTHON The only disadvantage is when you close the interactive session, the code no longer exists.Running Python Scripts by the InterpreterThe term Python Execution Model is given to the entire multi-step process to run Python scripts.At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. Then the code is compiled into a form of instruction set called the bytecode.Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code which optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.Finally, the interpreter transfers the code for execution.The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component which actually runs your scripts.Running Python Scripts using Command-LineThe most sought after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:print('Hello World!')Then save the file in your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.Using python commandThe most basic and the easy way to run Python scripts is by using the python command. You need to open a command-line and type the word python followed by the path to your script file, like this:python first_script.py Hello World!Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.Redirecting outputWindows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.An example of how you can do this:python first_script.py > output.txtWhat happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.Running modules with the -m optionA module is a file which contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command  python -m . It searches the module name in the sys.path and runs the content as __main__:python -m first_script Hello World!Note that the module-name is a module object and not any string.Using Script FilenameWindows makes use of the system registers and file association to run Python scripts. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.An example on how to do this using command prompt:C:\Users\Local\Python\Python37> first_script.py Hello World!On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:#Assign the execution permissions chmod +x first_script.py #Run script using its filename ./first_script.py Hello World!However, if it doesn’t work, you might want to check if the script is located in your currentworking directory or not. Otherwise, you can use the path of the file for this method. Running Python Scripts InteractivelyAs we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.Using importImporting a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. An implementation of the import:import first_script Hello World!You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.One important thing to note is that the import option works only once per session. This is because these operations are expensive.For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.You can run the code below to know what’s in your current PSMP:import sys for path in sys.path: print(path)\Users\Local\Python37\Lib\idlelib \Users\Local\Python37\python37.zip \Users\Local\Python37\DLLs \Users\Local\Python37\lib \Users\Local\Python37 \Users\Local\Python37\lib\site-packagesYou’ll get the list of directories and .zip files where your modules and packages are imported.Using importlibimportlib is a module which is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.An example to perform this:import importlib importlib.import_module('first_script') Hello World! importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.The following code shows that:import first_script #First import Hello World! import first_script import importlib #Second import does nothing importlib.reload(first_script) Hello World! However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:importlib.reload(first_script)Traceback (most recent call last): ... ...   raise TypeError("reload() argument must be a module") TypeError: reload() argument must be a moduleUsing runpy.run_module() and runpy.run_path()The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. The module is located using import and then executed. The first argument of the run_module() must contain a string:import runpy runpy.run_module(mod_name='first_script') Hello World! {'__name__': 'first_script',     ... '_': None}}Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.An example of such is as follows:import runpy runpy.run_path(file_path='first_script.py') Hello World! {'__name__': '',     ... '_': None}}Both the functions return the globals dictionary of the executed module.Using exec()Other than the most commonly used ways to run Python scripts, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.An example of exec() is:exec(open('first_script.py').read()) Hello World!Using py_compilepy_compile is a module which behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.You can compile your Python script using this module:import py_compile py_compile.compile('first_script.py'  '__pycache__\\first_script.cpython-37.pyc' The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.Running Python Scripts using an IDE or a Text EditorAn Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.You can also use popular text editors like Sublime and Atom to run Python scripts.If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output in your screen.Running Python Scripts from a File ManagerIf you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.However, to achieve this, some conditions must be met:On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.If you are using the command-line for running your script, you might likely come  through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.So it is suggested to use this option only after the code is debugged and ready to be in the production market.ConclusionWorking with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality and so on. They are also used to automate complex tasks in a simplified manner.In this article, you have learned to run your Python scripts using:The terminal or the command-line of the operating system.The Python Interactive session.Your favorite IDE or text editor.The system file manager.Here, you have gathered the knowledge and skills of how to run your scripts using various techniques.You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques as KnowledgeHut offers Python Certification Course.
Rated 4.5/5 based on 19 customer reviews
5970
How To Run Your Python Scripts

If you are planning to enter the world of Python p... Read More

What are Python KeyError Exceptions and How to Handle Them

There are times when you have written your code but while you execute, it might not run. These types of situations occur when the input is inappropriate or you try to open a file with a wrong path or try to divide a number by zero. Due to some errors or incorrect command the output will not be displayed. This is because of errors and exceptions which are a part of the Python programming language. Learn about such concepts and gain further knowledge by joining Python Programming Course.What is Exception Handling?Python raises exceptions when it encounters errors during execution. A Python Exception is basically a construct that signals any important event, such as a run-time error.Exception Handling is the process of responding to executions during computations, which often interrupts the usual flow of executing a program. It can be performed both at the software level as part of the program and also at hardware level using built-in CPU mechanisms.Why is Exception Handling Important?Although exceptions might be irritating when they occur, they play an essential role in high level languages by acting as a friend to the user.An error at the time of execution might lead to two things— either your program will die or will display a blue screen of death. On the other hand, exceptions act as communication tools. It allows the program to answer the questions — what, why and how something goes wrong and then terminates the program in a delicate manner.In simple words, exception handling protects against uncontrollable program failures and increases the potency and efficiency of your code. If you want to master yourself in programming, the knowledge of exceptions and how to handle them is very crucial, especially in Python.What are the Errors and Exceptions in Python?Python doesn’t like errors and exceptions and displays its dissatisfaction by terminating the program abruptly.There are basically two types of errors in the Python language-Syntax Error.Errors occuring at run-time or Exceptions.Syntax ErrorsSyntax Errors, also known as parsing errors, occur when the parser identifies an incorrect statement. In simple words, syntax error occurs when the proper structure or syntax of the programming language is not followed.An example of a syntax error:>>> print( 1 / 0 )) File "", line 1 print( 1 / 0 ))   ^SyntaxError: invalid syntaxExceptionsExceptions occur during run-time. Python raises an exception when your code has a correct syntax but it encounters a run-time issue which it is not able to handle.There are a number of defined built-in exceptions in Python which are used in specific situations. Some of the built-in exceptions are:ExceptionCause Of ErrorArithmeticErrorRaised when numerical computation fails.FloatingPointErrorRaised when floating point calculation fails.AssertionErrorRaised in case of failure of the Assert statement.ZeroDivisionErrorRaised when division or modulo by zero takes place for all numerical values.OverflowErrorRaised when result of an arithmetic operation is very large to be represented.IndexErrorRaised when an index is not found in a sequence.ImportErrorRaised when the imported module is not found.IndentationErrorRaised when indentation is not specified properly.KeyboardInterruptRaised when the user hits interrupt key.RuntimeErrorRaised when a generated error does not fall into any category.SyntaxErrorRaised when there is an error in Python syntax.IOErrorRaised when Python cannot access a file correctly on disk.KeyErrorRaised when a key is not found in a dictionary.ValueErrorRaised when an argument to a function is the right type but not in the right domain.NameErrorRaised when an identifier is not found in the local or global namespace.TypeErrorRaised when an argument to a function is not in the right type.There are another type of built-in exceptions called warnings. They are usually issued in situations where the user is alerted of some conditions. The condition does not raise an exception; rather it  terminates the program.What is a Python KeyError?Before getting into KeyError, you must know the meaning of dictionary and mapping in Python. Dictionary (dict) is an unordered collection of objects which deals with data type key. They are Python’s implementation of data structures and are also known as associative arrays. They comprise key-value pairs, in which each pair maps the key to its associated value.Dictionary is basically a data structure that maps one set of values into another and is the most common mapping in Python.Exception hierarchy of KeyError:->BaseException              ->Exception                         ->LookupError                                       ->KeyErrorA Python KeyError is raised when you try to access an invalid key in a dictionary. In simple terms, when you see a KeyError, it denotes that the key you were looking for could not be found.An example of KeyError:>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} >>> prices['Eraser'] Traceback (most recent call last): File "", line 1, in prices['Eraser'] KeyError: 'Eraser'Here, dictionary prices is declared with the prices of three items. The KeyError is raised when the item ‘Eraser’ is being accessed which is not present in prices.Whenever an exception is raised in Python, it is done using traceback, as you can see in the example code above. It tells why an exception is raised and what caused it.Let’s execute the same Python code from a file. This time, you will be asked to give the name of the item whose price you want to know:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') print(f'The price of {item} is {prices[item]}')You will get a traceback again but you’ll also get the information about the line from which the KeyError is raised:Get price of: Eraser Traceback (most recent call last): File "prices.py", line 5, in print(f'The price of {item} is {prices[item]}') KeyError: 'Eraser'The traceback in the example above provides the following information:A KeyError was raised.The key ‘Eraser’ was not found.The line number which raised the exception along with that line.Where else will you find a Python KeyError?Although most of the time, a KeyError is raised because of an invalid key in a Python dictionary or a dictionary subclass, you may also find it in other places in the Python Standard Library, such as in a zipfile. However, it denotes the same semantic meaning of the Python KeyError, which is not finding the requested key.An example of such:>>> from zipfile import ZipFile >>> my_zip_file = ZipFile('Avengers.zip') >>> my_zip_file.getinfo('Batman')Traceback (most recent call last): File "", line 1, in File "myzip.py", line 1119, in getinfo 'There is no item named %r in the archive' % name) KeyError: "There is no item named 'Batman' in the archive"In this example, the zipfile.ZipFile class is used to derive information about a ZIP archive ‘Batman’ using the getinfo() function. Here, the traceback indicates that the problem is not in your code but in the zipfile code, by showing the line which caused the problem. The exception raised here is not because of a LookUpError but rather due to the zipfile.ZipFile.getinfo()function call.When do you need to raise a Python KeyError?In Python Programming, it might be sensible at times to forcefully raise exceptions in your own code. You can usually raise an exception using the raise keyword and by calling the KeyError exception:>>> raise KeyError('Batman')Here, ‘Batman’ acts as the missing key. However, in most cases, you should provide more information about the missing key so that your next developer has a clear understanding of the problem.Conditions to raise a Python KeyError in your code:It should match the generic meaning behind the exception.A message should be displayed about the missing key along with the missing key which needs to be accessed.How to Handle a Python KeyError?The main motive of handling a Python KeyError is to stop unexpected KeyError exceptions to be raised. There are a number of number of ways of handling a KeyError exception.Using get()The get()is useful in cases where the exception is raised due to a failed dictionary LookupError. It returns either the specified key value or a default value.# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') price = prices.get(item) if price:   print(f'The price of {item} is {prices[item]}')   else:   print(f'The price of {item} is not known')This time, you’ll not get a KeyError because the get() uses a better and safer method to retrieve the price and if not found, the default value is displayed:Get price of: EraserThe price of Eraser is not knownIn this example, the variable price will either have the price of the item in the dictionary or the default value ( which is None by default ).In the example above, when the key ‘Eraser’ is not found in the dictionary, the get() returns  None by default rather than raising a KeyError. You can also give another default value as a second argument by calling get():price = prices.get(item,0)If the key is not found, it will return 0 instead of None.Checking for KeysIn some situations, the get() might not provide the correct information. If it returns None, it will mean that the key was not found or the value of the key in Python Dictionary is actually None, which might not be true in some cases. In such situations, you need to determine the existence of a key in the dictionary. You can use the if and in operator to handle such cases. It checks whether a key is present in the mapping or not by returning a boolean (True or False) value:dict = dictionary() for i in range(50):   key = i % 10     if key in dict: dict[key] += 1 else: dict[key] = 1In this case, we do not check what the value of the missing key is but rather we check whether the key is in the dictionary or not. This is a special way of handling an exception which is used rarely.This technique of handling exceptions is known as Look Before You Leap(LBYL).Using try-exceptThe try-except block is one of the best possible ways to handle the KeyError exceptions. It is also useful where the get() and the if and in operators are not supported.Let’s apply the try-except block on our earlier retrieval of prices code:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known')Here, in this example there are two cases— normal case and a backup case. try block corresponds to the normal case and except block to the backup case. If the normal case doesn’t print the name of the item and the price and raises a KeyError, the backup case prints a different statement or a message.Using try-except-elseThis is another way of handling exceptions. The try-except-else  has three blocks— try block, except block and else block.The else condition in a try-except statement is useful when the try condition doesn’t raise an exception. However, it must follow all the except conditions.Let us take our previous price retrieval code to illustrate try-except-else:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of:') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known') else: print(f'There is no error in the statement')First, we access an existing key in the try-except block. If the Keyerror is not raised, there are no errors. Then the else condition is executed and the statement is displayed on the screen.Using finallyThe try statement in Python can have an optional finally condition. It is used to define clean-up actions and is always executed irrespective of anything. It is generally used to release external sources.An example to show finally:# prices.py prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} item = input('Get price of: ') try: print(f'The price of {item} is {prices[item]}') except KeyError: print(f'The price of {item} is not known') finally: print(f'The finally statement is executed')Remember, the finally statement will always be executed whether an exception has occurred or not.How to raise Custom Exceptions in Python?Python comprises of a number of built-in exceptions which you can use in your program. However, when you’re developing your own packages, you might need to create your own custom exceptions to increase the flexibility of your program.You can create a custom Python exception using the pre-defined class Exception:def square(x): if x
Rated 4.5/5 based on 1 customer reviews
7589
What are Python KeyError Exceptions and How to Han...

There are times when you have written your code bu... Read More

20% Discount