identifying new not inherited methods

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • malkarouri@gmail.com

    #1

    identifying new not inherited methods

    Hi,

    I am writing a library in which I need to find the names of methods
    which are implemented in a class, rather than inherited from another
    class. To explain more, and to find if there is another way of doing
    it, here is what I want to do: I am defining two classes, say A and B,
    as:

    class A(object):
    def list_cmds(self) :
    'implementation needed'
    ?
    def __init__(self):
    ... (rest of class)

    class B(A):
    def cmd1(self, args):
    pass
    def cmd2(self, args):
    pass

    I need an implementation of list_cmds in A above so that I can get a
    result:
    >>b=B()
    >>b.list_cmds ()
    ['cmd1','cmd2'] #order not important

    I will be happy if anybody can point to me any way of doing it, using
    class attributes, metaclasses or otherwise. What I don't want to do is
    modifying class B, which contains just the cmds, if possible.

    Many thanks in advance.

    k

  • George Sakkis

    #2
    Re: identifying new not inherited methods

    malkaro...@gmai l.com wrote:
    Hi,
    >
    I am writing a library in which I need to find the names of methods
    which are implemented in a class, rather than inherited from another
    class. To explain more, and to find if there is another way of doing
    it, here is what I want to do: I am defining two classes, say A and B,
    as:
    >
    class A(object):
    def list_cmds(self) :
    'implementation needed'
    ?
    def __init__(self):
    ... (rest of class)
    >
    class B(A):
    def cmd1(self, args):
    pass
    def cmd2(self, args):
    pass
    >
    I need an implementation of list_cmds in A above so that I can get a
    result:
    >
    >b=B()
    >b.list_cmds( )
    ['cmd1','cmd2'] #order not important
    >
    I will be happy if anybody can point to me any way of doing it, using
    class attributes, metaclasses or otherwise. What I don't want to do is
    modifying class B, which contains just the cmds, if possible.
    >
    Many thanks in advance.
    >
    k
    I'd rather have it as a function, not attached to a specific class:

    from inspect import getmembers, ismethod

    def listMethods(obj ):
    d = obj.__class__._ _dict__
    return [name for name,_ in getmembers(obj, ismethod) if name in d]

    HTH,
    George

    Comment

    • Fredrik Lundh

      #3
      Re: identifying new not inherited methods

      malkarouri@gmai l.com wrote:
      I am writing a library in which I need to find the names of methods
      which are implemented in a class, rather than inherited from another
      class. To explain more, and to find if there is another way of doing
      it, here is what I want to do: I am defining two classes, say A and B,
      as:
      >
      class A(object):
      def list_cmds(self) :
      'implementation needed'
      ?
      def __init__(self):
      ... (rest of class)
      >
      class B(A):
      def cmd1(self, args):
      pass
      def cmd2(self, args):
      pass
      >
      I need an implementation of list_cmds in A above so that I can get a
      result:
      >
      >>>b=B()
      >>>b.list_cmds( )
      ['cmd1','cmd2'] #order not important
      >
      I will be happy if anybody can point to me any way of doing it, using
      class attributes, metaclasses or otherwise. What I don't want to do is
      modifying class B, which contains just the cmds, if possible.
      assuming that you want *all* methods that starts with "cmd", from all
      classes (including any commands in class A), you can do

      def list_cmds(self) :
      # get all names
      names = dir(self)
      # filter out the commands
      names = [name for name in names if name.startswith ("cmd")]
      return names

      if the command methods can have any arbitrary names, change the test to
      filter out the methods you're not interested in. it's usually easier to
      make sure that all commands use a common name prefix, though.

      and yes, if you haven't done so already, take a look at the "cmd" module
      before you build your own variant:



      hope this helps!

      </F>

      Comment

      • Tim Chase

        #4
        Re: identifying new not inherited methods

        I am writing a library in which I need to find the names of methods
        which are implemented in a class, rather than inherited from another
        class. To explain more, and to find if there is another way of doing
        it, here is what I want to do: I am defining two classes, say A and B,
        as:
        >
        class A(object):
        def list_cmds(self) :
        'implementation needed'
        ?
        def __init__(self):
        ... (rest of class)
        >
        class B(A):
        def cmd1(self, args):
        pass
        def cmd2(self, args):
        pass
        >
        I need an implementation of list_cmds in A above so that I can get a
        result:
        >
        >>>b=B()
        >>>b.list_cmds( )
        ['cmd1','cmd2'] #order not important
        While I'm not sure if this is the best/most-pythonic way to do
        it, but it did it for me:


        ############### ############### ############### ############### #
        class A(object):
        def list_cmds(self) :
        root_cmds = set(dir(A))
        child_cmds = set(dir(self))
        return list(child_cmds - root_cmds)
        def __init__(self):
        pass

        class B(A):
        def cmd1(self, args):
        pass
        def cmd2(self, args):
        pass

        b = B()
        print repr(b.list_cmd s())
        ############### ############### ############### ############### #


        If you have multiple inheritance going on, and you only want the
        methods that the child adds, you might try something like



        ############### ############### ############### ############### #
        class A(object):
        def list_cmds(self) :
        parent_cmds = set()
        for base in self.__class__. __bases__:
        parent_cmds.upd ate(dir(base))
        child_cmds = set(dir(self))
        return list(child_cmds - parent_cmds)
        def __init__(self):
        pass

        class C(object):
        def foo1(self, args): pass
        def foo2(self, args): pass

        class B(A, C):
        def cmd1(self, args):
        pass
        def cmd2(self, args):
        pass

        b = B()
        print repr(b.list_cmd s())

        ############### ############### ############### ############### #

        Just a few ideas,

        -tkc




        Comment

        • Steve Holden

          #5
          Re: identifying new not inherited methods

          malkarouri@gmai l.com wrote:
          Hi,
          >
          I am writing a library in which I need to find the names of methods
          which are implemented in a class, rather than inherited from another
          class. To explain more, and to find if there is another way of doing
          it, here is what I want to do: I am defining two classes, say A and B,
          as:
          >
          class A(object):
          def list_cmds(self) :
          'implementation needed'
          ?
          def __init__(self):
          ... (rest of class)
          >
          class B(A):
          def cmd1(self, args):
          pass
          def cmd2(self, args):
          pass
          >
          I need an implementation of list_cmds in A above so that I can get a
          result:
          >
          >
          >>>>b=B()
          >>>>b.list_cmds ()
          >
          ['cmd1','cmd2'] #order not important
          >
          I will be happy if anybody can point to me any way of doing it, using
          class attributes, metaclasses or otherwise. What I don't want to do is
          modifying class B, which contains just the cmds, if possible.
          >
          Many thanks in advance.
          >
          $ cat test01.py
          class A(object):
          def list_cmds(self) :
          """return callable attributes from
          subclasses not present in main class."""
          Amethods = [m for m in dir(A) if callable(getatt r(A, m))]
          return [m for m in dir(self.__clas s__)
          if callable(getatt r(self.__class_ _, m))
          and m not in Amethods]
          def __init__(self):
          pass

          class B(A):
          def cmd1(self, args):
          pass
          def cmd2(self, args):
          pass

          print "A additionals:", A().list_cmds()
          print "B additionals:", B().list_cmds()


          sholden@bigboy ~
          $ python test01.py
          A additionals: []
          B additionals: ['cmd1', 'cmd2']

          sholden@bigboy ~
          $

          Hope this helps.

          regards
          Steve
          --
          Steve Holden +44 150 684 7255 +1 800 494 3119
          Holden Web LLC/Ltd http://www.holdenweb.com
          Skype: holdenweb http://holdenweb.blogspot.com
          Recent Ramblings http://del.icio.us/steve.holden

          Comment

          • Chaz Ginger

            #6
            Re: identifying new not inherited methods

            Steve Holden wrote:
            malkarouri@gmai l.com wrote:
            >Hi,
            >>
            >I am writing a library in which I need to find the names of methods
            >which are implemented in a class, rather than inherited from another
            >class. To explain more, and to find if there is another way of doing
            >it, here is what I want to do: I am defining two classes, say A and B,
            >as:
            >>
            >class A(object):
            > def list_cmds(self) :
            > 'implementation needed'
            > ?
            > def __init__(self):
            > ... (rest of class)
            >>
            >class B(A):
            > def cmd1(self, args):
            > pass
            > def cmd2(self, args):
            > pass
            >>
            >I need an implementation of list_cmds in A above so that I can get a
            >result:
            >>
            >>
            >>>>b=B()
            >>>>b.list_cmds ()
            >>
            >['cmd1','cmd2'] #order not important
            >>
            >I will be happy if anybody can point to me any way of doing it, using
            >class attributes, metaclasses or otherwise. What I don't want to do is
            >modifying class B, which contains just the cmds, if possible.
            >>
            >Many thanks in advance.
            >>
            $ cat test01.py
            class A(object):
            def list_cmds(self) :
            """return callable attributes from
            subclasses not present in main class."""
            Amethods = [m for m in dir(A) if callable(getatt r(A, m))]
            return [m for m in dir(self.__clas s__)
            if callable(getatt r(self.__class_ _, m))
            and m not in Amethods]
            def __init__(self):
            pass
            >
            class B(A):
            def cmd1(self, args):
            pass
            def cmd2(self, args):
            pass
            >
            print "A additionals:", A().list_cmds()
            print "B additionals:", B().list_cmds()
            >
            >
            sholden@bigboy ~
            $ python test01.py
            A additionals: []
            B additionals: ['cmd1', 'cmd2']
            >
            sholden@bigboy ~
            $
            >
            Hope this helps.
            >
            regards
            Steve
            You don't really want to use dir(A), since this will not pick up all the
            classes that make up A. Don't you want to use the MRO instead?

            Chaz

            Comment

            • Chaz Ginger

              #7
              Re: identifying new not inherited methods

              Steve Holden wrote:
              malkarouri@gmai l.com wrote:
              >Hi,
              >>
              >I am writing a library in which I need to find the names of methods
              >which are implemented in a class, rather than inherited from another
              >class. To explain more, and to find if there is another way of doing
              >it, here is what I want to do: I am defining two classes, say A and B,
              >as:
              >>
              >class A(object):
              > def list_cmds(self) :
              > 'implementation needed'
              > ?
              > def __init__(self):
              > ... (rest of class)
              >>
              >class B(A):
              > def cmd1(self, args):
              > pass
              > def cmd2(self, args):
              > pass
              >>
              >I need an implementation of list_cmds in A above so that I can get a
              >result:
              >>
              >>
              >>>>b=B()
              >>>>b.list_cmds ()
              >>
              >['cmd1','cmd2'] #order not important
              >>
              >I will be happy if anybody can point to me any way of doing it, using
              >class attributes, metaclasses or otherwise. What I don't want to do is
              >modifying class B, which contains just the cmds, if possible.
              >>
              >Many thanks in advance.
              >>
              $ cat test01.py
              class A(object):
              def list_cmds(self) :
              """return callable attributes from
              subclasses not present in main class."""
              Amethods = [m for m in dir(A) if callable(getatt r(A, m))]
              return [m for m in dir(self.__clas s__)
              if callable(getatt r(self.__class_ _, m))
              and m not in Amethods]
              def __init__(self):
              pass
              >
              class B(A):
              def cmd1(self, args):
              pass
              def cmd2(self, args):
              pass
              >
              print "A additionals:", A().list_cmds()
              print "B additionals:", B().list_cmds()
              >
              >
              sholden@bigboy ~
              $ python test01.py
              A additionals: []
              B additionals: ['cmd1', 'cmd2']
              >
              sholden@bigboy ~
              $
              >
              Hope this helps.
              >
              regards
              Steve
              You don't really want to use dir(A), since this will not pick up all the
              classes that make up A. Don't you want to use the MRO instead?

              Chaz

              Comment

              • malkarouri@gmail.com

                #8
                Re: identifying new not inherited methods

                George Sakkis wrote:
                [...]
                I'd rather have it as a function, not attached to a specific class:
                >
                Thanks a lot George, that was what I was looking for. Got to
                understand/appreciate inspect more.
                Of course it works as a method. So, other than having it as a general
                utility, I presume there is no special reason to have it as a function
                rather than a method..


                Fredrik Lundh wrote:
                [...]
                if the command methods can have any arbitrary names, change the test to
                filter out the methods you're not interested in. it's usually easier to
                make sure that all commands use a common name prefix, though.
                Thanks a lot FL. I have actually gone down this road first. But I don't
                want to use a common prefix, and filtering methods out feels for me a
                probable bug source, as in remembering whenever I add a method to class
                A I need to add it to the filter.
                and yes, if you haven't done so already, take a look at the "cmd" module
                before you build your own variant:
                >
                http://effbot.org/librarybook/cmd.htm
                Thanks again. I know I am doing a cmd variant. Actually, that's exactly
                where I started, with your cmd module page.
                The reason I am doing this is mainly to use a cmd variant decoupled
                from stdin/stdout, to hook in PyShell or IPython (not decided yet). Is
                there a way to use cmd without assuming stdin/stdout?

                Regards,

                k

                Comment

                • George Sakkis

                  #9
                  Re: identifying new not inherited methods

                  malkarouri@gmai l.com wrote:
                  George Sakkis wrote:
                  [...]
                  I'd rather have it as a function, not attached to a specific class:
                  >
                  Thanks a lot George, that was what I was looking for. Got to
                  understand/appreciate inspect more.
                  Of course it works as a method. So, other than having it as a general
                  utility, I presume there is no special reason to have it as a function
                  rather than a method..
                  You're looking at it backwards; there's no particular reason this
                  should be a method of class A since it can be used for any arbitrary
                  object with no extra overhead. Now, if you intend to use it only for
                  instances of A and its subclasses, the only difference would be
                  syntactic; if you prefer x.list_cmds() from list_cmds(x), go with the
                  method.

                  George

                  Comment

                  • Steve Holden

                    #10
                    Re: identifying new not inherited methods

                    Chaz Ginger wrote:
                    Steve Holden wrote:
                    >
                    >>malkarouri@gm ail.com wrote:
                    >>
                    >>>Hi,
                    >>>
                    >>>I am writing a library in which I need to find the names of methods
                    >>>which are implemented in a class, rather than inherited from another
                    >>>class. [...]
                    >
                    >
                    You don't really want to use dir(A), since this will not pick up all the
                    classes that make up A. Don't you want to use the MRO instead?
                    >
                    Tell me, what won't appear in the dir() of A that *will* appear in the
                    dir() of a subclass of A? Seems to me you're trying to overcomplicate
                    things.

                    regards
                    Steve
                    --
                    Steve Holden +44 150 684 7255 +1 800 494 3119
                    Holden Web LLC/Ltd http://www.holdenweb.com
                    Skype: holdenweb http://holdenweb.blogspot.com
                    Recent Ramblings http://del.icio.us/steve.holden

                    Comment

                    • Chaz Ginger

                      #11
                      Re: identifying new not inherited methods

                      Steve Holden wrote:
                      Chaz Ginger wrote:
                      >Steve Holden wrote:
                      >>
                      >>malkarouri@gmai l.com wrote:
                      >>>
                      >>>Hi,
                      >>>>
                      >>>I am writing a library in which I need to find the names of methods
                      >>>which are implemented in a class, rather than inherited from another
                      >>>class. [...]
                      >>
                      >>
                      >You don't really want to use dir(A), since this will not pick up all
                      >the classes that make up A. Don't you want to use the MRO instead?
                      >>
                      Tell me, what won't appear in the dir() of A that *will* appear in the
                      dir() of a subclass of A? Seems to me you're trying to overcomplicate
                      things.
                      >
                      regards
                      Steve
                      You are right...I just never did a dir(class) before, instead relying on
                      using the MRO to do the searching. dir(class) is certainly a lot
                      simpler! Thanks.

                      Comment

                      • Chaz Ginger

                        #12
                        Re: identifying new not inherited methods

                        Steve Holden wrote:
                        Chaz Ginger wrote:
                        >Steve Holden wrote:
                        >>
                        >>malkarouri@gmai l.com wrote:
                        >>>
                        >>>Hi,
                        >>>>
                        >>>I am writing a library in which I need to find the names of methods
                        >>>which are implemented in a class, rather than inherited from another
                        >>>class. [...]
                        >>
                        >>
                        >You don't really want to use dir(A), since this will not pick up all
                        >the classes that make up A. Don't you want to use the MRO instead?
                        >>
                        Tell me, what won't appear in the dir() of A that *will* appear in the
                        dir() of a subclass of A? Seems to me you're trying to overcomplicate
                        things.
                        >
                        regards
                        Steve
                        You are right...I just never did a dir(class) before, instead relying on
                        using the MRO to do the searching. dir(class) is certainly a lot
                        simpler! Thanks.

                        Comment

                        • John Roth

                          #13
                          Re: identifying new not inherited methods


                          malkarouri@gmai l.com wrote:
                          Hi,
                          >
                          I am writing a library in which I need to find the names of methods
                          which are implemented in a class, rather than inherited from another
                          class. To explain more, and to find if there is another way of doing
                          it, here is what I want to do: I am defining two classes, say A and B,
                          as:
                          >
                          class A(object):
                          def list_cmds(self) :
                          'implementation needed'
                          ?
                          def __init__(self):
                          ... (rest of class)
                          >
                          class B(A):
                          def cmd1(self, args):
                          pass
                          def cmd2(self, args):
                          pass
                          >
                          I need an implementation of list_cmds in A above so that I can get a
                          result:
                          >
                          >b=B()
                          >b.list_cmds( )
                          ['cmd1','cmd2'] #order not important
                          >
                          I will be happy if anybody can point to me any way of doing it, using
                          class attributes, metaclasses or otherwise. What I don't want to do is
                          modifying class B, which contains just the cmds, if possible.
                          >
                          Many thanks in advance.
                          >
                          k
                          When I want to do this, I scan the __dict__
                          attribute of the class. If all you care about is
                          instance methods (which is all I care about
                          at the moment), they're just ordinary functions.
                          Do an isinstance and you've got it.

                          If you want to dig deeper and look at class
                          methods, static methods, descriptors and
                          other stuff, it's a bit more complicated, but
                          not much.

                          John Roth
                          Python FIT

                          Comment

                          • malkarouri@gmail.com

                            #14
                            Re: identifying new not inherited methods

                            George Sakkis wrote:
                            [...]
                            You're looking at it backwards; there's no particular reason this
                            should be a method of class A since it can be used for any arbitrary
                            object with no extra overhead. Now, if you intend to use it only for
                            instances of A and its subclasses, the only difference would be
                            syntactic; if you prefer x.list_cmds() from list_cmds(x), go with the
                            method.
                            You are right of course. Let's say it's just bad company; the group I
                            am working with are mainly Java developers.

                            k

                            Comment

                            Working...