Showing the method's class in expection's traceback

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Agustin Villena

    Showing the method's class in expection's traceback

    Hi!

    is there anyway to show the class of a method in an exception's
    traceback?

    For example, the next code

    class Some(object):
    def foo(self,x):
    raise Exception(x)

    obj = Some()
    obj.foo("some arg")

    produces the next traceback

    Traceback (most recent call last):
    File "<string>", line 231, in run_nodebug
    File "G:\dev\excepti ons\sample.py", line 7, in <module>
    obj.foo("some arg")
    File "G:\dev\excepti ons\sample.py", line 3, in foo
    raise Exception(x)
    Exception: some arg

    I want to improve the line
    File "G:\dev\excepti ons\sample.py", line 3, in foo

    to
    File "G:\dev\excepti ons\sample.py", line 3, in Some.foo

    Is this improvement feasible
  • Diez B. Roggisch

    #2
    Re: Showing the method's class in expection's traceback

    Agustin Villena schrieb:
    Hi!
    >
    is there anyway to show the class of a method in an exception's
    traceback?
    >
    For example, the next code
    >
    class Some(object):
    def foo(self,x):
    raise Exception(x)
    >
    obj = Some()
    obj.foo("some arg")
    >
    produces the next traceback
    >
    Traceback (most recent call last):
    File "<string>", line 231, in run_nodebug
    File "G:\dev\excepti ons\sample.py", line 7, in <module>
    obj.foo("some arg")
    File "G:\dev\excepti ons\sample.py", line 3, in foo
    raise Exception(x)
    Exception: some arg
    >
    I want to improve the line
    File "G:\dev\excepti ons\sample.py", line 3, in foo
    >
    to
    File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
    >
    Is this improvement feasible
    It should be. You can get a dictionary of the locals of an exception
    stack frame, of which you could extract the self-parameter's class.

    Diez

    Comment

    • Gabriel Genellina

      #3
      Re: Showing the method's class in expection's traceback

      En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch <deets@nospam.w eb.deescribió:
      Agustin Villena schrieb:
      >is there anyway to show the class of a method in an exception's
      >traceback?
      >>
      >I want to improve the line
      >File "G:\dev\excepti ons\sample.py", line 3, in foo
      >>
      >to
      >File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
      >>
      >Is this improvement feasible
      >
      It should be. You can get a dictionary of the locals of an exception
      stack frame, of which you could extract the self-parameter's class.
      That by itself is not enough, the method could be inherited; one should walk the base classes in the MRO to find the right one. And deal with classmethods and staticmethods. And decorators that don't preserve meta information... Hmmm, I think it isn't so trivial as it seems.

      --
      Gabriel Genellina

      Comment

      • Diez B. Roggisch

        #4
        Re: Showing the method's class in expection's traceback

        >
        That by itself is not enough, the method could be inherited; one should
        walk the base classes in the MRO to find the right one. And deal with
        classmethods and staticmethods. And decorators that don't preserve meta
        information... Hmmm, I think it isn't so trivial as it seems.
        You might even have an instance-unique method. But I think the OP is
        satisfied with a 90%-solution.

        Diez

        Comment

        • Agustin Villena

          #5
          Re: Showing the method's class in expection's traceback

          On May 18, 4:31 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
          Agustin Villena schrieb:
          >
          >
          >
          Hi!
          >
          is there anyway to show the class of amethodin an exception's
          traceback?
          >
          For example, the next code
          >
          class Some(object):
          def foo(self,x):
          raise Exception(x)
          >
          obj = Some()
          obj.foo("some arg")
          >
          produces the next traceback
          >
          Traceback (most recent call last):
          File "<string>", line 231, in run_nodebug
          File "G:\dev\excepti ons\sample.py", line 7, in <module>
          obj.foo("some arg")
          File "G:\dev\excepti ons\sample.py", line 3, in foo
          raise Exception(x)
          Exception: some arg
          >
          I want to improve the line
          File "G:\dev\excepti ons\sample.py", line 3, in foo
          >
          to
          File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
          >
          Is this improvement feasible
          >
          It should be. You can get a dictionary of the locals of an exception
          stack frame, of which you could extract the self-parameter's class.
          >
          Diez
          Hi!

          I digged on sys.exc_info() object and the traceback module and I
          could't figure how I can get the locals() of the exception stackframe

          Any advice?

          Thanks
          Agustin

          Comment

          • Gabriel Genellina

            #6
            Re: Showing the method's class in expection's traceback

            En Mon, 19 May 2008 10:54:05 -0300, Agustin Villena
            <agustin.villen a@gmail.comescr ibió:
            On May 18, 4:31 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
            >Agustin Villena schrieb:
            >>
            is there anyway to show the class of amethodin an exception's
            traceback?
            I want to improve the line
            File "G:\dev\excepti ons\sample.py", line 3, in foo
            to
            File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
            >>
            >It should be. You can get a dictionary of the locals of an exception
            >stack frame, of which you could extract the self-parameter's class.
            >
            I digged on sys.exc_info() object and the traceback module and I
            could't figure how I can get the locals() of the exception stackframe
            Put this function in traceback.py, and replace the lines
            name = co.co_name
            with
            name = guess_full_meth od_name(f)
            everywhere.
            Please read the docstring!!!

            def guess_full_meth od_name(frame):
            """Guess classname.metho dname for a given frame.

            Only a guess!
            Assumes the frame belongs to an instancemethod
            whose first argument is "self", or a classmethod
            whose first argument is "cls".
            Doesn't handle correctly any other situation.
            Returns the class name of the object on which
            the method was called, not the class where
            the method was actually defined.
            """
            cls_name = None
            fun_name = frame.f_code.co _name
            self = frame.f_locals. get('self', None)
            if self is None:
            cls = frame.f_locals. get('cls', None)
            else:
            cls = getattr(self, '__class__', None)
            if cls is not None:
            cls_name = getattr(cls, '__name__', None)
            if cls_name is not None:
            return '%s.%s' % (cls_name, fun_name)
            return fun_name

            --
            Gabriel Genellina

            Comment

            • Bruno Desthuilliers

              #7
              Re: Showing the method's class in expection's traceback

              Gabriel Genellina a écrit :
              En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch
              <deets@nospam.w eb.deescribió:
              >Agustin Villena schrieb:
              >
              >>is there anyway to show the class of a method in an exception's
              >>traceback?
              >>>
              >>I want to improve the line File "G:\dev\excepti ons\sample.py",
              >>line 3, in foo
              >>>
              >>to File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
              >>>
              >>Is this improvement feasible
              >It should be. You can get a dictionary of the locals of an
              >exception stack frame, of which you could extract the
              >self-parameter's class.
              >
              That by itself is not enough, the method could be inherited; one
              should walk the base classes in the MRO to find the right one. And
              deal with classmethods and staticmethods. And decorators that don't
              preserve meta information...
              And monkeypatches.
              Hmmm, I think it isn't so trivial as it
              seems.
              And not that useful - why would one care about the function being
              defined in class X or Y when one have the exact file and line ?

              Comment

              • Richard G Riley

                #8
                Re: Showing the method's class in expection's traceback

                Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                Gabriel Genellina a écrit :
                >En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch
                ><deets@nospam. web.deescribió :
                >>Agustin Villena schrieb:
                >>
                >>>is there anyway to show the class of a method in an exception's
                >>>traceback?
                >>>>
                >>>I want to improve the line File "G:\dev\excepti ons\sample.py",
                >>>line 3, in foo
                >>>>
                >>>to File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
                >>>>
                >>>Is this improvement feasible
                >>It should be. You can get a dictionary of the locals of an
                >>exception stack frame, of which you could extract the
                >>self-parameter's class.
                >>
                >That by itself is not enough, the method could be inherited; one
                >should walk the base classes in the MRO to find the right one. And
                >deal with classmethods and staticmethods. And decorators that don't
                >preserve meta information...
                >
                And monkeypatches.
                >
                >Hmmm, I think it isn't so trivial as it
                >seems.
                >
                And not that useful - why would one care about the function being
                defined in class X or Y when one have the exact file and line ?
                Very obvious I would think. One can develop ones own interactive class
                browser and code navigator. One can not bring up class help from "line 3
                in x.py" but one can from "classname : MyClass at line 2 in z.py". With
                the class name I can navigate directly to all sorts of class related
                information without the need to delve into a physical usage of it e.g
                program.py at line 3.


                Comment

                • Bruno Desthuilliers

                  #9
                  Re: Showing the method's class in expection's traceback

                  Richard G Riley a écrit :
                  Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                  (snip)
                  >And not that useful - why would one care about the function being
                  >defined in class X or Y when one have the exact file and line ?
                  >
                  Very obvious I would think. One can develop ones own interactive class
                  browser and code navigator.
                  From the traceback ?
                  One can not bring up class help from "line 3
                  in x.py" but one can from "classname : MyClass at line 2 in z.py". With
                  the class name I can navigate directly to all sorts of class related
                  information without the need to delve into a physical usage of it e.g
                  program.py at line 3.
                  Please bear with me, but I'm afraid I still don't get the point : I
                  don't need tracebacks to get to some object's info (help etc).

                  Comment

                  • Richard G Riley

                    #10
                    Re: Showing the method's class in expection's traceback

                    Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                    Richard G Riley a écrit :
                    >Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                    >
                    (snip)
                    >
                    >>And not that useful - why would one care about the function being
                    >>defined in class X or Y when one have the exact file and line ?
                    >>
                    >Very obvious I would think. One can develop ones own interactive class
                    >browser and code navigator.
                    >
                    From the traceback ?
                    >
                    > One can not bring up class help from "line 3
                    >in x.py" but one can from "classname : MyClass at line 2 in z.py". With
                    >the class name I can navigate directly to all sorts of class related
                    >information without the need to delve into a physical usage of it e.g
                    >program.py at line 3.
                    >
                    Please bear with me, but I'm afraid I still don't get the point : I
                    don't need tracebacks to get to some object's info (help etc).
                    This is a view quite common to people when they are happy with what they
                    have. Some like to improve what they have. It is immediately apparent to
                    me why having a class name and method name in the traceback would be
                    immediately useful. Having written a few extensions to IDEs in the past
                    I know it would help me, and I suspect, the original poster. As a recent
                    "recruit" to Python I am quite surprised as how poor most of the query
                    like tools in the python shell are. The first thing I did was to move to
                    iPython. Still, horses for courses.


                    Comment

                    • Bruno Desthuilliers

                      #11
                      Re: Showing the method's class in expection's traceback

                      Richard G Riley a écrit :
                      Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                      >
                      >Richard G Riley a écrit :
                      >>Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ites:
                      >(snip)
                      >>
                      >>>And not that useful - why would one care about the function being
                      >>>defined in class X or Y when one have the exact file and line ?
                      >>Very obvious I would think. One can develop ones own interactive class
                      >>browser and code navigator.
                      >From the traceback ?
                      >>
                      >> One can not bring up class help from "line 3
                      >>in x.py" but one can from "classname : MyClass at line 2 in z.py". With
                      >>the class name I can navigate directly to all sorts of class related
                      >>information without the need to delve into a physical usage of it e.g
                      >>program.py at line 3.
                      >Please bear with me, but I'm afraid I still don't get the point : I
                      >don't need tracebacks to get to some object's info (help etc).
                      >
                      This is a view quite common to people when they are happy with what they
                      have. Some like to improve what they have. It is immediately apparent to
                      me why having a class name and method name in the traceback would be
                      immediately useful.
                      Then please explain.
                      Having written a few extensions to IDEs in the past
                      I know it would help me,
                      To do what ?

                      Comment

                      • Agustin Villena

                        #12
                        Re: Showing the method's class in expection's traceback

                        And not that useful - why would one care about the function being
                        defined in class X or Y when one have the exact file and line ?
                        I have 3 reasons:

                        1) My developing time is expended running unit tests and browsing
                        tracebacks to find which is the real problem. Knowing the offender
                        class (instead of the method alone) makes me understand more quickly
                        which component of my software is failing.
                        2) There are some ocassions where I only have the traceback (e.g. when
                        analyzing an app's log) and no inmediate access to teh source code
                        3) And finally, for completeness: If a function is really a method, if
                        the traceback show only its name and not the class that defines it,
                        for me its a bug, because the method name has no sense out of its
                        class.

                        Just my two cents

                        Agustin

                        Comment

                        • Agustin Villena

                          #13
                          Re: Showing the method's class in expection's traceback

                          On 20 mayo, 12:10, "Gabriel Genellina" <gagsl-...@yahoo.com.a rwrote:
                          En Mon, 19 May 2008 10:54:05 -0300, Agustin Villena
                          <agustin.vill.. .@gmail.comescr ibió:
                          >
                          On May 18, 4:31 pm, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
                          Agustin Villena schrieb:
                          >
                          is there anyway to show the class of amethodin anexception's
                          traceback?
                          I want to improve the line
                          File "G:\dev\excepti ons\sample.py", line 3, in foo
                          to
                          File "G:\dev\excepti ons\sample.py", line 3, in Some.foo
                          >
                          It should be. You can get a dictionary of the locals of anexception
                          stack frame, of which you could extract the self-parameter's class.
                          >
                          I digged on sys.exc_info() object and the traceback module and I
                          could't figure how I can get the locals() of theexceptionsta ckframe
                          >
                          Put this function in traceback.py, and replace the lines
                          name = co.co_name
                          with
                          name = guess_full_meth od_name(f)
                          everywhere.
                          Please read the docstring!!!
                          >
                          def guess_full_meth od_name(frame):
                          """Guess classname.metho dname for a given frame.
                          >
                          Only a guess!
                          Assumes the frame belongs to an instancemethod
                          whose first argument is "self", or a classmethod
                          whose first argument is "cls".
                          Doesn't handle correctly any other situation.
                          Returns the class name of the object on which
                          the method was called, not the class where
                          the method was actually defined.
                          """
                          cls_name = None
                          fun_name = frame.f_code.co _name
                          self = frame.f_locals. get('self', None)
                          if self is None:
                          cls = frame.f_locals. get('cls', None)
                          else:
                          cls = getattr(self, '__class__', None)
                          if cls is not None:
                          cls_name = getattr(cls, '__name__', None)
                          if cls_name is not None:
                          return '%s.%s' % (cls_name, fun_name)
                          return fun_name
                          >
                          --
                          Gabriel Genellina
                          Thanks! I'll try it

                          Agustin

                          Comment

                          • Bruno Desthuilliers

                            #14
                            Re: Showing the method's class in expection's traceback

                            Agustin Villena a écrit :
                            >And not that useful - why would one care about the function being
                            >defined in class X or Y when one have the exact file and line ?
                            >
                            I have 3 reasons:
                            >
                            1) My developing time is expended running unit tests and browsing
                            tracebacks to find which is the real problem. Knowing the offender
                            class (instead of the method alone) makes me understand more quickly
                            which component of my software is failing.
                            This is only true when there is an obvious, one-to-one, unambiguous
                            relationship between the physical location of the error (file, line) and
                            the class of the object the method has been called on. Which is not
                            necessarily the case (inheritance, method decoration and monkeypatching
                            comes to mind here...).

                            Also, your above statement seems to imply that component==clas s, which
                            is not the case in Python.
                            2) There are some ocassions where I only have the traceback (e.g. when
                            analyzing an app's log) and no inmediate access to teh source code
                            Ok. But the above still apply...
                            3) And finally, for completeness: If a function is really a method, if
                            the traceback show only its name and not the class that defines it,
                            for me its a bug, because the method name has no sense out of its
                            class.
                            I'm not sure you really grasp what "methods" are in Python. What you
                            define (using the def statement) within a class is function, not a
                            method. It only becomes a method when it's looked up on an instance or
                            class object, and this 'method' is only a thin wrapper around the
                            instance, class and function objects. And FWIW, you don't need to define
                            the function within the class to make it a method:

                            # bar.py
                            def bar(obj):
                            print "function bar.bar called on obj %s" % obj


                            # foo.py

                            class Foo(object): pass

                            # baaz.py
                            from foo import Foo
                            import bar

                            Foo.baaz = bar.bar

                            def guux(obj):
                            print "function baaz.guux called on obj %s" % obj

                            # main.py
                            from baaz import Foo
                            f = Foo()
                            f.bar()

                            f.gnix = baae.guux.__get __(f, type(f))
                            f.gnix()



                            Not to say that your concerns are pointless, and that things cannot be
                            improved somehow, but this is not that trivial, and there may be
                            ambuiguities in some not so rare cases.

                            Comment

                            • Duncan Booth

                              #15
                              Re: Showing the method's class in expection's traceback

                              Bruno Desthuilliers <bruno.42.desth uilliers@websit eburo.invalidwr ote:
                              Not to say that your concerns are pointless, and that things cannot be
                              improved somehow, but this is not that trivial, and there may be
                              ambuiguities in some not so rare cases.
                              It might be worth considering an alternative approach here: a formatted
                              exception includes the relevant source lines (where possible).

                              The source lines are cached by the module linecache.py and it probably
                              wouldn't be too hard to build on the line cache so that it also scans the
                              source lines looking for class statements and recording the start and end
                              line numbers for each class.

                              That way any classname displayed would be based on the actual source
                              nesting and even static methods or functions injected from another class
                              would work 'correctly' (at some level).

                              --
                              Duncan Booth http://kupuguy.blogspot.com

                              Comment

                              Working...