Python "with"

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

    Python "with"

    Hi,

    I'm looking for a construct that's similar to (Turbo) Pascal's "with"
    statement. I read about the Python's new "with" statement, but I was
    dissapointed to learn that it does something different (I still don't
    see how it's better than try..except..fi nally, but that's not my question).

    Is there something similar to what I want that's Pythonic enough?

    (If you're not familiar with Pascal, here's how it works:

    with some.big.struct ure.or.nested.o bjects.element do begin
    member1 := something;
    member2 := something;
    end;

    which exactly translates to this equivalent:

    some.big.struct ure.or.nested.o bjects.element. member1 := something;
    some.big.struct ure.or.nested.o bjects.element. member2 := something;

    i.e. it's a wrist-saver. I think a similar feature exists in C99, for
    structs.

    I know it can be almost always done by using a temporary variable:

    tmp = some.big.struct ure.or.nested.o bjects.element
    tmp.member1 = something
    tmp.member2 = something

    but this looks ugly to me.)


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

    iD8DBQFG7Yzxldn AQVacBcgRAotkAK DeZ/uHf8WWpE+Lpk3ZM 56Pnl892wCgvCOn
    FDQ2/IgAA3duJ4R2vz3g lpg=
    =X0Y+
    -----END PGP SIGNATURE-----

  • J. Cliff Dyer

    #2
    Re: Python "with&quot ;

    Ivan Voras wrote:
    Hi,
    >
    I'm looking for a construct that's similar to (Turbo) Pascal's "with"
    statement. I read about the Python's new "with" statement, but I was
    dissapointed to learn that it does something different (I still don't
    see how it's better than try..except..fi nally, but that's not my question).
    >
    Is there something similar to what I want that's Pythonic enough?
    >
    (If you're not familiar with Pascal, here's how it works:
    >
    with some.big.struct ure.or.nested.o bjects.element do begin
    member1 := something;
    member2 := something;
    end;
    >
    which exactly translates to this equivalent:
    >
    some.big.struct ure.or.nested.o bjects.element. member1 := something;
    some.big.struct ure.or.nested.o bjects.element. member2 := something;
    >
    i.e. it's a wrist-saver. I think a similar feature exists in C99, for
    structs.
    >
    I know it can be almost always done by using a temporary variable:
    >
    tmp = some.big.struct ure.or.nested.o bjects.element
    tmp.member1 = something
    tmp.member2 = something
    >
    You can import the members directly, using:
    >>from some.big.struct ure.or.nested.o bjects.element import member1,
    member2

    which requires you to know the variable names. But if you want to do it
    after the import, your tmp example is the way to go. It would be less
    ugly if your variable is named so that it still has some connection to
    the purpose of the module.

    There are other options, too:
    >>import some.big.struct ure.or.nested.o bjects.element as tmp
    This will still make you prefix tmp to the variables, but you don't need
    a separate statement devoted to rebinding the module to a new name.

    Personally, I don't find the shorter prefix all that ugly. For me
    ugliness and clarity are almost entirely synonymous when it comes to
    code, so maintaining the certainty about where the variables came from
    is a good thing. I've just started a job where I have to maintain perl
    code, so I keep running across things like

    use File::Basename;
    my $dir = dirname($fullpa th);

    and I keep wondering where basename came from. Is it a builtin? Was it
    from File:: A prefix, no matter how short, how obscure, how
    undescriptive, will let you trace exactly where each name came from.
    Which I find deeply beautiful. All you have to do is look up the page,
    and it's there somewhere. You *can* do the same with Perl, but it's
    actually discouraged by the structure of the language. In other words,
    the simplest case does the wrong thing.

    Python does allow you to import all names from a module, unprefixed but
    it leads you into the same ugliness and namespace clobbering that you
    get with Perl, so I'm not going to tell you how to do it.

    I think the 'import long.name as short' syntax will help your wrists the
    most while still retaining the clarity of explicit module referencing.
    And you won't have the extraneous assignment (tmp = long.name)
    cluttering up your code.

    Cheers,
    Cliff

    Comment

    • Bjoern Schliessmann

      #3
      Re: Python "with&quot ;

      Ivan Voras wrote:
      I'm looking for a construct that's similar to (Turbo) Pascal's
      "with" statement.
      Please have a look at the archives -- this is discussed here from
      time to time. I think last time it was a Visual BASIC fan that
      asked a similar question.
      I know it can be almost always done by using a temporary variable:
      >
      tmp = some.big.struct ure.or.nested.o bjects.element
      tmp.member1 = something
      tmp.member2 = something
      >
      but this looks ugly to me.)
      Such big, javaish names are much uglier, IMHO.

      Regards,


      Björn

      --
      BOFH excuse #17:

      fat electrons in the lines

      Comment

      • Ben Finney

        #4
        Re: Python "with&quot ;

        Ivan Voras <ivoras@__fer.h r__writes:
        I know it can be almost always done by using a temporary variable:
        >
        tmp = some.big.struct ure.or.nested.o bjects.element
        tmp.member1 = something
        tmp.member2 = something
        >
        but this looks ugly to me.)
        To me, it looks explicit. Python programmers value explicit code.

        In other words, this looks like the right way to do it. The
        alternative you're looking for would be to make an implicit reference,
        which would make the code harder to follow.

        Note that in the specific case of an attribute of a module, the first
        lone of the above example can be rewritten as::

        from some.big.packag e.or.nested.mod ule import element as tmp

        which is at least as common as the assignment example above.

        --
        \ "The only tyrant I accept in this world is the still voice |
        `\ within." -- Mahatma Gandhi |
        _o__) |
        Ben Finney

        Comment

        • Dustan

          #5
          Re: Python &quot;with&quot ;

          On Sep 16, 3:07 pm, Ivan Voras <ivoras@__fer.h r__wrote:
          Hi,
          >
          I'm looking for a construct that's similar to (Turbo) Pascal's "with"
          statement. I read about the Python's new "with" statement, but I was
          dissapointed to learn that it does something different (I still don't
          see how it's better than try..except..fi nally, but that's not my question).
          >
          Is there something similar to what I want that's Pythonic enough?
          >
          (If you're not familiar with Pascal, here's how it works:
          >
          with some.big.struct ure.or.nested.o bjects.element do begin
          member1 := something;
          member2 := something;
          end;
          >
          which exactly translates to this equivalent:
          >
          some.big.struct ure.or.nested.o bjects.element. member1 := something;
          some.big.struct ure.or.nested.o bjects.element. member2 := something;
          >
          i.e. it's a wrist-saver. I think a similar feature exists in C99, for
          structs.
          >
          I know it can be almost always done by using a temporary variable:
          >
          tmp = some.big.struct ure.or.nested.o bjects.element
          tmp.member1 = something
          tmp.member2 = something
          >
          but this looks ugly to me.)
          >
          signature.asc
          1KDownload
          >>import this # Note item #5

          Comment

          • Laurent Pointal

            #6
            Re: Python &quot;with&quot ;

            Ivan Voras a écrit :
            <zip>
            I know it can be almost always done by using a temporary variable:
            >
            tmp = some.big.struct ure.or.nested.o bjects.element
            tmp.member1 = something
            tmp.member2 = something
            >
            but this looks ugly to me.)
            The ugly part is the 'tmp' name, try to choose a name with a proper
            meaning about what it is really, and it become clean and readable:

            filerefs = some.big.struct ure.or.nested.o bject.with.file .references
            filerefs.encodi ng = "utf-8"
            filerefs.name = "MyFileName.txt "
            filerefs.use_qu otes = True

            Isn't it ?

            Comment

            • Ivan Voras

              #7
              Re: Python &quot;with&quot ;

              Laurent Pointal wrote:
              The ugly part is the 'tmp' name, try to choose a name with a proper
              meaning about what it is really, and it become clean and readable:

              filerefs = some.big.struct ure.or.nested.o bject.with.file .references
              filerefs.encodi ng = "utf-8"
              filerefs.name = "MyFileName.txt "
              filerefs.use_qu otes = True

              Isn't it ?
              Well, no, but this might be due to personal tastes. At least, I don't
              think it's better then some other alternatives. For example, in C99 you
              can do:

              static struct option_s foo_option = {
              .name = "foo",
              .type = O_STRING,
              .def_value = "default"
              };

              At least to me, this looks even better than the Pascal's syntax.



              -----BEGIN PGP SIGNATURE-----
              Version: GnuPG v1.4.5 (GNU/Linux)
              Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

              iD8DBQFG7k3Kldn AQVacBcgRAxeaAJ 9M5OJxtJk57NNt5 BDOo6BcfZpPtwCf W7Rc
              zFjHiQvJw2PoBJD 6tVO/Bkg=
              =HYCZ
              -----END PGP SIGNATURE-----

              Comment

              • J. Cliff Dyer

                #8
                Re: Python &quot;with&quot ;

                Ivan Voras wrote:
                Laurent Pointal wrote:
                >
                >The ugly part is the 'tmp' name, try to choose a name with a proper
                >meaning about what it is really, and it become clean and readable:
                >>
                >filerefs = some.big.struct ure.or.nested.o bject.with.file .references
                >filerefs.encod ing = "utf-8"
                >filerefs.nam e = "MyFileName.txt "
                >filerefs.use_q uotes = True
                >>
                >Isn't it ?
                >
                Well, no, but this might be due to personal tastes. At least, I don't
                think it's better then some other alternatives. For example, in C99
                you can do:
                >
                static struct option_s foo_option = {
                .name = "foo",
                .type = O_STRING,
                .def_value = "default"
                };
                >
                At least to me, this looks even better than the Pascal's syntax.
                >
                >
                So basically, what you're saying is you don't like namespace prefixes at
                all?

                Keeping your namespaces separate will help the clarity of your code
                immensely, unless, arguably, you're doing heavy numerical processing,
                goes the argument in a recent thread. Probably what will help you the
                most is not a fancy trick for getting rid of the namespace, but getting
                over your aversion to them. That will make you a better programmer, in
                the long run. Debugging will be easier, people will enjoy working with
                your code more. Clarity is beautiful. Objectively so. Not just some
                lame "in the eye of the beholder" kind of beautiful.

                Cheers,
                Cliff

                Comment

                • Peter Otten

                  #9
                  Re: Python &quot;with&quot ;

                  Ivan Voras wrote:
                  Well, no, but this might be due to personal tastes. At least, I don't
                  think it's better then some other alternatives. For example, in C99 you
                  can do:
                  >
                  static struct option_s foo_option = {
                  .name = "foo",
                  .type = O_STRING,
                  .def_value = "default"
                  };
                  >
                  At least to me, this looks even better than the Pascal's syntax.
                  foo_option = OptionS(
                  name="foo",
                  type=O_STRING,
                  def_value="defa ult"
                  )

                  So doesn't the Python analog even look better than C? If so, you don't
                  need new syntax:
                  >>def with_(obj, **update):
                  .... for nv in update.iteritem s():
                  .... setattr(obj, *nv)
                  ....
                  >>with_(a.long. way.to.tipperar y,
                  .... alpha=42,
                  .... beta="yadda",
                  .... gamma=None
                  .... )
                  >>a.long.way.to .tipperary
                  A(alpha=42, beta='yadda', gamma=None)

                  Peter

                  Comment

                  • Laurent Pointal

                    #10
                    Re: Python &quot;with&quot ;

                    Ivan Voras a écrit :
                    Laurent Pointal wrote:
                    >
                    >The ugly part is the 'tmp' name, try to choose a name with a proper
                    >meaning about what it is really, and it become clean and readable:
                    >>
                    >filerefs = some.big.struct ure.or.nested.o bject.with.file .references
                    >filerefs.encod ing = "utf-8"
                    >filerefs.nam e = "MyFileName.txt "
                    >filerefs.use_q uotes = True
                    >>
                    >Isn't it ?
                    >
                    Well, no, but this might be due to personal tastes. At least, I don't
                    think it's better then some other alternatives. For example, in C99 you
                    can do:
                    >
                    static struct option_s foo_option = {
                    .name = "foo",
                    .type = O_STRING,
                    .def_value = "default"
                    };
                    >
                    At least to me, this looks even better than the Pascal's syntax.
                    If its at construction time, you can do the same with Python:

                    class option_s(object ) :
                    def __init__(self,* *initializers) :
                    self.__dict__.u pdate(initializ ers)

                    foo_option = option_s(
                    name = "foo",
                    type_ = O_STRING,
                    def_value = "default"
                    )


                    And if the class has no such construction idiom, you can play like this:

                    x = X()
                    x.__dict__.upda te(dict(
                    name = "foo",
                    type_ = O_STRING,
                    def_value = "default"
                    ))


                    Note: this directly manipulate objects attributes - some times its
                    preffered to use ad-hoc methods.

                    Note2: I prefer the "namespace. name = value" solution, more readable.

                    Note3: Its funny to see how Python users tries to change the language,
                    does this occure with C, C++, Java, C# ?

                    Comment

                    • Grant Edwards

                      #11
                      Re: Python &quot;with&quot ;

                      On 2007-09-17, Laurent Pointal <laurent.pointa l@limsi.frwrote :
                      Note3: Its funny to see how Python users tries to change the language,
                      does this occure with C, C++, Java, C# ?
                      Yes. I remember somebody I worked with once who write a C
                      program using a whole pile of macros to make it look like BASIC:

                      #define IF if (
                      #define THEN ) {
                      #define ELSE } else {
                      #define ENDIF }

                      and so on...

                      --
                      Grant Edwards grante Yow! I am deeply CONCERNED
                      at and I want something GOOD
                      visi.com for BREAKFAST!

                      Comment

                      • Bruno Desthuilliers

                        #12
                        Re: Python &quot;with&quot ;

                        Grant Edwards a écrit :
                        On 2007-09-17, Laurent Pointal <laurent.pointa l@limsi.frwrote :
                        >
                        >Note3: Its funny to see how Python users tries to change the language,
                        >does this occure with C, C++, Java, C# ?
                        >
                        Yes. I remember somebody I worked with once who write a C
                        program using a whole pile of macros to make it look like BASIC:
                        >
                        #define IF if (
                        #define THEN ) {
                        #define ELSE } else {
                        #define ENDIF }
                        >
                        and so on...
                        FWIW and IIRC, one of the rationales for C preprocessor macros was to
                        let Pascal programmers make C looks like Pascal !-)

                        Comment

                        • Bruno Desthuilliers

                          #13
                          Re: Python &quot;with&quot ;

                          Laurent Pointal a écrit :
                          (snip)
                          Note3: Its funny to see how Python users tries to change the language,
                          s/Python users/some new Python users/, IMHO.

                          Comment

                          • Colin J. Williams

                            #14
                            Re: Python &quot;with&quot ;

                            Ivan Voras wrote:
                            Hi,
                            >
                            I'm looking for a construct that's similar to (Turbo) Pascal's "with"
                            statement. I read about the Python's new "with" statement, but I was
                            dissapointed to learn that it does something different (I still don't
                            see how it's better than try..except..fi nally, but that's not my question).
                            >
                            Is there something similar to what I want that's Pythonic enough?
                            >
                            (If you're not familiar with Pascal, here's how it works:
                            >
                            with some.big.struct ure.or.nested.o bjects.element do begin
                            member1 := something;
                            member2 := something;
                            end;
                            >
                            which exactly translates to this equivalent:
                            >
                            some.big.struct ure.or.nested.o bjects.element. member1 := something;
                            some.big.struct ure.or.nested.o bjects.element. member2 := something;
                            >
                            i.e. it's a wrist-saver. I think a similar feature exists in C99, for
                            structs.
                            >
                            I know it can be almost always done by using a temporary variable:
                            >
                            tmp = some.big.struct ure.or.nested.o bjects.element
                            tmp.member1 = something
                            tmp.member2 = something
                            >
                            but this looks ugly to me.)
                            >
                            >
                            The "with" statement in Pascal was a neat feature to use with records.

                            Unfortunately, in Python 2.5, "with" has a different use.

                            Colin W.

                            Comment

                            • Nigel Rowe

                              #15
                              Re: Python &quot;with&quot ;

                              On Tue, 18 Sep 2007 00:26, Grant Edwards wrote in comp.lang.pytho n
                              <<13et3kv409e35 5d@corp.superne ws.com>>:
                              On 2007-09-17, Laurent Pointal <laurent.pointa l@limsi.frwrote :
                              >
                              >Note3: Its funny to see how Python users tries to change the
                              language,
                              >does this occure with C, C++, Java, C# ?
                              >
                              Yes. I remember somebody I worked with once who write a C
                              program using a whole pile of macros to make it look like BASIC:
                              >
                              #define IF if (
                              #define THEN ) {
                              #define ELSE } else {
                              #define ENDIF }
                              >
                              and so on...
                              >
                              and latin speaking perl programmers use Lingua::Romana: :Perligata
                              <http://www.csse.monash .edu.au/~damian/papers/HTML/Perligata.html>

                              Totaly insane. Oh, wait, they're perl programmers.

                              --
                              Nigel Rowe
                              A pox upon the spammers that make me write my address like..
                              rho (snail) fisheggs (stop) name

                              Comment

                              Working...