Reputation: 99
The pdb
module should contain a function called set_trace
, however, when I run the code import pdb; pdb.set_trace()
I get an error message saying module 'pdb' has no attribute 'set_trace'
. Why is this error happening, even though my code is correct?
Here the code.py file I am executing to get this error:
print("Hello, World!")
import pdb
pdb.set_trace()
print("Goodbye, World!")
And here is the complete output of my program:
Hello, World! Hello, World! Traceback (most recent call last): File "code.py", line 3, in import pdb File "/usr/lib/python3.6/pdb.py", line 76, in import code File "/tmp/code.py", line 4, in pdb.set_trace()
Upvotes: 1
Views: 987
Reputation: 99
One of the first things that pdb does after you execute it is import a module
called code
. However, since you've named your file code.py
Python ends up
executing both files. When your file is executed for the second time, it prints
the "Hello, World!" message again. At this point, Python is still processing the
first import pdb
statement when it encounters the same statement again. In a
language like C, this would result in infinite recursion, but Python
automatically ignores duplicate imports
(documentation).
Thus, Python ends up executing the next line of your code, pdb.set_trace()
,
before the initial import pdb
statement finished executing, which is why
you see an error message telling you that pdb.set_trace()
does not exist.
To fix this, you could just rename your file to something else, but it would be better to add a check so that your code doesn't execute when it is imported by a different file:
if __name__ == "__main__":
print("Hello, World!")
import pdb
pdb.set_trace()
print("Goodbye, World!")
Upvotes: 4