Learn How to Debug Python Code Effectively

Python debugging, starting with the basics, and moving to some new techniques and strategies to take your debugging to the next level, as well as suggest such Uncodemy courses that can be of support to your development.

Learn How to Debug Python Code Effectively

Learn How to Debug Python Code Effectively

Python Common Errors Explained

Before getting into the details of debugging, it is necessary to see that there are some error messages which seem common to Python and can be used initially to get the idea of what went wrong.

Error in Over-Indentation: unindented body

This is an error which is made when the programmer writes a code that is not written as required by the syntax rules in the program like parenthesis missing or wrong colon placed. The best way to resolve it is to ensure that there are syntax markers and that commas, brackets, parentheses, quotes, etc are matched.

NameError to global variable that is not defined

The code blocks in Python are defined by using indentation, and the error is caused by the inconsistent or wrong indentation. This can be fixed by ensuring that the indentation is done correctly and consistently, with spaces or tabs where necessary.

GLOBAL DECLARATION undefined

The problem occurs when you attempt to use a variable or procedure that is not defined. This error would be overcome by looking out for typos in names and putting them into definition before using them.

AttributeError: module object has no attribute_name

This can be an error you come across when you are trying to access a property or method which cannot exist on a module or an object. This can be solved by going to review your code to ensure that the called attribute or method is accurate and present.

FileNotFoundError: the file does not exist: ‘filename’

This is one of the errors that arise when the program wishes to use a file which is not available.In order to repair it, check the path of the file and make sure the file exists in the path pointed out.

out of range index error

This exception is thrown during an attempt to read an index of a sequence, e.g. a list or a string, outside of its valid range. This error will be rectified by making sure the index applied is within a valid range of the sequence.

ImportError module_name has no attribute module_name

This error will be raised when you are trying to import a module, which is not installed or available. This can be avoided by installing the necessary module using package manager such as pip or verifying that the module name does not have any typography errors.

TypeError

It is a common exception that is raised in Python when an operation or a function is performed on an object whose type does not suit it. Its examples could be TypeError: unsupported operand type(s) for +: 'type1' and 'type2' in case of any attempt to operate types that cannot be operated or TypeError: function_name() takes X positional arguments but Y were given when calling a non-existent number of arguments in a called function. An off-shoot or sub-category of TypeError is, the int object is not callable. This error is encountered when there is a temptation to use an object as a callable object, and it is not.

ValueError

ValueError occurs when the argument was passed to the function having the right type but with the wrong value. An example is ValueError: invalid literal for int() with base X: non-numeric that occurs in converting a value to an integer but it is not a normal numeric representation of the value. On the same note, ValueError: could not convert string to float: non-numeric is raised when there is an attempt to convert a non-numeric string to a floating point number. The other one is ValueError: unhashable type: mutable_type that happens when we attempt to use a mutable object such as a list or dictionary as a key in a dictionary or as an element of a set, which needs immutable objects. 

Print Statements

By applying the print() functions judiciously and strategically in your code, you can generate messages which will convey on the console and it will help you comprehend the flow of execution and the values of the variables at any given moment. Although print statements are good to use during initial development, they can become inconvenient in more complex programs and print statements are not the best form of production code.

Logging

As it should be, logging is an organized method of documenting your program run information, similar to detailed notes. It enables you to regulate the amount of information you want to see in messages and where logs need to be sent (e.g. to console, to file). The logging levels are DEBUG, INFO, WARNING, ERROR, and CRITICAL each having a special level of severity of a message. When the application is bigger, it is possible to have more control over logging in various areas of the application by leveraging particular loggers rather than the root logger.

Exception Handling

The best way to make your code robust is to wrap the suspicious blocks of codes with the try-except statements in order to intercept and monitor the exceptions in order to avoid sudden collapses of your program. This will allow beautiful error handling and writing of useful information to logs. The try block holds the code that could cause a fault to be raised whereas the except block is executed in case of an exception of a particular kind. The finally block, in the event that it is present at all, is always guaranteed to execute whether an exception was encountered or not.

Assertions

An assertion is a test that you put in your code to state whether a given condition is true and in the event that it is false, it is an indication of a bug or a surprise case. The assert keyword is available in Python and when the condition proves wrong an AssertionError is thrown. They are useful during development and debugging activities as these situations are most concerned with catching logical errors, which may be disabled at production to improve performance.

