New inited instance of class?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Samuel Kleiner

    New inited instance of class?

    Is there a builtin way of making making another instance of your own
    class? I really expected type(self)(*arg s, **keywords) to work this way.
    Currently i'm doing this:

    def new(self,*args, **keywords):
    from new import instance
    s=instance(self .__class__)
    if hasattr(D(),'__ init__'):
    s.__init__(*arg s,**keywords)
    return s

    --
    "You have to impress him! Be independent and plucky, but often do
    things that are moronic and out of character!"
    --50s Diana Dane to 90s Diana Dane
  • Douglas Alan

    #2
    Re: New inited instance of class?

    Samuel Kleiner <sam@samuel-kleiners-computer.local> writes:
    [color=blue]
    > Is there a builtin way of making making another instance of your own
    > class? I really expected type(self)(*arg s, **keywords) to work this way.[/color]

    Doesn't self.__class__( *args, **keywords) work?

    |>oug

    Comment

    • Francis Avila

      #3
      Re: New inited instance of class?


      Samuel Kleiner wrote in message ...[color=blue]
      >Is there a builtin way of making making another instance of your own
      >class?[/color]

      You mean, from the inside (from one of the instance methods of the class)?

      def new(self, *args, **kargs):
      return self.__class__( *args, **kargs)
      [color=blue]
      >I really expected type(self)(*arg s, **keywords) to work this way.[/color]

      Works for me. What traceback does it give you?
      [color=blue]
      >Currently i'm doing this:
      >
      >def new(self,*args, **keywords):
      > from new import instance
      > s=instance(self .__class__)
      > if hasattr(D(),'__ init__'):
      > s.__init__(*arg s,**keywords)
      > return s[/color]

      That's ugly.

      --
      Francis Avila

      Comment

      • Samuel Kleiner

        #4
        Re: New inited instance of class?

        Francis Avila wrote:[color=blue]
        >
        > Samuel Kleiner wrote in message ...[color=green]
        >>Is there a builtin way of making making another instance of your own
        >>class?[/color]
        >
        > You mean, from the inside (from one of the instance methods of the class)?[/color]

        Yes.
        [color=blue]
        > def new(self, *args, **kargs):
        > return self.__class__( *args, **kargs)[/color]

        This works. Thanks.
        [color=blue][color=green]
        >>I really expected type(self)(*arg s, **keywords) to work this way.[/color]
        >
        > Works for me. What traceback does it give you?[/color]

        Not for me. I really want to call it as the function itself, and

        type(self)(argu ment1,argument2 ,argument3)

        fails with

        Traceback (most recent call last):
        File "<stdin>", line 139, in ?
        File "<stdin>", line 78, in __add__
        TypeError: instance() takes at most 2 arguments (3 given)

        whereas

        self.__class__( argument1,argum ent2,argument3)

        does not
        [color=blue][color=green]
        >>Currently i'm doing this:
        >>
        >>[my code][/color]
        > That's ugly.[/color]

        Yes.

        --
        On an encouraging note, however, I found that throughout the source code,
        extremely conservative coding practices and good error checking everywhere
        means that our software does not crash when handling IPv6 addresses.
        --Joe Loughry, Lockheed Martin Space and Strategic Missiles, RADIANT MERCURY

        Comment

        • Francis Avila

          #5
          Re: New inited instance of class?

          Samuel Kleiner wrote in message ...[color=blue]
          >Not for me. I really want to call it as the function itself, and
          >
          >type(self)(arg ument1,argument 2,argument3)
          >
          >fails with
          >
          >Traceback (most recent call last):
          > File "<stdin>", line 139, in ?
          > File "<stdin>", line 78, in __add__
          >TypeError: instance() takes at most 2 arguments (3 given)[/color]

          Ah! You're using classic classes. Don't do that.

          Observe:
          [color=blue][color=green][color=darkred]
          >>> class classic: pass
          >>> type(classic)[/color][/color][/color]
          <type 'classobj'>[color=blue][color=green][color=darkred]
          >>> type(classic())[/color][/color][/color]
          <type 'instance'>[color=blue][color=green][color=darkred]
          >>> classic().__cla ss__[/color][/color][/color]
          <class __main__.classi c at 0x00F58030>
          [color=blue][color=green][color=darkred]
          >>> class newstyle(object ): pass
          >>> type(newstyle)[/color][/color][/color]
          <type 'type'>[color=blue][color=green][color=darkred]
          >>> type(newstyle() )[/color][/color][/color]
          <class '__main__.newst yle'>[color=blue][color=green][color=darkred]
          >>> newstyle().__cl ass__[/color][/color][/color]
          <class '__main__.newst yle'>[color=blue][color=green][color=darkred]
          >>>[/color][/color][/color]

          If you're curious, look in the Python Language Reference at the old and new
          style classes to see the differences. There's absolutely no advantage to
          old style classes, so stop usin' 'em.

          There's a grand old intro (by Guido) to new-style classes at python.org,
          linked from "What's New" in the 2.3 docs. I keep hunting for that link: it
          really should be in the distributed docs, because it's vital for
          understanding the still poorly-documented new-style classes.
          --
          Francis Avila

          Comment

          • Samuel Kleiner

            #6
            Re: New inited instance of class?

            Francis Avila wrote:
            [color=blue]
            > Ah! You're using classic classes. Don't do that.[/color]

            Ok, thanks-

            So can I make all my classes derive from object without
            doing so explicitly- IE, without having to change every
            single top-level class definition?

            --
            Loren ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
            nonummy nibh eusmod tincidunt ut laoreet dolore magna aliquam erat
            volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation

            Comment

            • Francis Avila

              #7
              Re: New inited instance of class?

              Samuel Kleiner wrote in message ...[color=blue]
              >Francis Avila wrote:
              >[color=green]
              >> Ah! You're using classic classes. Don't do that.[/color]
              >
              >Ok, thanks-
              >
              >So can I make all my classes derive from object without
              >doing so explicitly- IE, without having to change every
              >single top-level class definition?[/color]

              I doubt it. But I think sed or re could take care of that quite easily with
              a search/replace.

              Besides, "explicit is better than implicit." ;)
              --
              Francis Avila

              Comment

              • Peter Otten

                #8
                Re: New inited instance of class?

                Samuel Kleiner wrote:
                [color=blue]
                > So can I make all my classes derive from object without
                > doing so explicitly- IE, without having to change every
                > single top-level class definition?
                >[/color]

                You can do it on a per-file basis by putting

                __metaclass__ = type

                once before the class definitions.

                Peter

                Comment

                • Fredrik Lundh

                  #9
                  Re: New inited instance of class?

                  Francis Avila wrote:
                  [color=blue]
                  > If you're curious, look in the Python Language Reference at the old and new
                  > style classes to see the differences. There's absolutely no advantage to
                  > old style classes[/color]

                  except performance:

                  The official home of the Python Programming Language

                  [color=blue]
                  > it's vital for understanding the still poorly-documented new-style classes.[/color]

                  documentation may also be seen as an advantage, of course.

                  </F>




                  Comment

                  • Aahz

                    #10
                    Re: New inited instance of class?

                    In article <vt5b8npantkt35 @corp.supernews .com>,
                    Francis Avila <francisgavila@ yahoo.com> wrote:[color=blue]
                    >
                    >If you're curious, look in the Python Language Reference at the old
                    >and new style classes to see the differences. There's absolutely no
                    >advantage to old style classes, so stop usin' 'em.[/color]

                    <raised eyebrow> In addition to the factors Fredrik mentioned, there's
                    also the issue that new-style classes are more of a moving target WRT
                    syntax and semantics; for complex uses, it can be tricky (or impossible)
                    to get the same code working the same way on both 2.2 and 2.3.

                    More than that, you *can't* use new-style classes for exceptions. So
                    please stop telling people to avoid classic classes.
                    --
                    Aahz (aahz@pythoncra ft.com) <*> http://www.pythoncraft.com/

                    Weinberg's Second Law: If builders built buildings the way programmers wrote
                    programs, then the first woodpecker that came along would destroy civilization.

                    Comment

                    • Samuel Kleiner

                      #11
                      Re: New inited instance of class?

                      Peter Otten wrote:[color=blue]
                      > Samuel Kleiner wrote:
                      >[color=green]
                      >> So can I make all my classes derive from object without
                      >> doing so explicitly- IE, without having to change every
                      >> single top-level class definition?
                      >>[/color]
                      >
                      > You can do it on a per-file basis by putting
                      >
                      > __metaclass__ = type
                      >[/color]
                      That's what I meant. Great, thanks.

                      --
                      "You've got to kill people,
                      and when you've killed enough they stop fighting." --Curtis LeMay

                      Comment

                      • Francis Avila

                        #12
                        Re: New inited instance of class?

                        Peter Otten <__peter__@web. de> wrote in message ...[color=blue]
                        >Samuel Kleiner wrote:[color=green]
                        >> So can I make all my classes derive from object without
                        >> doing so explicitly- IE, without having to change every
                        >> single top-level class definition?
                        >>[/color]
                        >
                        >You can do it on a per-file basis by putting
                        >
                        >__metaclass_ _ = type
                        >
                        >once before the class definitions.[/color]

                        That strikes me as a very *bad* idea, because it's no longer obvious that
                        the classes themselves are new-style, and the OP might develop a bad habit
                        of using this to avoid typing '(object)' all the time. (Or he might show us
                        all for fools, if ':' becomes shorthand for '(object):'.)

                        Aside from that, metaclasses are a more advanced and less-commonly-used
                        feature of classes, and therefore probably more vulnerable to change. I
                        know it should work, but am uneasy that it might manifest some unexpected
                        behavior (or bug).
                        --
                        Francis Avila

                        Comment

                        • Francis Avila

                          #13
                          Re: New inited instance of class?

                          Fredrik Lundh wrote in message ...[color=blue]
                          >Francis Avila wrote:
                          >[color=green]
                          >> If you're curious, look in the Python Language Reference at the old and[/color][/color]
                          new[color=blue][color=green]
                          >> style classes to see the differences. There's absolutely no advantage to
                          >> old style classes[/color]
                          >
                          >except performance:
                          >
                          >http://www.python.org/~jeremy/weblog/030506.html[/color]

                          That's not a big difference, and in any case:

                          00000000

                          Creation of new-style instances is faster. I seem to recall Alex Martelli
                          also thinking that new-style classes are faster all-around. In any case,
                          he's gung-ho on new-style classes, even more than I am.
                          [color=blue][color=green]
                          >> it's vital for understanding the still poorly-documented new-style[/color][/color]
                          classes.[color=blue]
                          >
                          >documentatio n may also be seen as an advantage, of course.[/color]

                          True, but unless one is doing something elaborate (can't even think *what*)
                          or relies on the old mro, the only difference is that base classes will
                          derive from object. If there is code that depends upon the old mro, it
                          should probably be fixed anyway.

                          And it's probably not a problem. From "What's new in 2.3", section 16:
                          """
                          The method resolution order used by new-style classes has changed, though
                          you'll only notice the difference if you have a really complicated
                          inheritance hierarchy. Classic classes are unaffected by this change. Python
                          2.2 originally used a topological sort of a class's ancestors, but 2.3 now
                          uses the C3 algorithm as described in the paper ``A Monotonic Superclass
                          Linearization for Dylan''. To understand the motivation for this change,
                          read Michele Simionato's article ``Python 2.3 Method Resolution Order'', or
                          read the thread on python-dev starting with the message at
                          http://mail.python.org/pipermail/pyt...er/029035.html.
                          Samuele Pedroni first pointed out the problem and also implemented the fix
                          by coding the C3 algorithm. """

                          So I still stand by the claim that one should stop using old-style classes.
                          Changing old-style to new-style classes is more problematic, but I don't see
                          that it's much more. If the code is old enough to use changed/depreciated
                          pre-2.2 features, changing classic classes to new-style is the least of your
                          problems. But if it's 2.2 code, the jump to 2.3 is small and nothing but an
                          advantage--only a policy decision should keep anyone in 2.2.

                          What are the serious compatibility problems with changing an old-style class
                          to a new-style class (which I haven't encountered)? My understanding is
                          that the headaches are from *mixing* classic and new-style classes in the
                          same hieararchy.
                          --
                          Francis Avila

                          Comment

                          • Francis Avila

                            #14
                            Re: New inited instance of class?

                            Aahz wrote in message ...[color=blue]
                            >In article <vt5b8npantkt35 @corp.supernews .com>,
                            >Francis Avila <francisgavila@ yahoo.com> wrote:[color=green]
                            >>
                            >>If you're curious, look in the Python Language Reference at the old
                            >>and new style classes to see the differences. There's absolutely no
                            >>advantage to old style classes, so stop usin' 'em.[/color]
                            >
                            ><raised eyebrow> In addition to the factors Fredrik mentioned,[/color]

                            I responded to those concerns separately.
                            [color=blue]
                            >there's
                            >also the issue that new-style classes are more of a moving target WRT
                            >syntax and semantics; for complex uses, it can be tricky (or impossible)
                            >to get the same code working the same way on both 2.2 and 2.3.[/color]

                            True, but if you are coding for both 2.2 and 2.3, you have to avoid a great
                            deal more than new-style classes (but, what changed besides the mro?). If
                            we're worried about compatability with pre-2.2, shouldn't we not be using
                            __class__ either? Barring trying to get code running on 2.2, it seems we
                            should be coding for new-style classes where possible, and it's possible
                            almost everywhere. Classic classes are on their way out, and eight more
                            keystrokes now means fewer headaches later.
                            [color=blue]
                            >More than that, you *can't* use new-style classes for exceptions.[/color]

                            Exceptions should be derived from Exception or a subclass thereof, so
                            whether they're new- or old-style is not an issue. When Python supports
                            new-style class exceptions, Exception will be changed to reflect that.
                            [color=blue]
                            >So
                            >please stop telling people to avoid classic classes.[/color]

                            Someone better tell Alex Martelli, too, because IIRC he is far more gung-ho
                            on using new-style classes absolutely everywhere than I am. I believe he
                            said the only time he uses them is when he forgets to type (object), which
                            is about where I'm at.
                            --
                            Francis Avila

                            Comment

                            • Peter Otten

                              #15
                              Re: New inited instance of class?

                              Francis Avila wrote:
                              [color=blue][color=green]
                              >>You can do it on a per-file basis by putting
                              >>
                              >>__metaclass __ = type
                              >>
                              >>once before the class definitions.[/color]
                              >
                              > That strikes me as a very *bad* idea, because it's no longer obvious that
                              > the classes themselves are new-style, and the OP might develop a bad habit
                              > of using this to avoid typing '(object)' all the time. (Or he might show
                              > us all for fools, if ':' becomes shorthand for '(object):'.)[/color]

                              I indeed expect the classic/new-style class schism to go away even before
                              3.0 and am looking forward to remove both (object) in class A(object): and
                              __metaclass__ = type, which I expect to be equally *not* hard :-)
                              [color=blue]
                              > Aside from that, metaclasses are a more advanced and less-commonly-used
                              > feature of classes, and therefore probably more vulnerable to change. I
                              > know it should work, but am uneasy that it might manifest some unexpected
                              > behavior (or bug).[/color]

                              For the above recipe to work you need not know what metaclasses are. I'm not
                              in the ignorance is good camp, though. The more people play with
                              metaclasses (are there any in production yet?), the sooner the strengths
                              and weaknesses of this construct will reveal.

                              If you have the appropriate tests and can make your program pass them by
                              providing an explicit object superclass instead of the __metaclass__ line,
                              the fix should be a breeze.


                              Peter

                              Comment

                              Working...