473,895 Members | 2,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

variable declaration

Hello All!

I'am novice in python, and I find one very bad thing (from my point of view) in
language. There is no keyword or syntax to declare variable, like 'var' in
Pascal, or special syntax in C. It can cause very ugly errors,like this:

epsilon=0
S=0
while epsilon<10:
S=S+epsilon
epselon=epsilon +1
print S

It will print zero, and it is not easy to find such a bug!

Even Visual Basic have 'Option Explicit' keyword! May be, python also have such
a feature, I just don't know about it?

Alexander, za**@bk.ru
Jul 18 '05
83 6565
> A decorator is a modifier to a subsequent binding, and it modifies the
reference and not the referent. So how is it anythng but declarative?


I learned the hard way that it still is simply interpreted - its a pretty
straight forward syntactic sugaring, as this shows:

foo = classmethod(foo )

becomes:

@classmethod

Now @classmethod has to return a callable that gets passed foo, and the
result is assigned to foo - not more, not less, so it becomes equivalent to
the older type of creating a class method.

Is this a declaration? I'd personally say and think "practicall y, yes", as I
also view

class Bar:
....

as a declaration. But obviously some people like Alex Martelli have
different views on this (and are right), because you can do this in python:

if condition:
class Foo:
def bar(self):
pass

else:
class Foo:
def schnarz(self):
pass

So that makes class statements not as declarative as they are in languages
like java.

So to sum it up (for me at least): things like metaclasses, decorators and
so on make me write code more declarative - if they are a declaration in
the strict sense, I don't bother.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #11
Michael Tobis <mt@3planes.com > wrote:
With all due respect, I think "so go away if you don't like it" is
excessive, and "so go away if you don't like it and you obviously don't
like it so definitely go away" is more so. The writer is obviously
I disagree: I believe that, if the poster really meant what he wrote, he
may well be happier using other languages and all the declarations he
cherishes, so recommending that course of action to him is quite proper
on my part. Nobody forces him to follow my advice, in particular if, as
you suggest, he's mis-expressed himself.
neither a native speaker of English nor an accomplished user of Python,
so there are two language issues here. Try expressing your reply in
Russian before deciding that "very ugly" means exactly what you think
it does.
I don't know any Russian, and I don't see how that's relevant. If the
poster said "it's very ugly" meaning "I'm not fully comfortable with it"
or "it's the best thing I've ever seen in my life", he can perfectly
well correct his misexpression if he cares to -- not my job to try to
read his mind and perform exegesis on his words.
I think just saying that "experience d Python users have not
found the lack of declarations to be a major hindrance" would have been
more appropriate.
I think it would have been true, but weak and insufficient. Not only
experienced Python users have that opinion: lack of declarations didn't
faze me even I was a total newbie (other things did, and I learned that
most of them were good only gradually; but if I'd blocked on something
as obviously *fundamental* to Python, I'd never have gone deeper, of
course). Plus, I did offer a URL for a classic post by Robert Martin,
who's not even talking about Python yet came to exactly the same
conclusion *while using statically typed languages*, just on the basis
of unit-testing experience.

Also, the assertion that "Python has no declarations whatsoever" is no
longer obviously true. In the 2.4 decorator syntax, a decorator line is
not executable, but rather a modifier to a subsequent symbol binding. I
call it a declaration.
You may call it a strawberry, if you wish, but that doesn't mean it will
taste good with fresh cream. It's nothing more and nothing less than an
arguably weird syntax for a perfectly executable statement:

@<expression>
def functionname <rest of function header and body>

means EXACTLY the same thing as

def functionname <rest of function header and body>
functionname = <expression>(fu nctionname)

Nothing more, nothing less. The splat-syntax isn't a "declaratio n" in
any sense of the word, just a not-so-short shortcut for an assignment
statement. Proof by disassembly:
def f(): .... @foo
.... def g(): pass
.... dis.dis(f) 2 0 LOAD_GLOBAL 0 (foo)
3 LOAD_CONST 1 (<code object g at 0x3964e0,
file "<stdin>", line 2>)
6 MAKE_FUNCTION 0
9 CALL_FUNCTION 1
12 STORE_FAST 0 (g)
15 LOAD_CONST 0 (None)
18 RETURN_VALUE def f(): .... def g(): pass
.... g = foo(g)
.... dis.dis(f)

