SlideShare a Scribd company logo
1 of 32
Download to read offline
Tips for Happier Python
Debugging
Chun-Hao, Chang
2019-APR-05
To Audience
This slide targets the people who want to improve their Python debugging
skills thus have a happier life.
Especially, this is for those who have strong typing language experiences(C,
C++, and Java) but don't know to to Python properly.
Writing Python Should be Happy!
Image from RealPython.com
Overview
● Duck Typing: The loved and hated
● Interactive Programming: That's the Pythonic Way
● IPython: Powerful Interactive Shell
● Logging and Print: Basic but Useful
● IPDB: Python Debugger
● Debugging Tips: Unit Test, Try-Except Clause, Pickle and Dill
Duck Typing
If it walks like a duck and it quacks like a duck, then it must be a duck
A humorous and apt
representation of duck typing.
Source: Mastracci, 2014.
Duck Typing: Example
Duck Typing: the exceptional Enum
The enum object is comparing via their identity instead of value.
Duck Typing: Source of Surprises
Python is not a strong type language. It favors flexibility over safety.
This cause unexpected errors and troubles, especially for those who write
Python like C++ ʕ ͡° ͜ʖ ͡°ʔ .
The following slides will introduce interactive programming to avoid it and
debugging tools.
Interactive Programming
Python should be written or tested in an interactive way: REPL
Read-Eval-Prompt-Loop: A Responsive Playground
Interactive Programming: What you can do
In a REPL environment, you can do the following:
● Manipulate existing variables
● Call a function
● Define function and class
● Load a Python script
● Overwrite existing variables, function and class
● Debugging
● Read the documents and source codes of an imported function and class
● $ sudo rm -rf /*
● Basically, whatever you want ( ͡◉◞ ͜ʖ◟ ͡◉)
Interactive Programming: REPL-DD
You should keep testing and refining in REPL during development.
Don’t start testing your code until you finish everything!
Interactive Programming: Tools
There are awesome REPL tools like Jupyter Notebook, IPython, and the latest
Jupyter-Lab.
This slide does not cover Jupyter, but it’s a powerful for you to code, visualize,
and share the result in browsers. Please do search for it if you didn’t know it.
IPython
Interactive Python Shell is a powerful REPL environment and a system shell
as well. Just use it as a regular shell.
IPython: Basic Usage
#you can also specify the version by ipython2 or ipython3
$ipython
#loading a python scripts
[1] run my_example.py
#read the documents of the imported function
[2] example_fun?
#call a function from the previous script
[3] example_fun(3)
#leaving the shell
[4] exit
IPython: Magic Commands
Commands begin with % are magic commands making your life better . These
commands are not Python code. Only use them within IPython or Jupyter
● %time and %%time #measure times of a command
● %timeit and %%timeit #measure times of multiple lines commands
● %store #save a variable for another shell.
● %pdb #launch debugger when an exception occurred.
● %debug #post-mortem debugging
IPython: embed()
There are cases you can’t launch python scripts with IPython easily. For
example, ROS launch file and Python-written CMD.
● You can use IPython.embed() as a breakpoint to spawn an IPython
shell.
● The spawned shell is a copy of the original process, any modification is
irrelevant to the original process
IPython: Global Flag with embed()
If you insert IPython.embed() within a loop or in a function which might be
called multiple times. Make sure you use a global variable to prevent
IPython.embed() is called multiple times
Logging and Print
In debugging, print is easy and convenient. But it’s messy and tedious when
you print debug message everywhere in your codes.
logging module provides you an elegant way to manage your printing.
● Level of messages: DEBUG, INFO, WARNING, ERROR, and CRITICAL
● Format your printing easily and uniformly
● Send messages to different places easily.
During debugging, you can use logging.debug to print the detailed messages,
and set the logging level to debug.
After debug, you can raise the logging level to omit those messages.
Logging and Print: Example of Logging
From official Python documentation site
Logging and Print: Misleading Messages
Be careful, what you print might be misleading!
IPDB: Interactive Python Debugger
Except for the Debugger in PyCharm, you can also use IPDB(interactive PDB)
to debug.
Compare to IPython, IPDB enables line by line, iteration by iteration, step
into a function call, stop at a breakpoint.
IPDB: Basic Command
● n #next line, a function call or a loop is considered as one line
● s #step into a function or a loop
● c #continue until exception or breakpoint
● w #shows where you are in the codes.
● r #continue until the current function is returned or a loop is over.
● b 3 #breakpoint at line-3
● j 10 #jump to line-10
IPDB: Launch by set_trace()
Besides of launch IPDB from terminal, you can insert ipdb.set_trace() inside
your code, similar to IPython.embed(). This manual fashion is handy when you
can’t launch Python script directly.
IPDB: Global Flag with set_trace()
Just like IPython.embed(), you can use a global flag to prevent
ipdb.set_trace() is called multiple times.
IPDB: Launch by pm()
IPDB also provide post mortem debugging when an exception occurred.
You can use ipdb.pm() in a try-except clause or a REPL environment.
Launch ipdb.pm() before an exception causes error because of missing
sys.last_traceback
In IPython, the magic command %debug is equivalent to ipdb.pm()
IPDB: Automatic Launch by %pdb
In IPython, the %pdb command allows you to launch IPDB automatically when
an exception occurred. IPDB loads all sessions at the moment when an
exception is received.
Debugging Tips: Unit Test
The Python unittest module handles the exception on their own. So IPDB
doesn’t work properly outside of unittest class. The %pdb will not launch
when an exception occurs inside unittest.
To debug, you can either :
● Use ipdb.set_trace() manually inside the unittest class.
● $nosetest --ipdb unittest_example.py #it works like %pdb, make sure you install the
plugin by apt install ipdbplugin
Debugging Tips: Try-Except Clause
In a typical Try-Except Clause, usually the exception is caught, and traceback
message stops prompting . This is inconvenient to debug.
Debugging Tips: Unit Test
Removing try-except clause is tedious. A smarter way is to add raise under the
except scope. raise without argument throws the latest traceback.
Debugging Tips: Pickle and Distill
In extreme situations where IPython and IPDB do not work. You can choose to
dump any Python instance by Pickle. And load the instance again in a REPL
environment to debug.
Debugging Tips: Pickle and Dill
But in most of cases, we need to dump everything: variables, functions, and
class in order to reproduce the whole environment. Dill helps to dump and
load the whole session of the environment
Thank you for your time.
If you have any suggestion and questions. Please contact me ° ͜ʖ ͡ -
Chun-Hao.Chang
ccha97u@gmail.com

More Related Content

What's hot

Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Alessio Ricco
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malwarezynamics GmbH
 
Highly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT CompilationHighly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT CompilationMatthew Gaudet
 
An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()Blue Elephant Consulting
 
Python programming advance lab api how to
Python programming advance lab api  how toPython programming advance lab api  how to
Python programming advance lab api how toprofbnk
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Edureka!
 
Computer assignment for grade 9
Computer assignment for grade  9Computer assignment for grade  9
Computer assignment for grade 9nahomyitbarek
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonP3 InfoTech Solutions Pvt. Ltd.
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
CS1101 Unit 1 Discussion Assignment.docx
CS1101 Unit 1 Discussion Assignment.docxCS1101 Unit 1 Discussion Assignment.docx
CS1101 Unit 1 Discussion Assignment.docxzend_alvi
 
Python programming advance lab api npr 2
Python programming advance lab api npr  2Python programming advance lab api npr  2
Python programming advance lab api npr 2profbnk
 
Python ppt
Python pptPython ppt
Python pptpriyar80
 
PVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostPVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostAndrey Karpov
 
Introduction to mobile reversing
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversingjduart
 
PHP Mega Meetup, Sep, 2020, Anti patterns in php
PHP Mega Meetup, Sep, 2020, Anti patterns in phpPHP Mega Meetup, Sep, 2020, Anti patterns in php
PHP Mega Meetup, Sep, 2020, Anti patterns in phpAhmed Abdou
 
Python debuggers slides
Python debuggers slidesPython debuggers slides
Python debuggers slidesmattboehm
 
Ml goes fruitful
Ml goes fruitfulMl goes fruitful
Ml goes fruitfulPreeti Negi
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Igalia
 

What's hot (20)

Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator Best Practices in apps development with Titanium Appcelerator
Best Practices in apps development with Titanium Appcelerator
 
How to really obfuscate your pdf malware
How to really obfuscate your pdf malwareHow to really obfuscate your pdf malware
How to really obfuscate your pdf malware
 
Highly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT CompilationHighly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT Compilation
 
An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
 
Python programming advance lab api how to
Python programming advance lab api  how toPython programming advance lab api  how to
Python programming advance lab api how to
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
 
Computer assignment for grade 9
Computer assignment for grade  9Computer assignment for grade  9
Computer assignment for grade 9
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to Python
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
CS1101 Unit 1 Discussion Assignment.docx
CS1101 Unit 1 Discussion Assignment.docxCS1101 Unit 1 Discussion Assignment.docx
CS1101 Unit 1 Discussion Assignment.docx
 
Python programming advance lab api npr 2
Python programming advance lab api npr  2Python programming advance lab api npr  2
Python programming advance lab api npr 2
 
Python ppt
Python pptPython ppt
Python ppt
 
PVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostPVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to Boost
 
Introduction to mobile reversing
Introduction to mobile reversingIntroduction to mobile reversing
Introduction to mobile reversing
 
PHP Mega Meetup, Sep, 2020, Anti patterns in php
PHP Mega Meetup, Sep, 2020, Anti patterns in phpPHP Mega Meetup, Sep, 2020, Anti patterns in php
PHP Mega Meetup, Sep, 2020, Anti patterns in php
 
Tfs Per Team Agili
Tfs Per Team AgiliTfs Per Team Agili
Tfs Per Team Agili
 
Python debuggers slides
Python debuggers slidesPython debuggers slides
Python debuggers slides
 
Java lab lecture 1
Java  lab  lecture 1Java  lab  lecture 1
Java lab lecture 1
 
Ml goes fruitful
Ml goes fruitfulMl goes fruitful
Ml goes fruitful
 
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)Property-based testing an open-source compiler, pflua (FOSDEM 2015)
Property-based testing an open-source compiler, pflua (FOSDEM 2015)
 

Similar to Tips for Happier Python Debugging

PYTHON FEATURES.pptx
PYTHON FEATURES.pptxPYTHON FEATURES.pptx
PYTHON FEATURES.pptxMaheShiva
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfVaibhavKumarSinghkal
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptxHaythamBarakeh1
 
ppt notes for python language variable data types
ppt notes for python language variable data typesppt notes for python language variable data types
ppt notes for python language variable data typesSukhpreetSingh519414
 
Intro to Programming Week 2_Python Installation.pptx
Intro to Programming Week 2_Python Installation.pptxIntro to Programming Week 2_Python Installation.pptx
Intro to Programming Week 2_Python Installation.pptxiksanbukhori
 
Application development with Python - Desktop application
Application development with Python - Desktop applicationApplication development with Python - Desktop application
Application development with Python - Desktop applicationBao Long Nguyen Dang
 
Python Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxPython Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxManohar k
 
Learning Python for Raspberry Pi
Learning Python for Raspberry PiLearning Python for Raspberry Pi
Learning Python for Raspberry Pianishgoel
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introductionstn_tkiller
 
Python typing module
Python typing modulePython typing module
Python typing moduleRyan Blunden
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidanceMantoshKumar79
 

Similar to Tips for Happier Python Debugging (20)

PYTHON FEATURES.pptx
PYTHON FEATURES.pptxPYTHON FEATURES.pptx
PYTHON FEATURES.pptx
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Introduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdfIntroduction to Python Unit -1 Part .pdf
Introduction to Python Unit -1 Part .pdf
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptx
 
ppt notes for python language variable data types
ppt notes for python language variable data typesppt notes for python language variable data types
ppt notes for python language variable data types
 
Intro to Programming Week 2_Python Installation.pptx
Intro to Programming Week 2_Python Installation.pptxIntro to Programming Week 2_Python Installation.pptx
Intro to Programming Week 2_Python Installation.pptx
 
Python Programming Course in janak puri, New Delhi
Python Programming Course in janak puri, New DelhiPython Programming Course in janak puri, New Delhi
Python Programming Course in janak puri, New Delhi
 
Application development with Python - Desktop application
Application development with Python - Desktop applicationApplication development with Python - Desktop application
Application development with Python - Desktop application
 
Python programming
Python programmingPython programming
Python programming
 
kecs105.pdf
kecs105.pdfkecs105.pdf
kecs105.pdf
 
python-handbook.pdf
python-handbook.pdfpython-handbook.pdf
python-handbook.pdf
 
Introduction to python3.pdf
Introduction to python3.pdfIntroduction to python3.pdf
Introduction to python3.pdf
 
Python Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docxPython Programming and ApplicationsUnit-1.docx
Python Programming and ApplicationsUnit-1.docx
 
Learning Python for Raspberry Pi
Learning Python for Raspberry PiLearning Python for Raspberry Pi
Learning Python for Raspberry Pi
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
Python PPT1.pdf
Python PPT1.pdfPython PPT1.pdf
Python PPT1.pdf
 
Python typing module
Python typing modulePython typing module
Python typing module
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
 

Recently uploaded

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Recently uploaded (20)

Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 

Tips for Happier Python Debugging

  • 1. Tips for Happier Python Debugging Chun-Hao, Chang 2019-APR-05
  • 2. To Audience This slide targets the people who want to improve their Python debugging skills thus have a happier life. Especially, this is for those who have strong typing language experiences(C, C++, and Java) but don't know to to Python properly.
  • 3. Writing Python Should be Happy! Image from RealPython.com
  • 4. Overview ● Duck Typing: The loved and hated ● Interactive Programming: That's the Pythonic Way ● IPython: Powerful Interactive Shell ● Logging and Print: Basic but Useful ● IPDB: Python Debugger ● Debugging Tips: Unit Test, Try-Except Clause, Pickle and Dill
  • 5. Duck Typing If it walks like a duck and it quacks like a duck, then it must be a duck A humorous and apt representation of duck typing. Source: Mastracci, 2014.
  • 7. Duck Typing: the exceptional Enum The enum object is comparing via their identity instead of value.
  • 8. Duck Typing: Source of Surprises Python is not a strong type language. It favors flexibility over safety. This cause unexpected errors and troubles, especially for those who write Python like C++ ʕ ͡° ͜ʖ ͡°ʔ . The following slides will introduce interactive programming to avoid it and debugging tools.
  • 9. Interactive Programming Python should be written or tested in an interactive way: REPL Read-Eval-Prompt-Loop: A Responsive Playground
  • 10. Interactive Programming: What you can do In a REPL environment, you can do the following: ● Manipulate existing variables ● Call a function ● Define function and class ● Load a Python script ● Overwrite existing variables, function and class ● Debugging ● Read the documents and source codes of an imported function and class ● $ sudo rm -rf /* ● Basically, whatever you want ( ͡◉◞ ͜ʖ◟ ͡◉)
  • 11. Interactive Programming: REPL-DD You should keep testing and refining in REPL during development. Don’t start testing your code until you finish everything!
  • 12. Interactive Programming: Tools There are awesome REPL tools like Jupyter Notebook, IPython, and the latest Jupyter-Lab. This slide does not cover Jupyter, but it’s a powerful for you to code, visualize, and share the result in browsers. Please do search for it if you didn’t know it.
  • 13. IPython Interactive Python Shell is a powerful REPL environment and a system shell as well. Just use it as a regular shell.
  • 14. IPython: Basic Usage #you can also specify the version by ipython2 or ipython3 $ipython #loading a python scripts [1] run my_example.py #read the documents of the imported function [2] example_fun? #call a function from the previous script [3] example_fun(3) #leaving the shell [4] exit
  • 15. IPython: Magic Commands Commands begin with % are magic commands making your life better . These commands are not Python code. Only use them within IPython or Jupyter ● %time and %%time #measure times of a command ● %timeit and %%timeit #measure times of multiple lines commands ● %store #save a variable for another shell. ● %pdb #launch debugger when an exception occurred. ● %debug #post-mortem debugging
  • 16. IPython: embed() There are cases you can’t launch python scripts with IPython easily. For example, ROS launch file and Python-written CMD. ● You can use IPython.embed() as a breakpoint to spawn an IPython shell. ● The spawned shell is a copy of the original process, any modification is irrelevant to the original process
  • 17. IPython: Global Flag with embed() If you insert IPython.embed() within a loop or in a function which might be called multiple times. Make sure you use a global variable to prevent IPython.embed() is called multiple times
  • 18. Logging and Print In debugging, print is easy and convenient. But it’s messy and tedious when you print debug message everywhere in your codes. logging module provides you an elegant way to manage your printing. ● Level of messages: DEBUG, INFO, WARNING, ERROR, and CRITICAL ● Format your printing easily and uniformly ● Send messages to different places easily. During debugging, you can use logging.debug to print the detailed messages, and set the logging level to debug. After debug, you can raise the logging level to omit those messages.
  • 19. Logging and Print: Example of Logging From official Python documentation site
  • 20. Logging and Print: Misleading Messages Be careful, what you print might be misleading!
  • 21. IPDB: Interactive Python Debugger Except for the Debugger in PyCharm, you can also use IPDB(interactive PDB) to debug. Compare to IPython, IPDB enables line by line, iteration by iteration, step into a function call, stop at a breakpoint.
  • 22. IPDB: Basic Command ● n #next line, a function call or a loop is considered as one line ● s #step into a function or a loop ● c #continue until exception or breakpoint ● w #shows where you are in the codes. ● r #continue until the current function is returned or a loop is over. ● b 3 #breakpoint at line-3 ● j 10 #jump to line-10
  • 23. IPDB: Launch by set_trace() Besides of launch IPDB from terminal, you can insert ipdb.set_trace() inside your code, similar to IPython.embed(). This manual fashion is handy when you can’t launch Python script directly.
  • 24. IPDB: Global Flag with set_trace() Just like IPython.embed(), you can use a global flag to prevent ipdb.set_trace() is called multiple times.
  • 25. IPDB: Launch by pm() IPDB also provide post mortem debugging when an exception occurred. You can use ipdb.pm() in a try-except clause or a REPL environment. Launch ipdb.pm() before an exception causes error because of missing sys.last_traceback In IPython, the magic command %debug is equivalent to ipdb.pm()
  • 26. IPDB: Automatic Launch by %pdb In IPython, the %pdb command allows you to launch IPDB automatically when an exception occurred. IPDB loads all sessions at the moment when an exception is received.
  • 27. Debugging Tips: Unit Test The Python unittest module handles the exception on their own. So IPDB doesn’t work properly outside of unittest class. The %pdb will not launch when an exception occurs inside unittest. To debug, you can either : ● Use ipdb.set_trace() manually inside the unittest class. ● $nosetest --ipdb unittest_example.py #it works like %pdb, make sure you install the plugin by apt install ipdbplugin
  • 28. Debugging Tips: Try-Except Clause In a typical Try-Except Clause, usually the exception is caught, and traceback message stops prompting . This is inconvenient to debug.
  • 29. Debugging Tips: Unit Test Removing try-except clause is tedious. A smarter way is to add raise under the except scope. raise without argument throws the latest traceback.
  • 30. Debugging Tips: Pickle and Distill In extreme situations where IPython and IPDB do not work. You can choose to dump any Python instance by Pickle. And load the instance again in a REPL environment to debug.
  • 31. Debugging Tips: Pickle and Dill But in most of cases, we need to dump everything: variables, functions, and class in order to reproduce the whole environment. Dill helps to dump and load the whole session of the environment
  • 32. Thank you for your time. If you have any suggestion and questions. Please contact me ° ͜ʖ ͡ - Chun-Hao.Chang ccha97u@gmail.com