Loading ...
Sorry, an error occurred while loading the content.

[Cheetahtemplate-discuss] Fwd: $self?

Expand Messages
  • Tavis Rudd
    Hello, I m using cheetah to generate config file for a fair-sized distributed system: a handful of config files on each of a couple of dozen systems. Templates
    Message 1 of 5 , Oct 25, 2006
    • 0 Attachment
    • Tavis Rudd
      Hi Mike, For case 1 you re best leaving the $ off. It s only needed when you re either looking for variables from the searchlist or using namemapper style
      Message 2 of 5 , Oct 26, 2006
      • 0 Attachment
        Hi Mike,
        For case 1 you're best leaving the $ off. It's only needed when you're either
        looking for variables from the searchlist or using namemapper style unified
        notation. You're doing neither.

        For case 2, create a separate pure python module with a counter in it along
        with def incrementCounter and def getCount(). Import that module into your
        templates and you're set to go. An alternate approach is to create a pure
        python baseclass for your templates that controls the counter with
        classmethods.

        Cheers,
        Tavis

        -------------------------------------------------------------------------
        Using Tomcat but need to do more? Need to support web services, security?
        Get stuff done quickly with pre-integrated technology to make your job easier
        Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
        http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
        _______________________________________________
        Cheetahtemplate-discuss mailing list
        Cheetahtemplate-discuss@...
        https://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss
      • Mike Orr
        ... Either of the first two is OK. We re now recommending the first to avoid unnecessary $ , but I m personally undecided and switch back and forth. The
        Message 3 of 5 , Oct 26, 2006
        • 0 Attachment
          On 10/25/06, Tavis Rudd <tavis@...> wrote:
          > Case 1: A number of placeholder values can be derived from the class
          > name for most of the classes. Doing either of:
          >
          > #set $name = self.__class__.__name__
          > #set $name = $self.__class__.__name__
          >
          > works, but:
          >
          > #set $name = $__class__.__name__
          >
          > sets $name to "dict".

          Either of the first two is OK. We're now recommending the first to
          avoid unnecessary '$', but I'm personally undecided and switch back
          and forth.

          The third is finding the .__class__ attribute of an object earlier in
          the searchList. You obviously don't want this.

          In the current documentation we took as many shortcuts with $self as
          we could. It's clear if you understand how the searchList is built,
          but we should make it more explicit.

          This example shows what's going on under the hood. The last line of
          the output shows that the searchList contains the '#set global' dict,
          then any user-defined namespaces, then the template's 'self'.

          **** PROGRAM ****
          from Cheetah.Template import Template

          class MyClass(object):
          var1 = "foo"
          var2 = "bar"
          var3 = "boz"

          TEMPLATE = """\
          #set global $var1 = "PHOOEY!"
          #set $var3 = "local variable"
          ##
          var1 is $var1
          var2 is $var2
          var3 is $var3
          ##
          ## TURN AUTOCALLING OFF TO AVOID CALLING $range
          #compiler-settings
          useAutocalling = False
          #end compiler-settings
          ##
          builtin func 'range' is $range
          ##
          ## TURN AUTOCALLING BACK ON TO DEMONSTRATE SIMPLE USE OF $searchList
          #compiler-settings
          useAutocalling = True
          #end compiler-settings
          Simple use of \$searchList is equivalent to full: ${searchList ==
          $self.searchList()}
          """

          # Uncomment if you want to view the compiled template.
          #print Template.compile(TEMPLATE, returnAClass=False)

          print Template(TEMPLATE, namespaces=[MyClass]).respond()
          **** END PROGRAM ****

          **** OUTPUT ****
          var1 is PHOOEY!
          var2 is bar
          var3 is local variable
          builtin func 'range' is <built-in function range>
          Simple use of $searchList is equivalent to full: True

          [{'var1': 'PHOOEY!'}, <class '__main__.MyClass'>,
          <DynamicallyCompiledCheetahTemplate.DynamicallyCompiledCheetahTemplate
          object at 0xb7bf84ec>]
          **** END OUTPUT ****




          > Case 2: I needed class variables. Not just attributes, but real live
          > variables; basically I needed a value that changed for each instance
          > of the class. I forget exactly what I triecd, but I wound up doing:
          >
          > #set $self.instance_counter[0] += 1
          >
          > to get things to change properly.

          Not "class variables"; this is a template instance attribute.

          #set $self.instance_counter = 0
          #set $self.instance_counter += 1

          You CANNOT omit "self." when modifying an instance attribute.

          #set $instance_counter += 1 # Raises UnboundLocalError.

          The reason is that Cheetah does not use the NameMapper on the left
          side of a #set, so it looks only for an existing local variable.
          'self' is a local variable in Python.

          The value will leak from one template fill to the next, so you'll have
          to intialize it to 0 at the beginning of every fill. Also, modifying
          template attributes is thread unsafe.

          > One alternative would seem to be #set global, but the scope for that
          > isn't clearly defined. In particular, they don't seem to be inherited,

          What do you mean they aren't inherited? I tried different
          combinations of setting and printing a 'set global' variable in a
          superclass and subclass, an in superclass and subclass methods, and in
          an #include file, and they all shared the same dict. '#set global'
          sounds like an ideal solution to your problem.

          > and they are stored in a dictionary attached to self. So "instance
          > variable" seems about right - except they cross include boundaries,
          > which generate subobjects?

          Correct. $self attributes are not passed to or from #include files.

          --
          Mike Orr <sluggoster@...>

          -------------------------------------------------------------------------
          Using Tomcat but need to do more? Need to support web services, security?
          Get stuff done quickly with pre-integrated technology to make your job easier
          Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
          http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
          _______________________________________________
          Cheetahtemplate-discuss mailing list
          Cheetahtemplate-discuss@...
          https://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss
        • Mike Meyer
          ... I think I may have left out an important part: #attr $instance_counter = [0] I.e. - instance_counter is an attribute of the class the template compiles to,
          Message 4 of 5 , Oct 26, 2006
          • 0 Attachment
            In <6e9196d20610261359r115a0da8x5e210e957a92a907@...>, Mike Orr <sluggoster@...> typed:
            > On 10/25/06, Tavis Rudd <tavis@...> wrote:
            > > Case 2: I needed class variables. Not just attributes, but real live
            > > variables; basically I needed a value that changed for each instance
            > > of the class. I forget exactly what I tried, but I wound up doing:
            > >
            > > #set $self.instance_counter[0] += 1
            > >
            > > to get things to change properly.
            >
            > Not "class variables"; this is a template instance attribute.

            I think I may have left out an important part:

            #attr $instance_counter = [0]

            I.e. - instance_counter is an attribute of the class the template
            compiles to, not of an instance of that class. Or maybe that's what
            "template instance attribute" means.

            > The value will leak from one template fill to the next, so you'll have
            > to intialize it to 0 at the beginning of every fill. Also, modifying
            > template attributes is thread unsafe.

            And here's why I said I wanted "class variables" - I *want* the value
            to change between fills. I have nine hosts each running two copies of
            the same program with different config files. The programs are
            extracting data from something to turn it into rows in a
            database. They need to attach an id to each row, with the ids coming
            from a different range for each process. The range for a process is
            determined by the value of $self.instance_counter[0] at the time the
            configuration file is filled.

            In fact, that's why I used a one-element list. If I just used
            $self.instance_counter, then the #set that increments it would create
            a new attribute for the instance instead of incrementing the class
            variable. So the next time I filled the class, instance_counter would
            start over - not what I wanted.

            Thanks for the warning about thread safety. Not an issue for me,
            though.

            > > One alternative would seem to be #set global, but the scope for that
            > > isn't clearly defined. In particular, they don't seem to be inherited,
            > What do you mean they aren't inherited? I tried different
            > combinations of setting and printing a 'set global' variable in a
            > superclass and subclass, an in superclass and subclass methods, and in
            > an #include file, and they all shared the same dict. '#set global'
            > sounds like an ideal solution to your problem.

            I checked again, and yup, they are. I'm not sure what I was doing that
            created that impression, but I can't recreate it now. Sorry.

            <mike
            --
            Mike Meyer <mwm@...> http://www.mired.org/consulting.html
            Independent Network/Unix/Perforce consultant, email for more information.


            -------------------------------------------------------------------------
            Using Tomcat but need to do more? Need to support web services, security?
            Get stuff done quickly with pre-integrated technology to make your job easier
            Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
            http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
            _______________________________________________
            Cheetahtemplate-discuss mailing list
            Cheetahtemplate-discuss@...
            https://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss
          • Mike Orr
            ... If you really want a template class attribute, it s: #set $self.__class__.instance_counter = 0 #set $self.__class__.instance_counter += 1 I almost put that
            Message 5 of 5 , Oct 26, 2006
            • 0 Attachment
              On 10/26/06, Mike Meyer <mwm@...> wrote:
              > In <6e9196d20610261359r115a0da8x5e210e957a92a907@...>, Mike Orr <sluggoster@...> typed:
              > > On 10/25/06, Tavis Rudd <tavis@...> wrote:
              > > > Case 2: I needed class variables. Not just attributes, but real live
              > > > variables; basically I needed a value that changed for each instance
              > > > of the class. I forget exactly what I tried, but I wound up doing:
              > > >
              > > > #set $self.instance_counter[0] += 1
              > > >
              > > > to get things to change properly.
              > >
              > > Not "class variables"; this is a template instance attribute.
              >
              > I think I may have left out an important part:
              >
              > #attr $instance_counter = [0]
              >
              > I.e. - instance_counter is an attribute of the class the template
              > compiles to, not of an instance of that class. Or maybe that's what
              > "template instance attribute" means.
              >
              > > The value will leak from one template fill to the next, so you'll have
              > > to intialize it to 0 at the beginning of every fill. Also, modifying
              > > template attributes is thread unsafe.
              >
              > And here's why I said I wanted "class variables" - I *want* the value
              > to change between fills.

              If you really want a template class attribute, it's:

              #set $self.__class__.instance_counter = 0
              #set $self.__class__.instance_counter += 1

              I almost put that in my example but thought, "That can't be what he
              wants. Nobody in their right mind would share a variable across
              template instances." But it looks like you found a use for it.

              A template instance is what Template(...) returns. A template class
              is what Template.compile(...) returns -- it has to be instantiated
              before being filled. A template class is also what a compiled
              template module contains.

              'set global' variables won't be shared across fills. But class
              attributes won't be shared with #include files. If it has to be
              global across everything, put it in a Python module and #import the
              module.

              --
              Mike Orr <sluggoster@...>

              -------------------------------------------------------------------------
              Using Tomcat but need to do more? Need to support web services, security?
              Get stuff done quickly with pre-integrated technology to make your job easier
              Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
              http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
              _______________________________________________
              Cheetahtemplate-discuss mailing list
              Cheetahtemplate-discuss@...
              https://lists.sourceforge.net/lists/listinfo/cheetahtemplate-discuss
            Your message has been successfully submitted and would be delivered to recipients shortly.