Python Feature Request: Explicit variable declarations

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • samjnaa@gmail.com

    #1

    Python Feature Request: Explicit variable declarations

    Hello. Please tell me whether this feature request is sane (and not
    done before) for python so it can be posted to the python-dev mailing
    list. I should say first that I am not a professional programmer with
    too much technical knowledge.

    I would like to have something like the "option explicit" statement in
    Visual Basic which turns on C-like checking for declaration of
    variables. This is highly helpful for people who are coming from C/C+
    +, for people who are learning programming using Python, and even
    professionals, since this helps prevent typo errors like:

    sunlognitude = sunlongitude + 180.0

    where the user has inadvertantly typed "g" before "n" and will later
    wonder why his application is not working as expected.

  • Paddy

    #2
    Re: Python Feature Request: Explicit variable declarations

    On Apr 14, 11:21 am, samj...@gmail.c om wrote:
    Hello. Please tell me whether this feature request is sane (and not
    done before) for python so it can be posted to the python-dev mailing
    list. I should say first that I am not a professional programmer with
    too much technical knowledge.
    >
    I would like to have something like the "option explicit" statement in
    Visual Basic which turns on C-like checking for declaration of
    variables. This is highly helpful for people who are coming from C/C+
    +, for people who are learning programming using Python, and even
    professionals, since this helps prevent typo errors like:
    >
    sunlognitude = sunlongitude + 180.0
    >
    where the user has inadvertantly typed "g" before "n" and will later
    wonder why his application is not working as expected.
    Please read this:


    PyChecker and Pylint might help you.

    - Paddy.

    Comment

    • James Stroud

      #3
      Re: Python Feature Request: Explicit variable declarations

      samjnaa@gmail.c om wrote:
      Hello. Please tell me whether this feature request is sane (and not
      done before) for python so it can be posted to the python-dev mailing
      list. I should say first that I am not a professional programmer with
      too much technical knowledge.
      >
      I would like to have something like the "option explicit" statement in
      Visual Basic which turns on C-like checking for declaration of
      variables. This is highly helpful for people who are coming from C/C+
      +, for people who are learning programming using Python, and even
      professionals, since this helps prevent typo errors like:
      >
      sunlognitude = sunlongitude + 180.0
      >
      where the user has inadvertantly typed "g" before "n" and will later
      wonder why his application is not working as expected.
      >
      I have no formal training in programming and thus have had to shake off
      all of the worst habits afflicting amateurs on my path to the modest
      proficiency I enjoy now. So let me assure you that this is something I
      can honestly say is just about the least of your worries and
      consequently has no place clogging up a language like python.

      But, if you have masochistic tendencies and want a lot of overhead in
      your programming, you can always bind yourself mercilessly to classes:


      class C(object):
      declared = ['bob', 'carol', 'ted', 'alice']
      def __setattr__(sel f, anattr, aval):
      if anattr not in C.declared:
      raise TypeError, "Just can't hook you up, bro."
      else:
      self.__dict__[anattr] = aval


      E.g.:

      pyclass C(object):
      .... declared = ['bob', 'carol', 'ted', 'alice']
      .... def __setattr__(sel f, anattr, aval):
      .... if anattr not in C.declared:
      .... raise TypeError, "Just can't hook you up, bro."
      .... else:
      .... self.__dict__[anattr] = aval
      ....
      pyc = C()
      pyc.bob = 42
      pyc.bob
      42
      pyc.x = 69
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 5, in __setattr__
      TypeError: Just can't hook you up, bro.


      Extending this ugliness to type-checking is left as an exercise for the
      reader. Using metaclasses for such nonsense is left as an exercise for
      metaclass maniacs.

      James

      Comment

      • =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

        #4
        Re: Python Feature Request: Explicit variable declarations

        samjnaa@gmail.c om schrieb:
        Hello. Please tell me whether this feature request is sane (and not
        done before) for python so it can be posted to the python-dev mailing
        list. I should say first that I am not a professional programmer with
        too much technical knowledge.
        I believe it has been requested before, but I'm too lazy now to search
        for prior discussion. The request is sane, but is also incomplete: there
        is no syntax suggested for the actual declarations of local variables,
        and no discussion whether this is meant to apply to local variables
        only, or also to global variables and object attributes.

        I think there is a fairly low chance that such a request will be
        considered. It's a big change (implementation-wise, and
        documentation-wise), and likely controversial. So one would have
        to write a PEP first (see PEP 1 for details).

        Regards,
        Martin

        Comment

        • nikolas pontikos

          #5
          Re: Python Feature Request: Explicit variable declarations

          samjnaa@gmail.c om wrote:
          Hello. Please tell me whether this feature request is sane (and not
          done before) for python so it can be posted to the python-dev mailing
          list. I should say first that I am not a professional programmer with
          too much technical knowledge.
          >
          I would like to have something like the "option explicit" statement in
          Visual Basic which turns on C-like checking for declaration of
          variables. This is highly helpful for people who are coming from C/C+
          +, for people who are learning programming using Python, and even
          professionals, since this helps prevent typo errors like:
          >
          sunlognitude = sunlongitude + 180.0
          >
          where the user has inadvertantly typed "g" before "n" and will later
          wonder why his application is not working as expected.
          >
          Just as a side-note, if you used a+=1 instead of a=a+1 then you wouldn't
          have this problem.
          Languages like Perl and VB need a strict mode because they will
          auto-vivify variable for you. I.e. they will bring variables to life
          with defined or undefined values if you use them in a l-value (left hand
          side of an assignment) without having declared them prior. If you do
          that in Python you get an exception.

          Comment

          • jamadagni

            #6
            Re: Python Feature Request: Explicit variable declarations

            Languages like Perl and VB need a strict mode because they will
            auto-vivify variable for you. I.e. they will bring variables to life
            with defined or undefined values if you use them in a l-value (left hand
            side of an assignment) without having declared them prior. If you do
            that in Python you get an exception.
            I don't comprehend. I can just type a = 5 in a new Python session and
            I get no exception. Python currently does not require variables to be
            declared before they are used on the LHS.

            Comment

            • Army1987

              #7
              Re: Python Feature Request: Explicit variable declarations

              "jamadagni" <samjnaa@gmail. comha scritto nel messaggio
              news:1176557734 .456820.275780@ p77g2000hsh.goo glegroups.com.. .
              >Languages like Perl and VB need a strict mode because they will
              >auto-vivify variable for you. I.e. they will bring variables to life
              >with defined or undefined values if you use them in a l-value (left hand
              >side of an assignment) without having declared them prior. If you do
              >that in Python you get an exception.
              >
              I don't comprehend. I can just type a = 5 in a new Python session and
              I get no exception. Python currently does not require variables to be
              declared before they are used on the LHS.
              I think (s)he meant right hand.


              Comment

              • nikolas pontikos

                #8
                Re: Python Feature Request: Explicit variable declarations

                Army1987 wrote:
                "jamadagni" <samjnaa@gmail. comha scritto nel messaggio
                news:1176557734 .456820.275780@ p77g2000hsh.goo glegroups.com.. .
                >>Languages like Perl and VB need a strict mode because they will
                >>auto-vivify variable for you. I.e. they will bring variables to life
                >>with defined or undefined values if you use them in a l-value (left hand
                >>side of an assignment) without having declared them prior. If you do
                >>that in Python you get an exception.
                >I don't comprehend. I can just type a = 5 in a new Python session and
                >I get no exception. Python currently does not require variables to be
                >declared before they are used on the LHS.
                >
                I think (s)he meant right hand.
                >
                >
                Yes I did sorry about that. If an assignment had hands then I would
                have been right ;).

                Comment

                • Bart Willems

                  #9
                  That might be the case for more complex objects...

                  Dennis Lee Bieber wrote:
                  On 14 Apr 2007 06:35:34 -0700, "jamadagni" <samjnaa@gmail. comdeclaimed
                  the following in comp.lang.pytho n:
                  In Python, the "variable" NAME does NOT define storage; unlike most
                  other classical languages where the "variable name" is a storage
                  address, and the value of the RHS is COPIED to that address. Python does
                  not do such copying. Names are references to the RHS object itself.
                  >
                  a = 5
                  >
                  means that somewhere in memory is an integer object with the value "5";
                  the name "a" is now "pasted onto" that integer object.
                  >
                  b = a
                  >
                  finds the object that has the name "a" stuck to it, and sticks a second
                  name "b" onto the same object. There is still only one "5" in memory.
                  I can try this in interactive mode:
                  >>a = 5
                  >>b = a
                  >>a += 1
                  >>print b
                  5

                  So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
                  would expect b to be increased, just as a. But after increasing a, b is
                  still 5...

                  Lists behave as described above, integers and floats don't.

                  By the way, a classic language like C has features like this too;
                  they're called pointers.

                  Comment

                  • James Stroud

                    #10
                    Re: That might be the case for more complex objects...

                    Bart Willems wrote:
                    Dennis Lee Bieber wrote:
                    >On 14 Apr 2007 06:35:34 -0700, "jamadagni" <samjnaa@gmail. comdeclaimed
                    >the following in comp.lang.pytho n:
                    > In Python, the "variable" NAME does NOT define storage; unlike most
                    >other classical languages where the "variable name" is a storage
                    >address, and the value of the RHS is COPIED to that address. Python does
                    >not do such copying. Names are references to the RHS object itself.
                    >>
                    > a = 5
                    >>
                    >means that somewhere in memory is an integer object with the value "5";
                    >the name "a" is now "pasted onto" that integer object.
                    >>
                    > b = a
                    >>
                    >finds the object that has the name "a" stuck to it, and sticks a second
                    >name "b" onto the same object. There is still only one "5" in memory.
                    >
                    I can try this in interactive mode:
                    >>a = 5
                    >>b = a
                    >>a += 1
                    >>print b
                    5
                    >
                    So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
                    would expect b to be increased, just as a. But after increasing a, b is
                    still 5...
                    >
                    Lists behave as described above, integers and floats don't.
                    >
                    By the way, a classic language like C has features like this too;
                    they're called pointers.
                    I think that after a += 1, a memory location with a 6 is created and now
                    a points to that because += has assignment buried in it.

                    Comment

                    • Bjoern Schliessmann

                      #11
                      Re: That might be the case for more complex objects...

                      Bart Willems wrote:
                      I can try this in interactive mode:
                      >>a = 5
                      >>b = a
                      >>a += 1
                      >>print b
                      5
                      >
                      So, if /a/ and /b/ where pointing to the *same* "5" in memory,
                      They do:
                      >>a = 5
                      >>b = a
                      >>a is b
                      True
                      >>a += 1
                      >>a is b
                      False

                      .... but not after a is rebound to a new int.
                      then I would expect b to be increased, just as a. But after
                      increasing a, b is still 5...
                      int objects are immutable. Thus, when rebinding a (as happens here
                      in "a += 1"), a new instance of int is created and "a" points to
                      it.
                      By the way, a classic language like C has features like this too;
                      they're called pointers.
                      C's int* behaves differently.

                      Regards,


                      Björn

                      --
                      BOFH excuse #163:

                      no "any" key on keyboard

                      Comment

                      • DillonCo

                        #12
                        Re: That might be the case for more complex objects...

                        On Saturday 14 April 2007, James Stroud wrote:
                        I think that after a += 1, a memory location with a 6 is created and now
                        a points to that because += has assignment buried in it.
                        Bingo.

                        a+=1 will (basically) translate to either "a=a.__iadd__(1 )"
                        or "a=a.__add__(1) " depending on whether __iadd__ is defined of not.
                        >>'__iadd__' in dir(5)
                        False
                        >>'__add__' in dir(5)
                        True

                        So therefore "a+=1" becomes "a=a.__add_ _(a, 1)"
                        That make is relatively obvious that a '6' would be created and assigned back
                        to a.


                        You can have some fun with this using the 'is' operator. Remember that 'is'
                        compares objects and not values. So different objects can be equal, but
                        aren't the same. Thus:
                        >>a=[1,2,3]
                        >>b=[1,2,3]
                        >>a == b
                        True
                        >>a is b
                        False

                        To demonstrate the idea of name binding:
                        >>a=500
                        >>b=500
                        >>a == b
                        True
                        >>a is b
                        False
                        >>b=a
                        >>a is b
                        True

                        So typing the literal '500' creates an integer object with the value 500. By
                        typing it twice, two different objects of identical value are created
                        and "put in" two variables. However, by assigning one from the other, the
                        same object (created by the literal '500') is assigned to both variables.
                        This is why Python calls assignments "bindings"; you're realling just binding
                        the object from the right side to the name on the left.


                        For confusion's sake, here's what happens if you use smaller numbers:
                        >>a=1
                        >>b=1
                        >>a is b
                        True
                        >>3-2 is a
                        True

                        That happens because CPython (a particular and very common implementation of
                        Python) pre-creates objects for all small integers (something like <=100).
                        This saves memory, because all values of '1' are the same! So the
                        literal '1' simply gets a reference to the existing object of value '1',
                        rather than creating a new one (like the literal '500' does). The same is
                        also true for strings with len<=1.



                        Comment

                        • Steven D'Aprano

                          #13
                          Re: Python Feature Request: Explicit variable declarations

                          On Sat, 14 Apr 2007 15:55:03 +0000, Dennis Lee Bieber wrote:

                          Names are references to the RHS object itself.
                          >
                          a = 5
                          >
                          means that somewhere in memory is an integer object with the value "5";
                          the name "a" is now "pasted onto" that integer object.
                          That's not correct, as it implies that the object 5 knows which names (if
                          any) it is associated with. That's not the case: objects don't know which
                          names point to them.

                          What actually happens is that the current namespace gains an entry "a",
                          which points to the existing object 5.

                          b = a
                          >
                          finds the object that has the name "a" stuck to it, and sticks a second
                          name "b" onto the same object.
                          It most certainly does not. What it does is add another name into the
                          namespace, "b", and points it to the same object as "a" already points to.

                          We shouldn't be frightened of introducing namespaces to newbies. They
                          have to learn sooner or later, and they aren't hard to learn. Sometimes
                          over-simplifying is worse than not simplifying at all.

                          A namespace is just a thing in memory that the Python compiler looks up
                          names. They are very important to Python.



                          --
                          Steven.

                          Comment

                          • Steven D'Aprano

                            #14
                            Re: That might be the case for more complex objects...

                            On Sat, 14 Apr 2007 16:03:03 -0400, Bart Willems wrote:

                            I can try this in interactive mode:
                            >>a = 5
                            >>b = a
                            >>a += 1
                            >>print b
                            5
                            >
                            So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I
                            would expect b to be increased, just as a.
                            This is what you are implicitly _thinking_:

                            "a" points to a memory location, holding a few bytes with the bit pattern
                            0x05. When I add 1 to it, the bytes change to 0x06.

                            But integers in Python aren't bit patterns, they are objects. You can't
                            make the 5 object have value 6, that would be terrible:

                            py5 + 5 # remember that 5 has been changed to have value six!
                            12

                            So a += 1 rebinds the name "a" to the object 6. The name "b" still points
                            to the object 5, because you didn't do anything to "b".

                            Now, for extra credit: can you explain why this happens?
                            >>alist = [0]
                            >>blist = alist
                            >>alist += [1]
                            >>blist
                            [0, 1]



                            --
                            Steven.

                            Comment

                            • Alex Martelli

                              #15
                              Re: Python Feature Request: Explicit variable declarations

                              Dennis Lee Bieber <wlfraed@ix.net com.comwrote:
                              ...
                              In Python, the "variable" NAME does NOT define storage; unlike most
                              other classical languages where the "variable name" is a storage
                              address, and the value of the RHS is COPIED to that address. Python does
                              not do such copying. Names are references to the RHS object itself.
                              Right, but that's just like today's most popular languages -- Java and
                              C# -- with the one difference that in those languages "boxed" types
                              (elementary numbers, in Java) have different semantics.
                              Languages with "variable declarations" are pre-allocating object
                              space that can only hold objects of that type (ignoring VB "variant").
                              Again, this is not true for the most popular languages, Java and C# --
                              in those cases, excepting boxed types, variable declarations are
                              "pre-allocating" space for references, which can refer to any type
                              derived from theirs (so, e.g., in Java, "Object x;" means x can refer to
                              anything at all except a boxed type such as float).

                              I think you're confusing two issues with languages' underlying models:
                              boxes (C, Fortran, etc) vs tags (Java, Python, etc) for variables; and
                              declarations vs not. APL uses boxes but no declarations, etc, etc: you
                              can find all four variants!-)


                              Alex

                              Comment

                              Working...