2 0 LOAD_CONST 1 (<code object g at 0x389ee0,
file "<stdin>", line 2>)
3 MAKE_FUNCTION 0
6 STORE_FAST 0 (g)

3 9 LOAD_GLOBAL 1 (foo)
12 LOAD_FAST 0 (g)
15 CALL_FUNCTION 1
18 STORE_FAST 0 (g)
21 LOAD_CONST 0 (None)
24 RETURN_VALUE

the splat-syntax optimizes away one STORE_FAST of g and the
corresponding LOAD_FAST, by having the LOAD_GLOBAL of foo earlier; nice,
but not earth-shaking, and definitely no "declaratio n" whatsoever.

Let me add that I remain unconvinced that a language cannot combine the
best features of Python with very high performance, which is ultimately
I'm also unconvinced. Fortunately, so is the EU, so they have approved
very substantial financing for the pypy project, which aims in good part
exactly at probing this issue. If any single individual can be called
the ideator of pypy, I think it's Armin Rigo, well-known for his
excellent psyco specializing-compiler for Python: the key research
thesis behind both projects is that a higher-level, dynamic language
need not have performance inferior to a lower-level one and indeed may
well beat it.
what I want. It seems to me that such a language (possibly Python,
possibly a Python fork, possibly something else) will need substantial
programmer control over references as well as referents.
pypy is dedicated to proving you're wrong. With at least half a dozen
great people now finally having started working full-time on the
project, and due to continue so doing for the next couple of years, I
like our chances.

It seems to me that Python has a weaker case for purity in this regard
now that the dam has been breached with decorator syntax, which is, I
think, a declaration.
I entirely disagree that a minor syntax wheeze to introduce a shortcut
for a particular executable statement ``is a a declaration''.

Let me conclude with the confession that I'm still on the steep part of
the learning curve (if it ever flattens out at all...). Python has
definitely significantly modified how I think about things, and I
deeply appreciate all the efforts of you veterans. So I say this all
with some trepidation, because I don't want to join Alexander in
inadvertently offending you. And since I presumably missed some intense
flame wars about decorators by only a couple of months, this may be a
real hornet's nest I am poking.
Almost nobody really liked the splat-syntax for decorators, except of
course Guido, who's the only one who really counts (the BDFL). But that
was strictly a syntax-sugar issue -- which was exactly the reason making
the flamewars SO ferocious. It's one of Parkinson's Laws: the amount
and energy of discussion on an issue is inversely proportional to the
issue's importance. Fortunately, I was otherwise busy, so didn't enter
the fray at all (I intensely dislike the splat, but I don't care all
that much about such minor syntax sugar one way or another, anyway).

fici In summary, again with all due respect and gratitude for the
spectacularly excellent product that Python is today, I wonder *why*
this strong aversion to declarative statements, and *whether* decorator
syntax constitutes a violation of it. I'd appreciate any responses or
links.


If "declarativ e statement" means anything, I guess it means "having to
tell stuff to the compiler to be taken into account during compilation
but irrelevant at runtime". Python does have one such wart, the
'global' statement, and it's just as ugly as one might imagine, but
fortunately quite marginal, so one can almost forget it.

I have nothing against a declarative style _per se_ -- it just doesn't
fit Python's "everything happens at runtime" overall worldview, and that
simple and powerful worldview is a good part of what makes Python tick
SO well. I think there's a space for declarative languages, and it is
mostly ``orthogonal'' to Python. See, for example,
<http://www.strakt.com/docs/ep04_caps.pdf>, specifically the part of the
presentation that's about BLAM -- that's a declarative language (with
embedded Python for ``actions'', e.g., triggers, and computations), and
I think a neat and useful design, too.
Alex
Jul 18 '05 #12
Alex Martelli wrote:
Michael Tobis <mt@3planes.com > wrote:

[...]
Let me add that I remain unconvinced that a language cannot combine the
best features of Python with very high performance, which is ultimately

