Need help with Python class idioms

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

    Need help with Python class idioms

    Howdy!

    I'm trying to get my head around Python and I've come to realize that
    there are a lot of idioms in Python that are a bit different than in
    other languages. I have a class similar to what I've included below.
    The only difference is that in the real class, I have even more
    mandatory attributes. Too many to specify at once on a constructor and
    they don't always exist at construction time anyway, so the accessor
    idiom must remain.

    Can anyone suggest a more Pythony way to do the following?

    Thanks,
    Tad

    #!/bin/env python

    class A:
    def __init__(self):
    self.mandatoryV ar1 = None
    self.mandatoryV ar2 = None

    def setMV1(self, mv1):
    self.mandatoryV ar1 = mv1

    def setMV2(self, mv2):
    self.mandatoryV ar2 = mv2

    def saveToDB(self, db):
    if self.mandatoryV ar1 == None:
    raise Exception, "Mandatory Var 1 not set."
    if self.mandatoryV ar2 == None:
    raise Exception, "Mandatory Var 2 not set."

    # Using db, do whatever saving stuff is needed.
  • A.Schmolck

    #2
    Re: Need help with Python class idioms

    tad@tadland.net (Tad Marko) writes:[color=blue]
    > Can anyone suggest a more Pythony way to do the following?
    >
    > Thanks,
    > Tad
    >
    > #!/bin/env python
    >
    > class A:
    > def __init__(self):
    > self.mandatoryV ar1 = None
    > self.mandatoryV ar2 = None
    >
    > def setMV1(self, mv1):
    > self.mandatoryV ar1 = mv1
    >
    > def setMV2(self, mv2):
    > self.mandatoryV ar2 = mv2
    >
    > def saveToDB(self, db):
    > if self.mandatoryV ar1 == None:
    > raise Exception, "Mandatory Var 1 not set."
    > if self.mandatoryV ar2 == None:
    > raise Exception, "Mandatory Var 2 not set."
    >
    > # Using db, do whatever saving stuff is needed.[/color]

    class A(object):
    def saveToDB(self, db):
    # Using db, do whatever saving stuff is needed.

    'as

    Comment

    • James Henderson

      #3
      Re: Need help with Python class idioms

      On Wednesday 21 January 2004 8:43 pm, Tad Marko wrote:[color=blue]
      > Howdy!
      >
      > I'm trying to get my head around Python and I've come to realize that
      > there are a lot of idioms in Python that are a bit different than in
      > other languages. I have a class similar to what I've included below.
      > The only difference is that in the real class, I have even more
      > mandatory attributes. Too many to specify at once on a constructor and
      > they don't always exist at construction time anyway, so the accessor
      > idiom must remain.
      >
      > Can anyone suggest a more Pythony way to do the following?
      >
      > Thanks,
      > Tad
      >
      > #!/bin/env python
      >
      > class A:
      > def __init__(self):
      > self.mandatoryV ar1 = None
      > self.mandatoryV ar2 = None
      >
      > def setMV1(self, mv1):
      > self.mandatoryV ar1 = mv1
      >
      > def setMV2(self, mv2):
      > self.mandatoryV ar2 = mv2
      >
      > def saveToDB(self, db):
      > if self.mandatoryV ar1 == None:
      > raise Exception, "Mandatory Var 1 not set."
      > if self.mandatoryV ar2 == None:
      > raise Exception, "Mandatory Var 2 not set."
      >
      > # Using db, do whatever saving stuff is needed.[/color]

      What about this:

      class A:
      def __init__(self, mandatoryVar1, mandatoryVar2):
      self.mandatoryV ar1 = mandatoryVar1
      self.mandatoryV ar2 = mandatoryVar2

      --
      James Henderson, Logical Progression Ltd.

      Download MailManager for free. MailManager is designed to solve the problems companies have as the volumes of email they receive increase such as making sure email goes to the right person, making sure it is answered on time, ensuring information in email boxes is shared within th



      Comment

      • Josiah Carlson

        #4
        Re: Need help with Python class idioms


        On 21 Jan 2004 12:43:28 -0800
        tad@tadland.net (Tad Marko) wrote:
        [color=blue]
        > Howdy!
        >
        > I'm trying to get my head around Python and I've come to realize that
        > there are a lot of idioms in Python that are a bit different than in
        > other languages. I have a class similar to what I've included below.
        > The only difference is that in the real class, I have even more
        > mandatory attributes. Too many to specify at once on a constructor and
        > they don't always exist at construction time anyway, so the accessor
        > idiom must remain.
        >
        > Can anyone suggest a more Pythony way to do the following?
        >
        > Thanks,
        > Tad
        >
        > #!/bin/env python
        >
        > class A:
        > def __init__(self):
        > self.mandatoryV ar1 = None
        > self.mandatoryV ar2 = None
        >
        > def setMV1(self, mv1):
        > self.mandatoryV ar1 = mv1
        >
        > def setMV2(self, mv2):
        > self.mandatoryV ar2 = mv2
        >
        > def saveToDB(self, db):
        > if self.mandatoryV ar1 == None:
        > raise Exception, "Mandatory Var 1 not set."
        > if self.mandatoryV ar2 == None:
        > raise Exception, "Mandatory Var 2 not set."
        >
        > # Using db, do whatever saving stuff is needed.[/color]


        mandatoryvariab les = dict(mandatoryv ar1=mv1, mandatoryvar2=m v2...)
        inst = A()
        inst.__dict__.u pdate(mandatory variables)

        That should work for you.
        - Josiah

        Comment

        • James Henderson

          #5
          Re: Need help with Python class idioms

          On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote:[color=blue]
          > # P.S. Since you're asking about idiom, it would be more Pythonic to write:
          > #
          > # if self.mandatoryV ar1 is None:
          > #
          > # using the identity test "is" rather than equality test "==", since there
          > is # only one None.
          >
          > I'd write
          >
          > if not self.mandatoryV ar1:
          >
          > but the first method works, too.[/color]

          Are you sure an empty sequence or zero aren't valid values? J.
          --
          James Henderson, Logical Progression Ltd.

          Download MailManager for free. MailManager is designed to solve the problems companies have as the volumes of email they receive increase such as making sure email goes to the right person, making sure it is answered on time, ensuring information in email boxes is shared within th



          Comment

          • Jonathan Daugherty

            #6
            Re: Need help with Python class idioms

            # P.S. Since you're asking about idiom, it would be more Pythonic to write:
            #
            # if self.mandatoryV ar1 is None:
            #
            # using the identity test "is" rather than equality test "==", since there is
            # only one None.

            I'd write

            if not self.mandatoryV ar1:

            but the first method works, too.

            --

            Jonathan Daugherty


            "It's a book about a Spanish guy called Manual, you should read it."
            -- Dilbert

            Comment

            • Mike C. Fletcher

              #7
              Re: Need help with Python class idioms

              Tad Marko wrote:
              [color=blue]
              >Howdy!
              >
              >I'm trying to get my head around Python and I've come to realize that
              >there are a lot of idioms in Python that are a bit different than in
              >other languages. I have a class similar to what I've included below.
              >The only difference is that in the real class, I have even more
              >mandatory attributes. Too many to specify at once on a constructor and
              >they don't always exist at construction time anyway, so the accessor
              >idiom must remain.
              >
              >Can anyone suggest a more Pythony way to do the following?
              >
              >[/color]
              Note: shameless plug follows...

              With basicproperty, it would look something like this:

              class A( propertied.Prop ertied ):
              mandatoryVar1 = common.IntegerP roperty(
              "mandatoryVar1" , """Property that's mandatory 'cause we're cool""",
              )
              defaultVar1 = common.IntegerP roperty(
              "defaultVar 1", """Property that's got a default value""",
              defaultValue = 32,
              )
              defaultVar2 = common.StringPr operty(
              "defaultVar 2", """Property that's got a default function instead""",
              defaultFunction = lambda prop, client: client.__class_ _.__name__,
              )

              a = A( mandatoryVar1 = 3 )
              a.defaultVar2
              a.defaultVar1

              however, you continue on to show you're using a database, so you'd
              probably prefer something like pytable (which is built on top of
              basicproperty, but uses database schemas to control the creation and
              operation of the properties):

              from pytable.schemab uilder import *
              schema = table(
              "my_table",
              comment = """Table for storing whatevers""",
              fields = (
              field(
              'mandatoryVar1' , 'integer',0, # name, sql data-type, size
              constraints = (
              notNull(),
              ),
              ),
              field(
              'defaultVal1', 'integer',0, # name, sql data-type, size
              defaultValue = 32, # sql default value
              constraints = (
              notNull(),
              ),
              ),
              field(
              'Var2', 'timestamptz',0 , # name, sql data-type, size
              defaultValue = '"timestamp"(\' now\'::text)', # sql default value
              constraints = (
              notNull(),
              ),
              ),
              ),
              indices = (
              index( primary=1, fields=('mandat oryVar1', 'defaultVal1')) ,
              ),
              )

              print schema.itemClas s
              help( schema.itemClas s )

              row = schema.itemClas s( mandatoryVar1 = 33 )
              row.insertQuery ( my_db_connectio n ) # get one from pytable
              row.mandatoryVa r1 = 34
              row.updateQuery ( my_db_connectio n )
              row.deleteQuery ( my_db_connectio n )

              BasicProperty:

              PyTable RDBMS Wrapper:


              In a more general sense, for DB operations, use a database wrapper
              module, there's lots of them around. And even more generally,
              properties are *very* good at describing (common) property-based systems
              of objects such as you're apparently working with. Properties are new
              with Python 2.2, so underused sometimes, but they are very good at
              certain types of domain modelling.

              Enjoy yourself,
              Mike

              _______________ _______________ _________
              Mike C. Fletcher
              Designer, VR Plumber, Coder





              Comment

              • James Henderson

                #8
                Re: Need help with Python class idioms

                [Tad Marko][color=blue][color=green]
                > > def saveToDB(self, db):
                > > if self.mandatoryV ar1 == None:
                > > raise Exception, "Mandatory Var 1 not set."
                > > if self.mandatoryV ar2 == None:
                > > raise Exception, "Mandatory Var 2 not set."[/color][/color]

                P.S. Since you're asking about idiom, it would be more Pythonic to write:

                if self.mandatoryV ar1 is None:

                using the identity test "is" rather than equality test "==", since there is
                only one None.

                James
                --
                James Henderson, Logical Progression Ltd.

                Download MailManager for free. MailManager is designed to solve the problems companies have as the volumes of email they receive increase such as making sure email goes to the right person, making sure it is answered on time, ensuring information in email boxes is shared within th



                Comment

                • Paul McGuire

                  #9
                  Re: Need help with Python class idioms

                  "Jonathan Daugherty" <cygnus@cprogra mmer.org> wrote in message
                  news:mailman.61 1.1074719029.12 720.python-list@python.org ...[color=blue]
                  > # P.S. Since you're asking about idiom, it would be more Pythonic to[/color]
                  write:[color=blue]
                  > #
                  > # if self.mandatoryV ar1 is None:
                  > #
                  > # using the identity test "is" rather than equality test "==", since there[/color]
                  is[color=blue]
                  > # only one None.
                  >
                  > I'd write
                  >
                  > if not self.mandatoryV ar1:
                  >
                  > but the first method works, too.
                  >
                  > --
                  >
                  > Jonathan Daugherty
                  > http://www.cprogrammer.org
                  >
                  > "It's a book about a Spanish guy called Manual, you should read it."
                  > -- Dilbert
                  >[/color]

                  .... what if mandatoryVar1 was set to False?

                  -- Paul


                  Comment

                  • Jonathan Daugherty

                    #10
                    Re: Need help with Python class idioms

                    # ... what if mandatoryVar1 was set to False?

                    To all who have responded to me as such: of course, how one
                    treats the variable in a boolean context depends on what its
                    semantically "false" value is. You do the math; I just
                    provided a syntax alternative. :)

                    --

                    Jonathan Daugherty
                    cprogrammer.org is your first and best source for information about cprogrammer. Here you will also find topics relating to issues of general interest. We hope you find what you are looking for!


                    "It's a book about a Spanish guy called Manual, you should read it."
                    -- Dilbert

                    Comment

                    • kbass

                      #11
                      Python and writing a CSV file

                      I am new to Python and would like to attempt to write to a CSV file. I have
                      reviewed the documentation at http://www.object-craft.com.au/projects/csv/
                      for the csv 1.0 module but I didn't see any information referring to writing
                      (oe creating) a CSV file with this module. Does this module have the
                      capability to write a CSV file? Thanks!

                      Kevin


                      Comment

                      • Skip Montanaro

                        #12
                        Re: Python and writing a CSV file


                        Kevin> I am new to Python and would like to attempt to write to a CSV
                        Kevin> file. I have reviewed the documentation at
                        Kevin> http://www.object-craft.com.au/projects/csv/ for the csv 1.0
                        Kevin> module but I didn't see any information referring to writing (oe
                        Kevin> creating) a CSV file with this module. Does this module have the
                        Kevin> capability to write a CSV file?

                        Yes, but you should upgrade to 2.3 (if you haven't already) and just use the
                        csv module which comes with it:



                        Skip

                        Comment

                        • Mel Wilson

                          #13
                          Re: Need help with Python class idioms

                          In article <mailman.613.10 74720629.12720. python-list@python.org >,
                          James Henderson <james@logicalp rogression.net> wrote:[color=blue]
                          >On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote:[color=green]
                          >> # P.S. Since you're asking about idiom, it would be more Pythonic to write:
                          >> #
                          >> # if self.mandatoryV ar1 is None:
                          >> #
                          >> # using the identity test "is" rather than equality test "==", since there
                          >> is # only one None.
                          >>
                          >> I'd write
                          >>
                          >> if not self.mandatoryV ar1:
                          >>
                          >> but the first method works, too.[/color]
                          >
                          >Are you sure an empty sequence or zero aren't valid values? J.[/color]

                          It can get weird if you have to allow your caller to
                          optionally specify the value None:


                          class _MissingParam:
                          "An object that no-one else will have a valid use for."
                          ....
                          def a_func (opt1=_MissingP aram):
                          if opt1 is _MissingParam:
                          opt1 = default_calcula tion () # for instance
                          ....


                          Regards. Mel.

                          Comment

                          • James Henderson

                            #14
                            Re: Need help with Python class idioms

                            On Thursday 22 January 2004 6:05 pm, Mel Wilson wrote:[color=blue]
                            > In article <mailman.613.10 74720629.12720. python-list@python.org >,
                            >
                            > James Henderson <james@logicalp rogression.net> wrote:[color=green]
                            > >On Wednesday 21 January 2004 9:01 pm, Jonathan Daugherty wrote:[color=darkred]
                            > >> # P.S. Since you're asking about idiom, it would be more Pythonic to
                            > >> write: #
                            > >> # if self.mandatoryV ar1 is None:
                            > >> #
                            > >> # using the identity test "is" rather than equality test "==", since
                            > >> there is # only one None.
                            > >>
                            > >> I'd write
                            > >>
                            > >> if not self.mandatoryV ar1:
                            > >>
                            > >> but the first method works, too.[/color]
                            > >
                            > >Are you sure an empty sequence or zero aren't valid values? J.[/color]
                            >
                            > It can get weird if you have to allow your caller to
                            > optionally specify the value None:
                            >
                            >
                            > class _MissingParam:
                            > "An object that no-one else will have a valid use for."
                            > ...
                            > def a_func (opt1=_MissingP aram):
                            > if opt1 is _MissingParam:
                            > opt1 = default_calcula tion () # for instance
                            > ...
                            >
                            >
                            > Regards. Mel.[/color]

                            In the original example (not by me) it was None that was being used as the
                            marker that the value had not been set - that's all.

                            The topic was Python idiom and None is the most often used marker that a value
                            has not been passed explicitly and the default value should be used. (Of
                            course, if the default value is immutable it can be used directly.) See:



                            You're talking about the case where None may be passed explicitly and should
                            not trigger the default. An even terser solution to this than yours is to
                            use an empty list, though any mutable type will do. You see this all over
                            the Zope code:

                            _marker = []

                            J.
                            --
                            James Henderson, Logical Progression Ltd.

                            Download MailManager for free. MailManager is designed to solve the problems companies have as the volumes of email they receive increase such as making sure email goes to the right person, making sure it is answered on time, ensuring information in email boxes is shared within th



                            Comment

                            • kbass

                              #15
                              Re: Python and writing a CSV file


                              ----- Original Message -----
                              From: "Skip Montanaro" <skip@pobox.com >
                              To: "kbass" <kbass@midsouth .rr.com>
                              Cc: "Python List" <python-list@python.org >
                              Sent: Wednesday, January 21, 2004 6:39 PM
                              Subject: Re: Python and writing a CSV file

                              [color=blue]
                              >
                              > Kevin> I am new to Python and would like to attempt to write to a CSV
                              > Kevin> file. I have reviewed the documentation at
                              > Kevin> http://www.object-craft.com.au/projects/csv/ for the csv 1.0
                              > Kevin> module but I didn't see any information referring to writing[/color]
                              (oe[color=blue]
                              > Kevin> creating) a CSV file with this module. Does this module have[/color]
                              the[color=blue]
                              > Kevin> capability to write a CSV file?
                              >
                              > Yes, but you should upgrade to 2.3 (if you haven't already) and just use[/color]
                              the[color=blue]
                              > csv module which comes with it:
                              >
                              > http://www.python.org/doc/current/lib/module-csv.html
                              >
                              > Skip[/color]

                              Thanks for responding. Currently we do not have Python 2.3 installed on our
                              server, is there another way to perform this task with another module or
                              without a module? Thanks!

                              Kevin


                              Comment

                              Working...