473,804 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

block scope?

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?

Apr 6 '07
24 2675
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
Apr 8 '07 #21
Neal Becker <nd*******@gmai l.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
Apr 8 '07 #22
On Apr 7, 4:48 am, James Stroud <jstr...@mbi.uc la.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.Nam eError'>: 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 "<interacti ve input>", line 1, in <module>
NameError: name 'j' is not defined
>>>
- Paddy.

Apr 8 '07 #23
Alex Martelli schrieb:
Paul Rubin <http://ph****@NOSPAM.i nvalidwrote:
>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_functi on_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

Apr 8 '07 #24
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_functi on_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(**loca ls())
I'd be very unhappy to see it gone...
Apr 10 '07 #25

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

Similar topics

699
34287
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 capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
18
3466
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; }
12
2730
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 linkage? Not much on this in the FAQ or tutorials.
7
7720
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
2715
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 applies to objects created in the using scope. For example: <code> static DataTable getTable()
2
3606
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
11
1332
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 brackets
165
6931
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 when the struct is declared in main (block scope) it will segfault when passing namelist to freeFileNames().
4
2371
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;
0
9594
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10096
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
9174
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
7638
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
6866
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
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4311
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

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.