One thing I sometimes miss, which is common in some other languages (c++),
is idea of block scope. It would be useful to have variables that did not
outlive their block, primarily to avoid name clashes. This also leads to
more readable code. I wonder if this has been discussed? 24 2633
Neal Becker wrote:
One thing I sometimes miss, which is common in some other languages (c++),
is idea of block scope. It would be useful to have variables that did not
outlive their block, primarily to avoid name clashes. This also leads to
more readable code. I wonder if this has been discussed?
Probably, with good code, block scope would be overkill, except that I
would welcome list comprehensions to have a new scope:
pyi
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.NameError'>: name 'i' is not defined
py[i for i in xrange(4)]
[0, 1, 2, 3]
pyi # hoping for NameError
3
James Stroud <js*****@mbi.ucla.eduwrites:
Probably, with good code, block scope would be overkill, except that I
would welcome list comprehensions to have a new scope:
Block scope is a win because it gets rid of the uncertainty of whether
the variable is used outside the block or not. The "good code" theory
(just manually don't use the variable elsewhere) doesn't always hold
up under release deadline pressure and so on and doesn't make sense
anyway. What's the point of NOT having block scope if you don't want
to allow for creating variables in inner blocks and using them in
other blocks? I think it's best to require creating the variable
in a mutually enclosing scope if you want to use it that way.
Paul Rubin wrote:
James Stroud <js*****@mbi.ucla.eduwrites:
>>Probably, with good code, block scope would be overkill, except that I would welcome list comprehensions to have a new scope:
Block scope is a win because it gets rid of the uncertainty of whether
the variable is used outside the block or not.
In a language with few declarations, it's probably best not to
have too many different nested scopes. Python has a reasonable
compromise in this area. Functions and classes have a scope, but
"if" and "for" do not. That works adequately.
Javascript got it wrong. They have declarations, but the default,
in the absence of a declaration, is global, not local or an error.
Bad design. It's a result of retrofitting declarations to a language,
which usually has painful aftereffects.
John Nagle
John Nagle <na***@animats.comwrites:
In a language with few declarations, it's probably best not to
have too many different nested scopes. Python has a reasonable
compromise in this area. Functions and classes have a scope, but
"if" and "for" do not. That works adequately.
I think Perl did this pretty good. If you say "my $i" that declares
$i to have block scope, and it's considered good practice to do this,
but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }"
and that gives $i the same scope as the for loop. Come to think of it
you can do something similar in C++.
Paul Rubin wrote:
John Nagle <na***@animats.comwrites:
> In a language with few declarations, it's probably best not to have too many different nested scopes. Python has a reasonable compromise in this area. Functions and classes have a scope, but "if" and "for" do not. That works adequately.
I think Perl did this pretty good. If you say "my $i" that declares
$i to have block scope, and it's considered good practice to do this,
but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }"
and that gives $i the same scope as the for loop. Come to think of it
you can do something similar in C++.
How then might one define a block? All lines at the same indent level
and the lines nested within those lines?
i = 5
for my i in xrange(4):
if i: # skips first when i is 0
my i = 100
if i:
print i # of course 100
break
print i # i is between 0 & 3 here
print i # i is 5 here
Doesn't leave a particularly bad taste in one's mouth, I guess (except
for the intended abuse).
James
James Stroud wrote:
Paul Rubin wrote:
>John Nagle <na***@animats.comwrites:
>> In a language with few declarations, it's probably best not to have too many different nested scopes. Python has a reasonable compromise in this area. Functions and classes have a scope, but "if" and "for" do not. That works adequately.
I think Perl did this pretty good. If you say "my $i" that declares $i to have block scope, and it's considered good practice to do this, but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" and that gives $i the same scope as the for loop. Come to think of it you can do something similar in C++.
How then might one define a block? All lines at the same indent level
and the lines nested within those lines?
i = 5
for my i in xrange(4):
if i: # skips first when i is 0
my i = 100
if i:
print i # of course 100
break
print i # i is between 0 & 3 here
print i # i is 5 here
Doesn't leave a particularly bad taste in one's mouth, I guess (except
for the intended abuse).
James
Yes, the above is pretty much what I had in mind. +1.
On Apr 7, 6:48 am, James Stroud <jstr...@mbi.ucla.eduwrote:
Neal Becker wrote:
One thing I sometimes miss, which is common in some other languages (c++),
is idea of block scope. It would be useful to have variables that did not
outlive their block, primarily to avoid name clashes. This also leads to
more readable code. I wonder if this has been discussed?
Probably, with good code, block scope would be overkill, except that I
would welcome list comprehensions to have a new scope:
Generator expressions have a new scope, and in Python 3.0 list
comprehensions will have one as well (according to http://www.python.org/dev/peps/pep-0289/
). It's a fix that might break existing code so it couldn't be
introduced in "minor" versions like 2.4 and 2.5.
Neal Becker <nd*******@gmail.comwrote:
...
i = 5
for my i in xrange(4):
if i: # skips first when i is 0
my i = 100
if i:
print i # of course 100
break
print i # i is between 0 & 3 here
print i # i is 5 here
Doesn't leave a particularly bad taste in one's mouth, I guess (except
for the intended abuse).
James
Yes, the above is pretty much what I had in mind. +1.
I prefer Java's approach (14.4.2 in the JLS 2nd edition): forbid "inner"
blocks from shadowing variables in "outer" ones. I quote:
"""
If a declaration of an identifier as a local variable of the same
method, constructor, or initializer block appears within the scope of a
parameter or local variable of the same name, a compile-time error
occurs.
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
This restriction helps to detect some otherwise very obscure bugs.
"""
I entirely agree with the JLS here, having fought just such bugs in C++
and other languages that lack the restriction in question. I just wish
Python had adopted the same restriction regarding nested functions, when
proper lexical scoping was introduced -- I argued for it at the time,
but backwards compatibility blocked its introduction. There are
definitely NOT many Java-specific language characteristics that I like,
but this one is a winner!-) [[but, I disagree with the lack in Java of
a similar restriction against shadowing between instance variables and
local variables, and the weak rationale for that in the JLS:-)]].
Alex
Alex Martelli wrote:
Neal Becker <nd*******@gmail.comwrote:
...
>>i = 5 for my i in xrange(4): if i: # skips first when i is 0 my i = 100 if i: print i # of course 100 break print i # i is between 0 & 3 here print i # i is 5 here
Doesn't leave a particularly bad taste in one's mouth, I guess (except for the intended abuse).
James
Yes, the above is pretty much what I had in mind. +1.
I prefer Java's approach (14.4.2 in the JLS 2nd edition): forbid "inner"
blocks from shadowing variables in "outer" ones. I quote:
"""
If a declaration of an identifier as a local variable of the same
method, constructor, or initializer block appears within the scope of a
parameter or local variable of the same name, a compile-time error
occurs.
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
This restriction helps to detect some otherwise very obscure bugs.
"""
I entirely agree with the JLS here, having fought just such bugs in C++
and other languages that lack the restriction in question. I just wish
Python had adopted the same restriction regarding nested functions, when
proper lexical scoping was introduced -- I argued for it at the time,
but backwards compatibility blocked its introduction. There are
definitely NOT many Java-specific language characteristics that I like,
but this one is a winner!-) [[but, I disagree with the lack in Java of
a similar restriction against shadowing between instance variables and
local variables, and the weak rationale for that in the JLS:-)]].
What do you think the chances are of this being accepted for Python 3.0?
It is indeed about the most rational approach, though of course it does
cause problems with dynamic namespaces.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com al***@mac.com (Alex Martelli) writes:
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
I'm ok with this; at the minimum, I think such nesting should produce
a warning message.
Steve Holden <st***@holdenweb.comwrote:
What do you think the chances are of this being accepted for Python 3.0?
It is indeed about the most rational approach, though of course it does
cause problems with dynamic namespaces.
What problems do you have in mind? The compiler already determines the
set of names that are local variables for a function; all it needs to do
is diagnose an error or warning if the set of names for a nested
function overlaps with that of an outer one.
I shamefully admit that I haven't followed Python 3.0 discussions much
lately, so I don't really know what's planned on this issue.
Alex
Paul Rubin <http://ph****@NOSPAM.invalidwrote: al***@mac.com (Alex Martelli) writes:
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
I'm ok with this; at the minimum, I think such nesting should produce
a warning message.
Yes, a warning could surely be a reasonable compromise.
Alex
In article <1h***************************@mac.com>,
Alex Martelli <al***@mac.comwrote:
>Steve Holden <st***@holdenweb.comwrote:
>> What do you think the chances are of this being accepted for Python 3.0? It is indeed about the most rational approach, though of course it does cause problems with dynamic namespaces.
What problems do you have in mind? The compiler already determines the set of names that are local variables for a function; all it needs to do is diagnose an error or warning if the set of names for a nested function overlaps with that of an outer one.
exec?
--
Aahz (aa**@pythoncraft.com) <* http://www.pythoncraft.com/
Why is this newsgroup different from all other newsgroups?
Paul Rubin wrote:
John Nagle <na***@animats.comwrites:
> In a language with few declarations, it's probably best not to have too many different nested scopes. Python has a reasonable compromise in this area. Functions and classes have a scope, but "if" and "for" do not. That works adequately.
I think Perl did this pretty good. If you say "my $i" that declares
$i to have block scope, and it's considered good practice to do this,
but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }"
and that gives $i the same scope as the for loop. Come to think of it
you can do something similar in C++.
Those languages have local declarations. "my" is a local
declaration. If you have explicit declarations, explict block
scope is no problem. Without that, there are problems. Consider
def foo(s, sname) :
if s is None :
result = ""
else :
result = s
msg = "Value of %s is %s" % (sname, result)
return(msg)
It's not that unusual in Python to initialize a variable on
two converging paths. With block scope, you'd break
code that did that.
John Nagle
Aahz <aa**@pythoncraft.comwrote:
In article <1h***************************@mac.com>,
Alex Martelli <al***@mac.comwrote:
Steve Holden <st***@holdenweb.comwrote:
>
What do you think the chances are of this being accepted for Python 3.0?
It is indeed about the most rational approach, though of course it does
cause problems with dynamic namespaces.
What problems do you have in mind? The compiler already determines the
set of names that are local variables for a function; all it needs to do
is diagnose an error or warning if the set of names for a nested
function overlaps with that of an outer one.
exec?
option 1: that just runs the compiler a bit later -- thus transforming
ClashingVariableError into a runtime issue, exactly like it already does
for SyntaxError.
option 2: since a function containing any exec statement does not
benefit from the normal optimization of local variables, let it also
forgo the normal diagnosis of shadowed/clashing names.
option 3: extend the already-existing prohibition of mixing exec with
nested functions:
>>def outer():
.... def inner(): return x
.... exec('x=23')
.... return inner()
....
File "<stdin>", line 3
SyntaxError: unqualified exec is not allowed in function 'outer' it
contains a nested function with free variables
to prohibit any mixing of exec and nested functions (not just those
cases where the nested function has free variables).
My personal favorite is option 3.
Alex al***@mac.com (Alex Martelli) writes:
exec?
option 1: that just runs the compiler a bit later ...
Besides exec, there's also locals(), i.e.
locals['x'] = 5
can shadow a variable. Any bad results are probably deserved ;)
On Apr 7, 8:50 am, James Stroud <jstr...@mbi.ucla.eduwrote:
Paul Rubin wrote:
John Nagle <n...@animats.comwrites:
In a language with few declarations, it's probably best not to
have too many different nested scopes. Python has a reasonable
compromise in this area. Functions and classes have a scope, but
"if" and "for" do not. That works adequately.
I think Perl did this pretty good. If you say "my $i" that declares
$i to have block scope, and it's considered good practice to do this,
but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }"
and that gives $i the same scope as the for loop. Come to think of it
you can do something similar in C++.
How then might one define a block? All lines at the same indent level
and the lines nested within those lines?
i = 5
for my i in xrange(4):
if i: # skips first when i is 0
my i = 100
if i:
print i # of course 100
break
print i # i is between 0 & 3 here
print i # i is 5 here
Doesn't leave a particularly bad taste in one's mouth, I guess (except
for the intended abuse).
How about something like this instead:
i = 5
block:
for i in xrange(4):
if i: # skips first when i is 0
block:
i = 100
if i:
print i # of course 100
break
print i # i is between 0 & 3 here
print i # i is 5 here
Any variable that's assigned to within a block would be local to that
block, as it is in functions.
Paul Rubin <http://ph****@NOSPAM.invalidwrote: al***@mac.com (Alex Martelli) writes:
exec?
option 1: that just runs the compiler a bit later ...
Besides exec, there's also locals(), i.e.
locals['x'] = 5
can shadow a variable. Any bad results are probably deserved ;)
>>locals['x']=5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object does not support item
assignment
I suspect you want to index the results of calling locals(), rather than
the builtin function itself. However:
>>def f():
.... locals()['x'] = 5
.... return x
....
>>f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
NameError: global name 'x' is not defined
No "shadowing", as you see: the compiler knows that x is NOT local,
because it's not assigned to (the indexing of locals() does not count:
the compiler's not expected to detect that), so it's going to look it up
as a global variable (and not find it in this case).
I think that ideally there should be a runtime error when assigning an
item of locals() with a key that's not a local variable name (possibly
excepting functions containing exec, which are kind of screwy anyway).
Alex al***@mac.com (Alex Martelli) writes:
>locals['x']=5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object does not support item
assignment
Whoops, yeah, meant "locals()['x'] = 5".
I think that ideally there should be a runtime error when assigning an
item of locals() with a key that's not a local variable name (possibly
excepting functions containing exec, which are kind of screwy anyway).
I have no opinion of this, locals() has always seemed like a crazy
part of the language to me and I never use it. I'd be happy to see it
gone since it makes compiling a lot easier.
Paul Rubin wrote:
al***@mac.com (Alex Martelli) writes:
I have no opinion of this, locals() has always seemed like a crazy
part of the language to me and I never use it. I'd be happy to see it
gone since it makes compiling a lot easier.
I think of that, from a compiler perspective, as one of the features
that, if used, means you have to switch to a more inefficient representation.
I encourage the hard-code optimizing compiler people to keep plugging
away on Python. It's a convenient way to program, but the implementations
are slower than they should be a decade into the language's life cycle.
John Nagle
Neal Becker <nd*******@gmail.comwrites:
One thing I sometimes miss, which is common in some other languages (c++),
is idea of block scope. It would be useful to have variables that did not
outlive their block, primarily to avoid name clashes. This also leads to
more readable code.
I have on occassion used lambda as a poor-man's let, but only if I needed to
avoid multiple evaluation:
res = (lambda x=blah(...), y=blahz(...): f(x*y,x+y))()
I'm sure most people would debate it's more readable, but it's IMO superior to
cleaning up manually with ``del``. I sometimes also find it useful to avoid
cluttering up the interactive shell.
'as
On Apr 7, 4:48 am, James Stroud <jstr...@mbi.ucla.eduwrote:
Neal Becker wrote:
One thing I sometimes miss, which is common in some other languages (c++),
is idea of block scope. It would be useful to have variables that did not
outlive their block, primarily to avoid name clashes. This also leads to
more readable code. I wonder if this has been discussed?
Probably, with good code, block scope would be overkill, except that I
would welcome list comprehensions to have a new scope:
pyi
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.NameError'>: name 'i' is not defined
py[i for i in xrange(4)]
[0, 1, 2, 3]
pyi # hoping for NameError
3
Yep, i think that we need consistent scope rules for
listexps and genexps. Isn't it coming in 3.0?
If it is, then maybe it will be back-ported to
Python 2.6.
In Python 2.5 we have the following:
>>[k for k in (j for j in range(5))]
[0, 1, 2, 3, 4]
>>k
4
>>j
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'j' is not defined
>>>
- Paddy.
Alex Martelli schrieb:
Paul Rubin <http://ph****@NOSPAM.invalidwrote:
>al***@mac.com (Alex Martelli) writes:
exec?
option 1: that just runs the compiler a bit later ...
Besides exec, there's also locals(), i.e. locals['x'] = 5 can shadow a variable. Any bad results are probably deserved ;)
>>>locals['x']=5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object does not support item
assignment
I suspect you want to index the results of calling locals(), rather than
the builtin function itself. However:
>>>def f():
... locals()['x'] = 5
... return x
...
>>>f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
NameError: global name 'x' is not defined
No "shadowing", as you see: the compiler knows that x is NOT local,
because it's not assigned to (the indexing of locals() does not count:
the compiler's not expected to detect that), so it's going to look it up
as a global variable (and not find it in this case).
Even assignments to real local variable names in the locals() result do
normally not result in the variable having a new value.
I think that ideally there should be a runtime error when assigning an
item of locals() with a key that's not a local variable name (possibly
excepting functions containing exec, which are kind of screwy anyway).
I would make the locals() result completely independent from the frame,
and document that it is read only.
(though, this needs some other way for trace functions to interact with
the frame's local variables.)
Georg
Paul Rubin a écrit :
al***@mac.com (Alex Martelli) writes:
>>>>>locals['x']=5
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'builtin_function_or_method' object does not support item assignment
Whoops, yeah, meant "locals()['x'] = 5".
>>I think that ideally there should be a runtime error when assigning an item of locals() with a key that's not a local variable name (possibly excepting functions containing exec, which are kind of screwy anyway).
I have no opinion of this, locals() has always seemed like a crazy
part of the language to me and I never use it. I'd be happy to see it
gone since it makes compiling a lot easier.
I personally find locals() handy in few cases, like
def output():
foo = 42
bar = baaz()
quux = blah(foo, bar)
return "the %(bar)s is %(foo)d and the %(quux)s shines" % locals()
or:
class Foo(object):
@apply
def bar():
def fget(self):
return self._quux / 42
def fset(self, value):
self._quux = value * 42
return property(**locals())
I'd be very unhappy to see it gone... This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: mike420 |
last post by:
I think everyone who used Python will agree that its syntax is
the best thing going for it. It is very readable and easy
for everyone to learn. But, Python does not a have very good
macro...
|
by: Minti |
last post by:
I was reading some text and I came across the following snippet
switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
|
by: G Patel |
last post by:
I've seen some code with extern modifiers in front of variables
declared inside blocks. Are these purely definitions (no definition)
or are they definitions with static duration but external...
|
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...
|
by: Bill Priess |
last post by:
Hey gang,
Ok, I'm stumped on this one... I am using the using statement to wrap a
SqlDataAdapter that I am using to fill a DataTable. Now, what I need to know
is, just how much block-scope...
|
by: Anoj |
last post by:
Hi All,
As you all know in vb.net we can declare block level
variables. Like :
Dim I As Integer
For I = 1 To 3
Dim N As Long
' N has block scope in VB.NET
N = N + I
Next
|
by: |
last post by:
Is it possible to define a variable in a block in order to make
it invisible outside that block? For example, in C I can write
{
int a
....
}
then a will only be available inside the curley...
|
by: Dieter |
last post by:
Hi.
In the snippet of code below, I'm trying to understand why when the
struct dirent ** namelist
is declared with "file" scope, I don't have a problem freeing the
allocated memory. But...
|
by: shilpa |
last post by:
Hi,
I just wanted to know whether we can access global variable within a
local block , where both variables are having same name.
For ex:
int temp=5 ;
{
int temp=10;
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
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,...
| |