Skip to main content
Engineering LibreTexts

15.7: Debugging

  • Page ID
    42431
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)

    When you start working with objects, you are likely to encounter some new exceptions. If you try to access an attribute that doesn’t exist, you get an AttributeError:

    >>> p = Point()
    >>> p.x = 3
    >>> p.y = 4
    >>> p.z
    AttributeError: Point instance has no attribute 'z'
    

    If you are not sure what type an object is, you can ask:

    >>> type(p)
    <class '__main__.Point'>
    

    You can also use isinstance to check whether an object is an instance of a class:

    >>> isinstance(p, Point)
    True
    

    If you are not sure whether an object has a particular attribute, you can use the built-in function hasattr:

    >>> hasattr(p, 'x')
    True
    >>> hasattr(p, 'z')
    False
    

    The first argument can be any object; the second argument is a string that contains the name of the attribute.

    You can also use a try statement to see if the object has the attributes you need:

    try:
        x = p.x
    except AttributeError:
        x = 0
    

    This approach can make it easier to write functions that work with different types; more on that topic is coming up in Section 17.9.


    15.7: Debugging is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey.

    • Was this article helpful?