Brain Dead Singleton

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

    Brain Dead Singleton

    I looked on this newsgroup, and saw all the problems with making a
    Singleton class with Python.

    I don't really care about 'returning the single shared instance' in
    the constructor and all, I just want to avoid being inefficient... so
    I implemented this (code fragment follows):

    class Whatever:
    _singleton = 0
    def __init__(self):
    self.__class__. _singleton += 1
    if self.__class__. _singleton > 1:
    raise Exception("Sing leton!")

    There. I've got it trussed up to where I can't create more than one
    without raising an exception, which works good enough for my purposes.

    --Kamilche
  • Colin Brown

    #2
    Re: Brain Dead Singleton

    "Kamilche" <klachemin@home .com> wrote in message
    news:889cbba0.0 406041333.10402 447@posting.goo gle.com...[color=blue]
    > I looked on this newsgroup, and saw all the problems with making a
    > Singleton class with Python.[/color]

    Whenever I want a singleton "class", I just use a module with functions and
    global variables. Modules only import once.

    Colin Brown
    PyNZ



    Comment

    • Robin Becker

      #3
      Re: Brain Dead Singleton

      Colin Brown wrote:[color=blue]
      > "Kamilche" <klachemin@home .com> wrote in message
      > news:889cbba0.0 406041333.10402 447@posting.goo gle.com...
      >[color=green]
      >>I looked on this newsgroup, and saw all the problems with making a
      >>Singleton class with Python.[/color]
      >
      >
      > Whenever I want a singleton "class", I just use a module with functions and
      > global variables. Modules only import once.
      >
      > Colin Brown
      > PyNZ
      >
      >
      >[/color]
      should often work, but this illustrates how it can go wrong

      ############### ###
      f=open('my_sing leton_module.py ','w')
      f.write('''a=0
      def incr(i):
      global a
      oa = a
      a+=i
      return oa
      ''')
      f.close()

      import my_singleton_mo dule as inst0
      print inst0.a
      inst0.incr(5)
      print inst0.a
      import sys
      del sys.modules['my_singleton_m odule']
      import my_singleton_mo dule as inst1
      print inst1.a
      ############### ###

      so if sys.modules gets interfered with approriately, your singleton can
      start breeding.
      --
      Robin Becker

      Comment

      • Peter Hansen

        #4
        Re: Brain Dead Singleton

        Robin Becker wrote:
        [color=blue]
        > Colin Brown wrote:[color=green]
        >> Whenever I want a singleton "class", I just use a module with
        >> functions and
        >> global variables. Modules only import once.
        >>[/color]
        > should often work, but this illustrates how it can go wrong[/color]
        [...][color=blue]
        > del sys.modules['my_singleton_m odule'][/color]
        [...][color=blue]
        > so if sys.modules gets interfered with approriately, your singleton can
        > start breeding.[/color]

        We're all adults. How often do you see (or write) code that
        goes around deleting modules from sys.modules. Colin's
        suggesting is just fine for most sane situations.

        -Peter

        Comment

        • Robin Becker

          #5
          Re: Brain Dead Singleton

          Peter Hansen wrote:
          [color=blue]
          > Robin Becker wrote:
          >[color=green]
          >> Colin Brown wrote:
          >>[color=darkred]
          >>> Whenever I want a singleton "class", I just use a module with
          >>> functions and
          >>> global variables. Modules only import once.
          >>>[/color]
          >> should often work, but this illustrates how it can go wrong[/color]
          >
          > [...]
          >[color=green]
          >> del sys.modules['my_singleton_m odule'][/color]
          >
          > [...]
          >[color=green]
          >> so if sys.modules gets interfered with approriately, your singleton
          >> can start breeding.[/color]
          >
          >
          > We're all adults. How often do you see (or write) code that
          > goes around deleting modules from sys.modules. Colin's
          > suggesting is just fine for most sane situations.
          >
          > -Peter[/color]

          well I actually have a use case for deleting modules from sys.modules.
          In some legacy code for ReportLab documentation, import was used in the form

          import chapter1
          import chapter2
          ......

          in two different documents causing confusion. An easy fix involved
          restoring sys.modules to a pristine state before each document was
          generated.
          --
          Robin Becker

          Comment

          • Peter Hansen

            #6
            Re: Brain Dead Singleton

            Robin Becker wrote:
            [color=blue]
            > Peter Hansen wrote:[color=green]
            >> Colin's suggesting is just fine for most sane situations.[/color]
            >
            > well I actually have a use case for deleting modules from sys.modules.[/color]
            [...][color=blue]
            > An easy fix involved restoring sys.modules to a pristine state
            > before each document was generated.[/color]

            I'd argue perhaps that "easy fix" should have read "hack", and
            that this doesn't fit my condition of "most sane situations".

            Would you say that this "fix" was really an elegant solution,
            or just a quick hack? I don't think deleting things from
            sys.modules has defined, guaranteed behaviour, so I'm uncertain
            whether anyone should rely on it working. I still think
            Colin's approach is a generally okay one.

            -Peter

            Comment

            • Robin Becker

              #7
              Re: Brain Dead Singleton

              Peter Hansen wrote:

              .......
              [color=blue][color=green]
              > > An easy fix involved restoring sys.modules to a pristine state
              > > before each document was generated.[/color]
              >
              > I'd argue perhaps that "easy fix" should have read "hack", and
              > that this doesn't fit my condition of "most sane situations".
              >[/color]

              I think I would agree that this is a hack. Probably the correct fix
              would have been to packagize each document folder and the containing
              folder and then change all the imports to be absolute, but that would
              have meant changing far more lines of code and introducing packages
              which are not really packages.
              [color=blue]
              > Would you say that this "fix" was really an elegant solution,
              > or just a quick hack? I don't think deleting things from
              > sys.modules has defined, guaranteed behaviour, so I'm uncertain
              > whether anyone should rely on it working. I still think
              > Colin's approach is a generally okay one.
              >
              > -Peter[/color]

              If sys.modules isn't intended to be a modifiable cache, perhaps we
              shouldn't be given access to it.

              The docs for 2.3 say
              "modules
              This is a dictionary that maps module names to modules which have
              already been loaded. This can be manipulated to force reloading of
              modules and other tricks. Note that removing a module from this
              dictionary is not the same as calling reload() on the corresponding
              module object."

              So the Gods call call this a trick :)
              --
              Robin Becker

              Comment

              • Peter Hansen

                #8
                Re: Brain Dead Singleton

                Robin Becker wrote:[color=blue]
                > Peter Hansen wrote:[color=green]
                >> I don't think deleting things from
                >> sys.modules has defined, guaranteed behaviour, so I'm uncertain
                >> whether anyone should rely on it working.[/color]
                >
                > If sys.modules isn't intended to be a modifiable cache, perhaps we
                > shouldn't be given access to it.
                >
                > The docs for 2.3 say
                > "modules
                > This is a dictionary that maps module names to modules which have
                > already been loaded. This can be manipulated to force reloading of
                > modules and other tricks.... "[/color]

                Hmmm... I'd be more inclined to think it was an approval
                if it didn't use the term "trick" to describe it.

                Anyway, this now leads me to wonder whether any singleton
                pattern which doesn't involve manipulating __builtin__ is
                safe from deletion of items in sys.modules...

                -Peter

                Comment

                • Robin Becker

                  #9
                  Re: Brain Dead Singleton

                  Peter Hansen wrote:
                  .......[color=blue][color=green]
                  >> The docs for 2.3 say
                  >> "modules
                  >> This is a dictionary that maps module names to modules which have
                  >> already been loaded. This can be manipulated to force reloading of
                  >> modules and other tricks.... "[/color]
                  >
                  >
                  > Hmmm... I'd be more inclined to think it was an approval
                  > if it didn't use the term "trick" to describe it.
                  >
                  > Anyway, this now leads me to wonder whether any singleton
                  > pattern which doesn't involve manipulating __builtin__ is
                  > safe from deletion of items in sys.modules...[/color]

                  .....

                  If you hold onto an instance then I think it's safe, I guess the problem
                  is when the class code (from a module) gets violently changed in some
                  way. When you next get an instance even from a borg type pattern it
                  needn't be the same as the last instance. Of course modules, classes etc
                  are not normally read only so they can be subverted just by writing into
                  them.
                  [color=blue]
                  > -Peter[/color]
                  --
                  Robin Becker

                  Comment

                  • Kamilche

                    #10
                    Re: Brain Dead Singleton

                    Well, to cop a phrase from 'Brother Where Art Thou?', "I'm with you
                    fellers."

                    You both are much more experienced than I, so much so that I don't
                    even know what you're talking about, yet. :-o

                    Comment

                    • Peter Otten

                      #11
                      Re: Brain Dead Singleton

                      Robin Becker wrote:
                      [color=blue]
                      > Peter Hansen wrote:[/color]

                      [...]
                      [color=blue][color=green]
                      >> Anyway, this now leads me to wonder whether any singleton
                      >> pattern which doesn't involve manipulating __builtin__ is
                      >> safe from deletion of items in sys.modules...[/color]
                      >
                      > ....
                      >
                      > If you hold onto an instance then I think it's safe, I guess the problem[/color]

                      The same is true for modules. If you keep a reference of a module and refer
                      only to that instead of doing an import every time you need to access your
                      singleton - well nothing will break that. However, you have now reduced the
                      original pattern to a mere "please do not rebind that name" convention.

                      Peter

                      Comment

                      Working...