__dict__ for instances?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ivan Voras

    #1

    __dict__ for instances?

    While using PyGTK, I want to try and define signal handlers
    automagically, without explicitly writing the long dictionary (i.e. I
    want to use signal_autoconn ect()).

    To do this, I need something that will inspect the current "self" and
    return a dictionary that looks like:

    {
    "method_nam e" : self.method_nam e
    }

    Class.__dict__ does something very similar, but when I use it, either
    I'm doing something wrong or it doesn't return methods bound to "self",
    and python complains a wrong number of arguments is being passed to the
    methods (one instead of two).

    instance.__dict __ on the other hand returns an empty dictionary.

    This looks like it should be easy, but I can't find the solution :(

    --
    (\__/)
    (O.o)
    (< )

    This is Bunny.
    Copy Bunny into your signature to help him on his way to world domination!


    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.4.4 (MingW32)
    Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

    iD8DBQFGRlnFldn AQVacBcgRAugIAJ 0aqM6ZNKeUZUFCu r7ODEbGcMFvCgCg xze2
    LCUqdGi4nCvZrwn Fru2To6Y=
    =+8Zd
    -----END PGP SIGNATURE-----

  • half.italian@gmail.com

    #2
    Re: __dict__ for instances?

    On May 12, 5:20 pm, Ivan Voras <ivoras@__fer.h r__wrote:
    While using PyGTK, I want to try and define signal handlers
    automagically, without explicitly writing the long dictionary (i.e. I
    want to use signal_autoconn ect()).
    >
    To do this, I need something that will inspect the current "self" and
    return a dictionary that looks like:
    >
    {
    "method_nam e" : self.method_nam e
    >
    }
    >
    Class.__dict__ does something very similar, but when I use it, either
    I'm doing something wrong or it doesn't return methods bound to "self",
    and python complains a wrong number of arguments is being passed to the
    methods (one instead of two).
    >
    instance.__dict __ on the other hand returns an empty dictionary.
    >
    This looks like it should be easy, but I can't find the solution :(
    >
    --
    (\__/)
    (O.o)
    (< )
    >
    This is Bunny.
    Copy Bunny into your signature to help him on his way to world domination!
    >
    signature.asc
    1KDownload
    I think you want "dir(instan ce)" __dict__ returns the instance
    variables and values as a dictionary, but doesn't return methods.
    dir() returns a list of the instance's methods and variables. Then
    you'd need to iterate over the list with type() looking for instance
    methods

    instance = Class.Class()
    dict = {}
    methods = [f for f in dir(instance) if str(type(instan ce.f)) == "<type
    'instancemethod '>"]
    for m in methods:
    dict[m.name] = m

    The above is untested. I'm sure there is a better way to do this.

    ~Sean

    Comment

    • Ivan Voras

      #3
      Re: __dict__ for instances?

      half.italian@gm ail.com wrote:
      I think you want "dir(instan ce)" __dict__ returns the instance
      Part of the problem is that dir(instance) returns a list of strings, so
      iterating the dir(instance) gets me strings, not methods. Alternatively,
      is there a way to get a "bound" instance by its name - some
      introspection function perhaps?
      variables and values as a dictionary, but doesn't return methods.
      It does on a Class :(

      --
      (\__/)
      (O.o)
      (< )

      This is Bunny.
      Copy Bunny into your signature to help him on his way to world domination!


      -----BEGIN PGP SIGNATURE-----
      Version: GnuPG v1.4.4 (MingW32)
      Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

      iD8DBQFGRvbdldn AQVacBcgRAvtoAJ 46Z2Tkwo+MS6khy h9UZ4w2vqbccQCg 11yr
      SbMsN4ezb8lWw3Y z3evcDAc=
      =dxlb
      -----END PGP SIGNATURE-----

      Comment

      • Bruno Desthuilliers

        #4
        Re: __dict__ for instances?

        Ivan Voras a écrit :
        half.italian@gm ail.com wrote:
        >
        >
        >>I think you want "dir(instan ce)" __dict__ returns the instance
        >
        >
        Part of the problem is that dir(instance) returns a list of strings, so
        iterating the dir(instance) gets me strings, not methods. Alternatively,
        is there a way to get a "bound" instance by its name - some
        introspection function perhaps?
        getattr(obj, name)
        >
        >>variables and values as a dictionary, but doesn't return methods.
        >
        >
        It does on a Class :(
        >
        Usually, methods are attributes of the class, not of the instance.

        Comment

        • Bruno Desthuilliers

          #5
          Re: __dict__ for instances?

          Ivan Voras a écrit :
          While using PyGTK, I want to try and define signal handlers
          automagically, without explicitly writing the long dictionary (i.e. I
          want to use signal_autoconn ect()).
          >
          To do this, I need something that will inspect the current "self" and
          return a dictionary that looks like:
          >
          {
          "method_nam e" : self.method_nam e
          }
          >
          Class.__dict__ does something very similar, but when I use it, either
          I'm doing something wrong or it doesn't return methods bound to "self",
          and python complains a wrong number of arguments is being passed to the
          methods (one instead of two).
          You're not doing anything wrong, that's just how Python works. "methods"
          are wrapper objects around function objects attributes. The wrapping
          only happens at lookup time, and returns different kind of "method"
          wrapper (resp. unbound or bound methods) if the attribute is looked up
          on an instance or a class (there are also the staticmethod/classmethod
          things, but that's not your problem here).

          You can build the dict you're looking for using dir() and getattr():

          from types import MethodType

          autoconnect_dic t = {}
          for name in dir(self):
          attr = getattr(self, name)
          if isinstance(attr , MethodType):
          autoconnect_dic t[name] = attr
          return autoconnect_dic t

          instance.__dict __ on the other hand returns an empty dictionary.
          the instance's __dict__ only stores per-instance attributes. While it's
          technically possible to attach methods per-instance, it's definitively a
          corner case.

          Comment

          • Marc Christiansen

            #6
            Re: __dict__ for instances?

            Ivan Voras <ivoras@__fer.h r__scribis:
            While using PyGTK, I want to try and define signal handlers
            automagically, without explicitly writing the long dictionary (i.e. I
            want to use signal_autoconn ect()).
            >
            To do this, I need something that will inspect the current "self" and
            return a dictionary that looks like:
            >
            {
            "method_nam e" : self.method_nam e
            }
            Nope, at least for PyGTK 2 :) See below.

            [...]
            This looks like it should be easy, but I can't find the solution :(
            Use the doc, Luke, oops, Ivan :)
            Citing the gtk.glade.XML.s ignal_autoconne ct documentation:
            def signal_autoconn ect(dict)
            dict: a mapping or an instance
            ^^^^^^^^

            The signal_autoconn ect() method is a variation of the
            gtk.glade.XML.s ignal_connect method. It uses Python's introspective
            features to look at the keys (if dict is a mapping) or attributes (if
            ^^^^^^^^^^^^^^
            dict is an instance) and tries to match them with the signal handler
            ^^^^^^^^^^^^^^^ ^^^^
            names given in the interface description. The callbacks referenced by
            each matched key or attribute are connected to their matching signals.
            The argument is called dict due to compatibility reasons since
            originally only the mapping interface was supported. The instance
            variant was introduced in PyGTK 2.0.

            So simply using signal_autoconn ect(self) should work.

            AdiaÅ­, Marc

            Comment

            • half.italian@gmail.com

              #7
              Re: __dict__ for instances?

              On May 13, 4:30 am, Ivan Voras <ivoras@__fer.h r__wrote:
              half.ital...@gm ail.com wrote:
              I think you want "dir(instan ce)" __dict__ returns the instance
              >
              Part of the problem is that dir(instance) returns a list of strings, so
              iterating the dir(instance) gets me strings, not methods. Alternatively,
              is there a way to get a "bound" instance by its name - some
              introspection function perhaps?
              >
              variables and values as a dictionary, but doesn't return methods.
              >
              It does on a Class :(
              >
              --
              (\__/)
              (O.o)
              (< )
              >
              This is Bunny.
              Copy Bunny into your signature to help him on his way to world domination!
              >
              signature.asc
              1KDownload
              I tried.

              ~Sean

              Comment

              • Ivan Voras

                #8
                Re: __dict__ for instances?

                Marc Christiansen wrote:
                Nope, at least for PyGTK 2 :) See below.
                Aaah, but....!
                [...]
                >This looks like it should be easy, but I can't find the solution :(
                Use the doc, Luke, oops, Ivan :)
                Citing the gtk.glade.XML.s ignal_autoconne ct documentation:
                def signal_autoconn ect(dict)
                dict: a mapping or an instance
                ^^^^^^^^
                I should have mentioned - I tried it already and it didn't work. The
                specific error I get is:

                "WARNING: "on_button_clic ked" not callable or a tuple"

                once for each handler when I call autoconnect. And I've got a recent
                version of pyGTK (2.10.4) so it should.


                --
                (\__/)
                (O.o)
                (< )

                This is Bunny.
                Copy Bunny into your signature to help him on his way to world domination!


                -----BEGIN PGP SIGNATURE-----
                Version: GnuPG v1.4.4 (MingW32)
                Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

                iD8DBQFGR0jOldn AQVacBcgRAvHqAK CdYJxSmCqvyrBXV TPQMc50R5KsMwCf ULkH
                jpSJzgL8qBJRaQI P8xKQrXA=
                =SsEg
                -----END PGP SIGNATURE-----

                Comment

                • Ivan Voras

                  #9
                  Re: __dict__ for instances?

                  Bruno Desthuilliers wrote:
                  You're not doing anything wrong, that's just how Python works. "methods"
                  are wrapper objects around function objects attributes. The wrapping
                  only happens at lookup time, and returns different kind of "method"
                  wrapper (resp. unbound or bound methods) if the attribute is looked up
                  on an instance or a class (there are also the staticmethod/classmethod
                  things, but that's not your problem here).
                  Got it, thanks for the explanation!



                  --
                  (\__/)
                  (O.o)
                  (< )

                  This is Bunny.
                  Copy Bunny into your signature to help him on his way to world domination!


                  -----BEGIN PGP SIGNATURE-----
                  Version: GnuPG v1.4.4 (MingW32)
                  Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

                  iD8DBQFGR0kPldn AQVacBcgRAls/AJ9vyGQG9Hvasr0 Qex5gTl+wDD3gTg CeNBo0
                  GQNo30dEuhwVZax fHitgBv4=
                  =8ZXE
                  -----END PGP SIGNATURE-----

                  Comment

                  • Bruno Desthuilliers

                    #10
                    Re: __dict__ for instances?

                    Ivan Voras a écrit :
                    Marc Christiansen wrote:
                    >
                    >
                    >>Nope, at least for PyGTK 2 :) See below.
                    >
                    >
                    Aaah, but....!
                    >
                    >
                    >>[...]
                    >>
                    >>>This looks like it should be easy, but I can't find the solution :(
                    >>
                    >>Use the doc, Luke, oops, Ivan :)
                    >>Citing the gtk.glade.XML.s ignal_autoconne ct documentation:
                    > def signal_autoconn ect(dict)
                    > dict: a mapping or an instance
                    > ^^^^^^^^
                    >
                    >
                    I should have mentioned - I tried it already and it didn't work. The
                    specific error I get is:
                    >
                    "WARNING: "on_button_clic ked" not callable or a tuple"
                    Please post the relevant code and the full traceback.

                    Comment

                    • Ivan Voras

                      #11
                      Re: __dict__ for instances?

                      Bruno Desthuilliers wrote:
                      >"WARNING: "on_button_clic ked" not callable or a tuple"
                      Please post the relevant code and the full traceback.
                      The code:

                      Class W:
                      def __init__(self):
                      self.xml = gtk.glade.XML(" glade/mainwin.glade")
                      self.window = self.xml.get_wi dget("mainwin")
                      self.xml.signal _autoconnect(se lf)

                      w = W()
                      gtk.main()

                      The error (not an exception, only the message appears and the handler
                      doesn't work):

                      ** (finstall.py:75 51): WARNING **: handler for 'on_button_next _clicked'
                      not callable or a tuple

                      (the file has some 20 lines, not 7551)


                      --
                      (\__/)
                      (O.o)
                      (< )

                      This is Bunny.
                      Copy Bunny into your signature to help him on his way to world domination!


                      -----BEGIN PGP SIGNATURE-----
                      Version: GnuPG v1.4.4 (MingW32)
                      Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

                      iD8DBQFGR5Xqldn AQVacBcgRAu7xAJ 9COrvqgow1O0gcK 6F+AS7rfu/AlwCg3rnI
                      fVb71HKuapkbaE+ cwt+4JT0=
                      =2of5
                      -----END PGP SIGNATURE-----

                      Comment

                      • Bruno Desthuilliers

                        #12
                        Re: __dict__ for instances?

                        Ivan Voras a écrit :
                        Bruno Desthuilliers wrote:
                        >
                        >>"WARNING: "on_button_clic ked" not callable or a tuple"
                        >Please post the relevant code and the full traceback.
                        >
                        The code:
                        >
                        Class W:
                        def __init__(self):
                        self.xml = gtk.glade.XML(" glade/mainwin.glade")
                        self.window = self.xml.get_wi dget("mainwin")
                        self.xml.signal _autoconnect(se lf)
                        >
                        w = W()
                        gtk.main()
                        >
                        The error (not an exception, only the message appears and the handler
                        doesn't work):
                        >
                        ** (finstall.py:75 51): WARNING **: handler for 'on_button_next _clicked'
                        not callable or a tuple
                        Is this the full message, or did you skip the preceding lines ?
                        (the file has some 20 lines, not 7551)
                        >
                        Is "finstall.p y" the name of your file ? If yes, I'd suspect something
                        wrong with your sys.path or like...





                        Comment

                        • Ivan Voras

                          #13
                          Re: __dict__ for instances?

                          Bruno Desthuilliers wrote:
                          >The error (not an exception, only the message appears and the handler
                          >doesn't work):
                          >>
                          >** (finstall.py:75 51): WARNING **: handler for 'on_button_next _clicked'
                          >not callable or a tuple
                          Is this the full message, or did you skip the preceding lines ?
                          The full message.
                          >(the file has some 20 lines, not 7551)
                          >>
                          Is "finstall.p y" the name of your file ? If yes, I'd suspect something
                          wrong with your sys.path or like...
                          This is the name of my file - and it IS executed, only the error message
                          is weird.


                          --
                          (\__/)
                          (O.o)
                          (< )

                          This is Bunny.
                          Copy Bunny into your signature to help him on his way to world domination!


                          -----BEGIN PGP SIGNATURE-----
                          Version: GnuPG v1.4.4 (MingW32)
                          Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

                          iD8DBQFGWKULldn AQVacBcgRArdiAK Dhp9tGfknLb9xoS FLZeFMrj3Cq4wCg k8ET
                          qq91Y8nFcjyC754 5MaAtwM4=
                          =2lug
                          -----END PGP SIGNATURE-----

                          Comment

                          Working...