I'm also unconvinced. Fortunately, so is the EU, so they have approved
very substantial financing for the pypy project, which aims in good part
exactly at probing this issue. If any single individual can be called
the ideator of pypy, I think it's Armin Rigo, well-known for his
excellent psyco specializing-compiler for Python: the key research
thesis behind both projects is that a higher-level, dynamic language
need not have performance inferior to a lower-level one and indeed may
well beat it.

I should be failing in my duty as Chairman if I didn't remind readers at
this point that they can hear Armin Rigo's talk "PyPy and Type
Inference" at PyCon at 5:30 on Wednesday March 23.

http://www.python.org/pycon/dc2005/register.html

While Alex is not necessarily too modest to mention it he might forget
that he is also giving three talks to PyCon. I believe this is the first
year he has been able to attend PyCon, so delegates are definitely in
for a treat this year.

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #13
"Alexander Zatvornitskiy"
<Al************ *********@p131. f3.n5025.z2.fid onet.org> wrote in message
news:MS******** *************** ******@fidonet. org...
Hello All!

I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in
Pascal, or special syntax in C. It can cause very ugly errors,like this:

epsilon=0
S=0
while epsilon<10:
S=S+epsilon
epselon=epsilon +1
print S

It will print zero, and it is not easy to find such a bug!

Even Visual Basic have 'Option Explicit' keyword! May be, python also have such a feature, I just don't know about it?


Exactly so!
Python *does* require that your variables be declared and initialized before
you use them. You did that with epsilon=0 and S=0 at the top. It is
unfortunate, however, that the statement epselon=epsilon +1 also declares a
new variable in the wrong place at the wrong time. Such mispellings are a
*common* error caught instantly in languages that require a more formal
declaration procedure.

Another irksome sitiuation is that while Python does enforce strict type
checking, you can re-declare variables and morph them in the middle of
nowhere.
S = 0 # It's an Integer!
S = S + 'Hello' # No can do! Strong type checking forbids this.
S = 'GoodBye' # Whoops - Now it's a string! Unfortunately
legal!
This seemingly demolishes all the good reasons one has for wanting strict
type checking.

That second example is just bad programming practice and easy to avoid. The
problem you point out in your code, however, hurts! Was that an I, an l or a
1 in the variable name?

Hey! - I like Python a lot.
But nothings perfect
Thomas Bartkus
Jul 18 '05 #14

Thomas Bartkus wrote:
Python *does* require that your variables be declared and initialized before you use them. You did that with epsilon=0 and S=0 at the top. It is
unfortunate, however, that the statement epselon=epsilon +1 also declares a new variable in the wrong place at the wrong time. Such mispellings are a *common* error caught instantly in languages that require a more formal declaration procedure.

I have no interest in arguing this right now, but it does raise a
question for me: How common is it for a local variable to be bound in
more than one place within a function? It seems that it isn't (or
shouldn't be) too common.

Certainly the most common case where this occurs is for temporary
variables and counters and stuff. These typically have short names and
thus are not as likely to be misspelled.