Expert Debugging

Unit Testing

Unit testing is a technique to test software, in which software components or functions are tested independently of each other, and in the proper functioning.Unit testing allows early identification of bugs, it also allows debugging to identify the origin of an error and finally, it serves as a safety net to allow new changes not to break existing functionality. Such use of Python is common with the builtin unittest framework or the pytest third party framework.

PDB (Interactive Debugger)

PDB (Python DeBugger) is a built-in debugger of Python which lets you turn execution of code off, view variables and step through the code line by line to debug problems. It has a command-line interface that offers an interactive environment of debugging. With the pdb.set_trace() (or breakpoint() in python 3.7 or more recent) you can put break points to halt the program and continue to another location. Upon encountering a breakpoint, the application switches into interactive debugger mode and the program is preceded with a (Pdb) prompt which enables you to run some commands.

C (continue): Starts off where the last line is completed; all the lines that have to be executed up to the last line have to have been done.

n (next): Just continues the program forward to the next line of the current function, and does not step into function calls on the current line.

(step): Performs the current line and interrupts at the first possible opportunity, either by entering a called routine or by stepping to the next line of the current routine.

l (list): the source of the lines around it.

q (quit): exits the debugger, abandons the program.

p <expression> (print): Prints the value of the given expression, and can be used to investigate the contents of variables.

DELETE specifies breakpoint.

  • bline_number or b (break): Place a breakpoint at a line number or a function.
  • sets a temporary breakpoint that is removed automatically after being hit.
  • returns (return): Performs terminations until the addition of present function return is attempted.
  • j (jump): Goes to a given line of the current file.

 

Waits until the call to the current function returns.

  • args (arguments): Prints the argument list of the function in which data is used.
  • pp <expression> (pretty-print): Values of the expression are pretty-printed.

 

Remote Debugging

Remote debugging Debugging code running on a system or a server that is not part of the development environment is common on the sort of applications run on remote servers or in the cloud. You have your local IDE integrated to the remote environment and you work with remote breakpoints, stepping through code, variable inspection and all the other features that your IDE can provide. The support of remote debugging is inbuilt in popular IDEs such as PyCharm and Visual Studio Code.

Performance Debugging

Profiling is the analysis of the performance of your code in order to detect bottlenecks and any areas that still need some optimization. Python includes the built-in modules cProfile and profile which can be used to do deterministic profiling, to record the time each function takes to perform. Such tools as snakeviz can be used to visualize profiling results to ease analysis. More advanced profiling tools are available in the form of line profiling using line_profiler, to observe the time taken on per line, and memory_profiling to inspect memory resources usage and memory leaks.

Other Debugging Hints

Version Control and git bisect: Using version control tools such as git, one can track the changes and revert to the golden versions. git bisect commands are used to find the specific commit terminating with the bug.

Code Comments and Documentation: Proper comments and documentation of the code help the developer in comprehending the functions and pieces of code and simplifies searching and debugging the code by an existing as well as new developer.

The way to search solutions to bugs and errors An example taken.

On the other hand, when you come across a problem that you are not able to solve at the moment, then effective use of web resources is able to give solutions.

Error Message: The first point is to understand the error message which means you have to identify key terms and error codes to search on. Provide the context such as operating system, version of software, libraries, or frameworks, because bugs and solutions are different.

Use Descriptive Keywords and Quotes: Use specific terms that are relevant to the topic of the error such as the programming language, frameworks, and other technologies. The searching of exact phrases, e.g. to find a particular error message or code snippet, can be done by using quotation marks.

Learn to Boost Your Skills with Uncodemy

Whether you are a newbie in Python or simply want to go over your existing skills, Uncodemy has an all-inclusive Python training course. Uncodemy Python course in Mohali is based on practical training and industry application of Python Programming language and the curriculum has shifted to reflect the latest skills in demand in the industry. Uncodemy offers learning with flexibility in terms of both offline learning in Mohali and online learning and it is up to you to choose what suits you. The distinctive advantage is that they focus several efforts on job placement, and they can provide their students with placement services and the opportunity to practice their skills on the real examples in cooperation with several companies. Uncodemy is the key to achieving a successful life with the skills required in the digital world as the company is keen on the success of students.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses