debugging - hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. design an...
TRANSCRIPT
![Page 1: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/1.jpg)
Debugging
BBM101-Introduc/ontoProgrammingI
Hace7epeUniversityFall2015
FuatAkal,AykutErdem,ErkutErdem,VahidGarousi
1SlidesbasedonmaterialpreparedbyRuthAnderson,MichaelErnstandBillHoweinthecourseCSE140UniversityofWashington
![Page 2: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/2.jpg)
Example:WriteaFunc5on
Writeafunc/onthatwillreturnthesetofauser’sfriendswithapar/cularuserremovedfromthatset.
2
![Page 3: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/3.jpg)
TheProblem
Whatyouwantyourprogramtodo
Whatyourprogramdoes
Notthesame!
3
Thereisabug!
![Page 4: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/4.jpg)
WhatisDebugging?
• GraceHopperwasoneofU.S.’sfirstprogrammers.• ShefoundamothintheMarkIcomputer,whichwascausingerrors,andcalleditacomputer“bug”
• Thus,theworddebuggingiscoinedJ
4
![Page 5: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/5.jpg)
DebuggingTools
• Pythonerrormessage• assert • print • Pythoninterpreter• PythonTutor(h7p://pythontutor.com)• Pythondebugger• Besttool:
5
![Page 6: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/6.jpg)
TwoKeyIdeas1. Thescien/ficmethod2. DivideandconquerIfyoumasterthose,youwillfinddebuggingeasy,andpossiblyenjoyable;-)
6
![Page 7: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/7.jpg)
TheScien5ficMethod1. Createahypothesis2. Designanexperimenttotestthathypothesis
– Ensurethatityieldsinsight3. Understandtheresultofyourexperiment
– Ifyoudon’tunderstand,thenpossiblysuspendyourmainlineofworktounderstandthat
Tips:• Besystema/c
– Neverdoanythingifyoudon'thaveareason– Don’tjustflail
• Randomguessingislikelytodigyouintoadeeperhole• Don’tmakeassump/ons(verifythem)
7
![Page 8: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/8.jpg)
ExampleExperiments
1. Analternateimplementa/onofafunc/on– Runallyourtestcasesaferward
2. Anew,simplertestcase– Examples:smallerinput,ortestafunc/oninisola/on
– Canhelpyouunderstandthereasonforafailure
8
![Page 9: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/9.jpg)
YourScien5ficNotebookRecordeverythingyoudo• Specificinputsandoutputs(bothexpectedandactual)• Specificversionsoftheprogram
– Ifyougetstuck,youcanreturntosomethingthatworks– Youcanwritemul/pleimplementa/onsofafunc/on
• Whatyouhavealreadytried• Whatyouareinthemiddleofdoingnow
– Thismaylooklikeastack!• Whatyouaresureof,andwhyYournotebookalsohelpsifyouneedtogethelporreproduceyourresults
9
![Page 10: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/10.jpg)
ReadtheErrorMessageTraceback (most recent call last): File "nx_error.py", line 41, in <module> print friends_of_friends(rj, myval) File "nx_error.py", line 30, in friends_of_friends f = friends(graph, user) File "nx_error.py", line 25, in friends return set(graph.neighbors(user))# File "/Library/Frameworks/…/graph.py", line 978, in neighbors return list(self.adj[n]) TypeError: unhashable type: 'list' Listofallexcep/ons(errors):h7p://docs.python.org/2/library/excep/ons.html#bl/n-excep/onsTwootherresources,withmoredetailsaboutafewoftheerrors:h7p://inventwithpython.com/appendixd.htmlh7p://www.cs.arizona.edu/people/mccann/errors-python
Callstackortraceback
Firstfunc/onthatwascalled(<module> meanstheinterpreter)
Secondfunc/onthatwascalled
Lastfunc/onthatwascalled(thisonesufferedanerror)
Theerrormessage:daun/ngbutuseful.Youneedtounderstand:• theliteralmeaningof
theerror• theunderlying
problemscertainerrorstendtosuggest
10
![Page 11: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/11.jpg)
CommonErrorTypes• Asser/onError
– Raisedwhenanassertstatementfails.
• IndexError– Raisedwhenasequencesubscriptisoutofrange.
• KeyError– Raisedwhenamapping(dic/onary)keyisnotfoundinthesetofexis/ngkeys.
• KeyboardInterrupt– Raisedwhentheuserhitstheinterruptkey(normallyControl-CorDelete).
• NameError– Raisedwhenalocalorglobalnameisnotfound.
• SyntaxError– Raisedwhentheparserencountersasyntaxerror.
• Indenta/onError– Baseclassforsyntaxerrorsrelatedtoincorrectindenta/on.
• TypeError– Raisedwhenanopera/onorfunc/onisappliedtoanobjectofinappropriatetype. 11
![Page 12: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/12.jpg)
DivideandConquer• Whereisthedefect(or“bug”)?• Yourgoalistofindtheoneplacethatitis• Findingadefectisofenharderthanfixingit
• Ini/ally,thedefectmightbeanywhereinyourprogram– Itisimprac/caltofinditifyouhavetolookeverywhere
• Idea:bitbybitreducethescopeofyoursearch• Eventually,thedefectislocalizedtoafewlinesoroneline
– Thenyoucanunderstandandfixit
• 4waystodivideandconquer:– Intheprogramcode– Intestcases– Duringtheprogramexecu/on– Duringthedevelopmenthistory
12
![Page 13: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/13.jpg)
DivideandConquerintheProgramCode
• Localizethedefecttopartoftheprogram– e.g.,onefunc/on,oronepartofafunc/on
• Codethatisn’texecutedcannotcontainthedefect
3approaches:• Testonefunc/onata/me• Addasser/onsorprintstatements
– Thedefectisexecutedbeforethefailingasser/on(andmaybeaferasucceedingasser/on)
• SplitcomplexexpressionsintosimpleronesExample:Failurein result = set({graph.neighbors(user)}) Changeitto nbors = graph.neighbors(user) nbors_set = {nbors} result = set(nbors_set) Theerroroccursonthe“nbors_set={nbors}"line
13
![Page 14: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/14.jpg)
DivideandConquerinTestCases
• Yourprogramfailswhenrunonsomelargeinput– It’shardtocomprehendtheerrormessage– Thelogofprintstatementoutputisoverwhelming
• Tryasmallerinput– Chooseaninputwithsomebutnotallcharacteris/csofthelargeinput
– Example:duplicates,zeroesindata,…
14
![Page 15: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/15.jpg)
DivideandConquerinExecu5onTimeviaPrint(or“logging”)Statements
• Asequenceofprintstatementsisarecordoftheexecu/onofyourprogram
• Theprintstatementsletyouseeandsearchmul/plemomentsin/me
• Printstatementsareausefultechnique,inmodera/on• Bedisciplined– Toomuchoutputisoverwhelmingratherthaninforma/ve– Rememberthescien/ficmethod:haveareason(ahypothesistobetested)foreachprintstatement
– Don’tonlyuseprintstatements
15
![Page 16: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/16.jpg)
DivideandConquerinDevelopmentHistory
• Thecodeusedtowork(forsometestcase)• Thecodenowfails• Thedefectisrelatedtosomelineyouchanged
• Thisisusefulonlyifyoukeptaversionofthecodethatworked(usegoodnames!)
• Thisismostusefulifyouhavemadefewchanges• Moral:testofen!– Fewerlinestocompare– Yourememberwhatyouwerethinking/doingrecently
16
![Page 17: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/17.jpg)
AMetaphorAboutDebuggingIfyourcodedoesn’tworkasexpected,thenbydefini/onyoudon’tunderstandwhatisgoingon.• You’relostinthewoods.• You’rebehindenemylines.• Allbetsareoff.• Don’ttrustanyoneoranything.Don’tpressonintounexploredterritory--gobackthewayyoucame!(andleavebreadcrumbs!)
You’retryingto“advancethefrontlines,”not“trailblaze”17
![Page 18: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/18.jpg)
Time-SavingTrick:MakeSureYouareDebuggingtheRightProblem
• Thegameistogofrom“workingtoworking”• Whensomethingdoesn’twork,STOP!
– It’swildoutthere!• FIRST:Gobacktothelastsitua/onthatworkedproperly.
– Rollbackyourrecentchangesandverifythateverythings/llworksasexpected.
– Don’tmakeassump/ons–bydefini/on,youdon’tunderstandthecodewhensomethinggoeswrong,soyoucan’ttrustyourassump/ons.
– Youmayfindthatevenwhatpreviouslyworkednowdoesn’t– Perhapsyouforgottoconsidersome“innocent”oruninten/onalchange,
andnoweventestedcodeisbroken
18
![Page 19: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/19.jpg)
ABadTimeline
• Aworks,socelebrateali7le• NowtryB• Bdoesn’twork• ChangeBandtryagain• ChangeBandtryagain• ChangeBandtryagain…
19
![Page 20: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/20.jpg)
ABeSerTimeline• Aworks,socelebrateali7le• NowtryB• Bdoesn’twork• RollbacktoA• DoesAs/llwork?
– Yes:FindA’thatissomewherebetweenAandB– No:Youhaveuninten=onallychangedsomethingelse,andthere’sno
pointfutzingwithBatall!
These“innocent”andunno/cedchangeshappenmorethanyouwouldthink!• Youaddacomment,andtheindenta/onchanges.• Youaddaprintstatement,andafunc/onisevaluatedtwice.• Youmoveafile,andthewrongoneisbeingread• Youareonadifferentcomputer,andthelibraryisadifferentversion
20
![Page 21: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/21.jpg)
OnceYouareonSolidGroundYoucanSetOutAgain
• Onceyouhavesomethingthatworksandsomethingthatdoesn’twork,itisonlyama7erof/me
• Youjustneedtoincrementallychangetheworkingcodeintothenon-workingcode,andtheproblemwillrevealitself.
• Varia/on:Perhapsyourcodeworkswithoneinput,butfailswithanother.Incrementallychangethegoodinputintothebadinputtoexposetheproblem.
21
![Page 22: Debugging - Hacettepe Üniversitesibbm101/fall15/lectures/... · 2015. 11. 4. · 2. Design an experiment to test that hypothesis – Ensure that it yields insight 3. Understand the](https://reader036.vdocument.in/reader036/viewer/2022071015/5fce8b5d7644d97b92381e6a/html5/thumbnails/22.jpg)
SimpleDebuggingTools
print– showswhatishappeningwhetherthereisaproblemornot
– doesnotstopexecu/onassert– Raisesanexcep/onifsomecondi/onisnotmet– Doesnothingifeverythingworks– Example:assert len(rj.edges()) == 16 – Usethisliberally!Notjustfordebugging!
22