Another common place is for variables that get bound before and inside
a loop. I would guess that's not as common in Python as it is in other
languages, seeing that Python has features like iterators that obviate
the need to do this. (The OP's original example should have been "for
epsilon in range(10)"; epsilon only needed bound in one place.)

I guess this might be why, in practice, I don't seem to encounter the
misspelling-a-rebinding error too often, even though I'm prone to
spelling errors. Perhaps, if someone runs into this error a lot, the
problem is not with Python, but with their tendency to rebind variables
too much? Just a thought.
--
CARL BANKS

Jul 18 '05 #15
In article <1g************ *************** *@yahoo.com>,
Alex Martelli <al*****@yahoo. com> wrote:

Some people claim a language should change the way you think -- a
frequent poster, excellent Python contributor, and friend, even has that
claim in his signature.


Generally speaking, I change my .sig either when I get bored or when
someone references it. So here's the new one.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"Given that C++ has pointers and typecasts, it's really hard to have a serious
conversation about type safety with a C++ programmer and keep a straight face.
It's kind of like having a guy who juggles chainsaws wearing body armor
arguing with a guy who juggles rubber chickens wearing a T-shirt about who's
in more danger." --Roy Smith, c.l.py, 2004.05.23
Jul 18 '05 #16
This is definitely a wart:

.... z = 42.3
....
.... def f():
.... if False:
.... global z
.... z = -666
....
.... f()
.... print z

Jul 18 '05 #17
Alex Martelli wrote:
Michael Tobis <mt@3planes.com > wrote: he can perfectly
well correct his misexpression if he cares to -- not my job to try to
read his mind and perform exegesis on his words.
Well, I hate to try to tell you your job, but it doesn't seem to be to
be all that great of a marketing strategy to actively chase people
away... Hey, he might have been a Nutshell customer.
I think it would have been true, but weak and insufficient. Not only
experienced Python users have that opinion: lack of declarations didn't faze me even I was a total newbie
It did me, and it did many others. Perhaps you are unrepresentativ e.

It's one thing to say "no can do, sorry", it's another to say "you
don't need this anyway and if you think you do you aren't worthy".

In fact, it was your book I spent the most time thumbing through
looking for the "use strict" equivalent that I was absolutely certain
must exist. Hell, even Fortran eventually gave in to "IMPLICIT NONE".
It's practically the only thing I've ever expected to find in Python
that hasn't vastly exceeded my expectations, aand I'm sure Alexander is
not the only person to be put off by it. In fact, I'd recommend a
paragraph early in the Nutshell book saying "there are no declarations,
no use strict, no implicit none, sorry, forget it", and an index
listing under "declaratio ns" pointing to a detailed exegesis of their
nonexistence. It would have saved me some time.

It's true that in some sense an assignment is all the declaration you
need. I think Carl Banks's point (what we think of as assignment as a
carryover from other languages is really rebinding, and in many cases
can be avoided) is also helpful.

But that doesn't make the "epselon" bug go away, and wanting to have a
way to catch it quickly isn't, to my mind, obviously a criminal act.
Also, based on what DogWalker demonstrates, it's really not that alien
to Python and should be feasible.
Also, the assertion that "Python has no declarations whatsoever" is no longer obviously true. In the 2.4 decorator syntax, a decorator line is not executable, but rather a modifier to a subsequent symbol binding. I call it a declaration.


You may call it a strawberry, if you wish, but that doesn't mean it

will taste good with fresh cream. It's nothing more and nothing less than an arguably weird syntax for a perfectly executable statement:
This may well be true in implementation, but cognitively it is a
declaration that modifies the reference and not the referent. I see
that it is a big deal to ask for more of these, but I don't see why.
Let me add that I remain unconvinced that a language cannot combine the best features of Python with very high performance, which is

ultimately
I'm also unconvinced. Fortunately, so is the EU, so they have approved very substantial financing for the pypy project, which aims in good part exactly at probing this issue.
I hope this works out, but it's hard for me to see how pypy will avoid
lots of hashing through dictionaries. I'm willing to help it by
declaring an immutable reference. Here, don't look this up; it always
points to that.

I'm guessing that this will also be considered a bad idea, and maybe
someday I'll understand why. I'm looking for insight, not controversy.
If any single individual can be called
the ideator of pypy, I think it's Armin Rigo, well-known for his
excellent psyco specializing-compiler for Python:
I'm hoping I can make the meeting. Maybe proximity to the core group
will help me approach the sort of enlightenment I seek. Just being in
the vicinity of Ian Bicking's aura on occasion has been most inspiring.
Almost nobody really liked the splat-syntax for decorators, except of
course Guido, who's the only one who really counts (the BDFL). But that was strictly a syntax-sugar issue
Um, sugar isn't exactly what I'd call it. I think it matters a lot
though. Python's being easy on the eyes is not a trivial advantage for
some people, myself incuded.
If "declarativ e statement" means anything, I guess it means "having to tell stuff to the compiler to be taken into account during compilation but irrelevant at runtime". Python does have one such wart, the
'global' statement, and it's just as ugly as one might imagine, but
fortunately quite marginal, so one can almost forget it.
I am trying to talk about having expressive power in constraining
references as well as the referents. Python studiously avoids this, but
decorators change that. I am not deep enough into the mojo as yet to
have more than a glimmer of an idea about the distinction you are
making. It's not the one I'm trying to make.

decorators may not be implemented as declarations, but they cognitively
act as declarations, and that's what I care about here.
I have nothing against a declarative style _per se_ -- it just doesn't fit Python's "everything happens at runtime" overall worldview, and that simple and powerful worldview is a good part of what makes Python tick SO well.


I'm glad you have said something something I absolutely agree with. I'm
alarmed at the suggestions here that class and def blocks are
declarative. The fact that they're executable is really a core part of
the beauty of Python.

However, I don't see how an 'import strict' would necessarily violate
this, nor an "import immutableref", which is something I would find
useful in trying to wrestle with NumArray, and which a high-performance
Python could (I think) use to advantage.

Now I may be wrong; in fact I'd bet against me and in favor of you and
Frederik if I had to bet. It's just that I don't see why I'm wrong.
--
mt

Jul 18 '05 #18
Michael Tobis wrote:
This is definitely a wart:

... z = 42.3
...
... def f():
... if False:
... global z
... z = -666
...
... f()
... print z


no, it's a declaration. from the documentation:

http://docs.python.org/ref/global.html

"The global statement is a declaration which holds for the entire
current code block."

"the global is a directive to the parser. It applies only to code
parsed at the same time as the global statement"

</F>

Jul 18 '05 #19
"Michael Tobis" <mt@3planes.com > writes:
In fact, I'd recommend a paragraph early in the Nutshell book saying
"there are no declarations, no use strict, no implicit none, sorry,
forget it",
It would have to be a pretty long paragraph, if it were to list all
the things that you do NOT find in Python.
and an index listing under "declaratio ns" pointing to a detailed
exegesis of their nonexistence.
Think about this. You are either asking that the book's author
anticipate your personal expectations, and write the book to cater for
YOUR PERSONAL expectiations ... or you are asking for a book with an
inifititely long index. The list of things absent from Python is
infinite.
It would have saved me some time.


You don't want a book, you want a personal tutor.
Jul 18 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2684
by: YGeek | last post by:
Is there any difference between declaring a variable at the top of a method versus in the code of the method? Is there a performance impact for either choice? What about if the method will return before the variable is used? I'm trying to get an idea of whether the .NET compilers for VB.NET and C# will move all variable declaration to the beginning of a method or whether they will allocate the memory as it is needed by the method to...
12
3117
by: Michael B Allen | last post by:
Which style of local variable declaration do you prefer; put everything at the top of a function or only within the block in which it is used? For example; void fn(struct foo *f, int bar) { struct abc d; int i;
7
7723
by: seamoon | last post by:
Hi, I'm doing a simple compiler with C as a target language. My language uses the possibility to declare variables anywhere in a block with scope to the end of the block. As I remembered it this would be easily translated to C, but it seems variable declaration is only possible in the beginning of a block in C. Any suggestions how to get around this?
5
2431
by: widmont | last post by:
Hello, I would like to know the difference between two variable declaration ways: int point(0); and int point=0;
21
2856
by: Kannan | last post by:
Its been a while I have done pure C programming (I was coding in C++). Is the following function valid according to standard C? int main(int argc, char *argv) { int x; x = 9; printf("Value of x is: %d\n", x);
9
6807
by: Denis Petronenko | last post by:
i can write something like this int foo() { return 100; } if( int x=foo() ) { .... }else{
14
13084
by: subramanian100in | last post by:
Consider the following program: #include <iostream> using namespace std; int main() { int i;
15
14924
by: vaib | last post by:
hi to all.i'd like to know the actual difference between variable declaration and definition.it would be very helpful if anyone out there wud help me out with this thing.i'm writing here after here after a long time since people here also helped me out with my lexer. thanking in anticipation.
1
11888
NeoPa
by: NeoPa | last post by:
Problem Description : In VBA there is an option to enforce declaration of variables in your code. With this set, any reference to a variable that has not been previously declared (Dim; Private; Public; Global; etc) will cause an error, either at compile time or when attempting to execute the procedure it's referred to from within. With this unset, any unregognised references will be treated as a previously unknown and unset variable of type...
0
9990
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11250
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10475
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9653
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8030
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7181
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6072
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4695
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4291
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.