473,321 Members | 1,669 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

Unbinding multiple variables

Hi!

Is there a way to automate the unbinding of multiple variables? Say I
have a list of the names of all variables in the current scope via
dir(). Is there a command using del or something like that that will
iterate the list and unbind each of the variables?

Thanks much! (If anyone posts an answer, if you could also cc your
reply to my email ai******@yahoo.com, would be much obliged. Thanks
again!)

Best,
-Johnny
www.johnny-lin.com

Jul 18 '05 #1
10 1976
On 20 Jan 2005 19:24:43 -0800, Johnny Lin <ai******@yahoo.com> wrote:
Hi!

Is there a way to automate the unbinding of multiple variables? Say I
have a list of the names of all variables in the current scope via
dir(). Is there a command using del or something like that that will
iterate the list and unbind each of the variables?

Thanks much! (If anyone posts an answer, if you could also cc your
reply to my email ai******@yahoo.com, would be much obliged. Thanks
again!)


My immediate reaction is "You never want to do that"

If you're doing something along these lines:

#some code
#create lots of variables
#do stuff with those variables
# <want to delete variables here
#more code

Try converting it to this idiom:

def someFunction(someinput)
#create lots of variables
#do stuff with those variables
return output

#some code
output = someFunction(input)
#more code

Regards,
Stephen Thorne.
Jul 18 '05 #2
>>>>> "Johnny" == Johnny Lin <ai******@yahoo.com> writes:

Johnny> Hi! Is there a way to automate the unbinding of multiple
Johnny> variables? Say I have a list of the names of all
Johnny> variables in the current scope via dir(). Is there a
Johnny> command using del or something like that that will iterate
Johnny> the list and unbind each of the variables?
Hi Johnny

I assume you are the one and only Johnny Lin at the U of C, no?

John-Hunters-Computer:~> python
Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
x = 1
y = 2
locals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', 'y': 2, '__doc__': None, 'x': 1} print x,y 1 2 del locals()['x']
print x,y Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined locals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__':
'__main__', 'y': 2, '__doc__': None}

Jul 18 '05 #3

Johnny Lin wrote:
Hi!

Is there a way to automate the unbinding of multiple variables? Say I have a list of the names of all variables in the current scope via
dir(). Is there a command using del or something like that that will
iterate the list and unbind each of the variables?

Yes. It's called "return".

Jul 18 '05 #4
John Hunter wrote:
del locals()['x']

The locals() dictionary will only modify values in a module's top-level
code (i.e. when the expression "locals() is globals()" is true).
Jul 18 '05 #5
thanks everyone for the replies!

John Hunter, yep, this is Johnny Lin in geosci :).

re using return: the problem i have is somewhere in my code there's a
memory leak. i realize return is supposed to unbind all the local
variables, but since the memory leak is happening despite return, i
thought it might help me track down the leak if i unbound everything
explicitly that i had defined in local scope before i returned. or if
anyone has recomm. on plugging leaks, would be thankful for any
pointers there too.

my understanding about locals() from the nutshell book was that i
should treat that dictionary as read-only. is it safe to use it to
delete entries?

thanks again!

Jul 18 '05 #6
Johnny Lin wrote:
my understanding about locals() from the nutshell book was that i
should treat that dictionary as read-only. is it safe to use it to
delete entries?


No it's not:

py> def f():
.... x = 1
.... del locals()['x']
.... print x
....
py> f()
1
py> def f():
.... x = 1
.... del x
.... print x
....
py> f()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 4, in f
UnboundLocalError: local variable 'x' referenced before assignment

Steve
Jul 18 '05 #7
Johnny Lin <ai******@yahoo.com> wrote:
...
my understanding about locals() from the nutshell book was that i
should treat that dictionary as read-only. is it safe to use it to
delete entries?


Speaking as the Nutshell author: it's "safe", it just doesn't DO
anything. I _hoped_ locals() would become a dictionary-proxy giving at
least some *warning* about futile attempts to modify things through it,
on the basis of "errors shouldn't pass silently", but it just didn't
happen (yet). Nevertheless, any modifications to locals() are utterly
futile (within a function).

Unfortunately, I believe the only way to "delete locals" automatically
as you desire is through exec statements (which will inevitably turn off
the normal optimizations and make the whole function unbearably slow).
I also suspect this won't help you one bit in tracking down your leaks.
I would rather suggest you look into module gc...
Alex

Jul 18 '05 #8
Alex Martelli wrote:
Nevertheless, any modifications to locals() are utterly
futile (within a function).


Evil hack that makes modifications to locals() not quite as futile:

py> import sys
py> import ctypes
py> def f():
.... x = 1
.... locals()['x'] = 2
.... ctypes.pythonapi.PyFrame_LocalsToFast(
.... ctypes.py_object(sys._getframe()), 0)
.... return x
....
py> f()
2

Warning! NEVER do this! ;)

(Also note that you can't del or add variables in this manner -- only
modify them.)

Steve
Jul 18 '05 #9
On 21 Jan 2005 11:13:20 -0800, "Johnny Lin" <ai******@yahoo.com> wrote:
thanks everyone for the replies!

John Hunter, yep, this is Johnny Lin in geosci :).

re using return: the problem i have is somewhere in my code there's a
memory leak. i realize return is supposed to unbind all the local
variables, but since the memory leak is happening despite return, i
thought it might help me track down the leak if i unbound everything
explicitly that i had defined in local scope before i returned. or if
anyone has recomm. on plugging leaks, would be thankful for any
pointers there too.
It helps to clue people into what your real goal is ;-) (Your initial post
said nothing about memory leaks).

Step 1: How do you know you have a memory leak? Python retains some memory
in internal free pools rather than returning it to the OS, so you might not
have a memory leak at all, in the true sense.

If you are having a real memory leak, look first at any C extensions you've
written yourself, then at other's alpha/beta stuff you may be using. Core CPython
is probably the last place to look ;-)

If you are creating reference loops, I think some may be uncollectable.

I'm not sure how you are detecting "memory leaks," but whatever the method,
if you can write a test harness that will create a zillion of each suspect
thing and delete them in turn, and print out your detection data -- even if
you have to run separate processes to do it, that might narrow down your search.
E.g., if you write a little test.py that takes a command line argument to choose
which object to create zillions of, and print out leak evidence, then you could
run that systematically via popen etc. Or just run test.py by hand if you don't
have that many suspects (hopefully the case ;-)

my understanding about locals() from the nutshell book was that i
should treat that dictionary as read-only. is it safe to use it to
delete entries?

Well, it's not read-only, but it doesn't write through to the actual locals.
Think of it as a temp dict object with copies of the local name:value bindings,
but changing anything in it only changes the temp dict object in the usual way. UIAM ;-)

(OTOH, deletions of actual local bindings do seem to propagate back into a previously
bound value of locals on exit, and a new call to locals() seems to return the same identical
object as before, so I'm not sure I believe the <type 'dict'>, unless it has a special slot
and it is automatically updated at exit. But a local bare name assignment or deletion doesn't
immediately propagate. But it does on exit. So the <type 'dict'> returned by locals() has
a special relationship to the function it reflects, if it is otherwise a normal dict:
def foo(x): ... d = locals()
... print '1:',id(d), type(d), d
... del x
... print '2:',id(d), type(d), d
... del d['x']
... print '3:',id(d), type(d), d
... y = 123
... print '4:',id(d), type(d), d
... d['z'] = 'zee'
... print '5:',id(d), type(d), d
... return d, locals()
... dret, endinglocals = foo('arg passed to foo') 1: 49234780 <type 'dict'> {'x': 'arg passed to foo'}
2: 49234780 <type 'dict'> {'x': 'arg passed to foo'}
3: 49234780 <type 'dict'> {}
4: 49234780 <type 'dict'> {}
5: 49234780 <type 'dict'> {'z': 'zee'} dret {'y': 123, 'z': 'zee', 'd': {...}} endinglocals {'y': 123, 'z': 'zee', 'd': {...}} dret is endinglocals True dret['d'] is dret

True
(the {...} is an indication of the recursive reference)

Note that at 2: the del x was not reflected, nor did the y = 123 show at 4:
But the d['z'] showed up immediately, as you might expect ... but d['z'] also
in that last returned locals(), which you might not expect, since there was
no assignment to bare z. But they are apparently the same dict object, so you
would expect it. So maybe there is some kind of finalization at exit like closure
building. Anyway, d = dict(locals()) would probably behave differently, but I'm
going to leave to someone else ;-)

Regards,
Bengt Richter
Jul 18 '05 #10
thanks again for all the help! especially the advice on ideas of
tracking down the memory leak :). (sorry for not mentioning it
earlier...i had thought deleting everything might be a quick and dirty
way short-term fix. :P)

best,
-Johnny

Jul 18 '05 #11

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

Similar topics

13
by: jing_li | last post by:
Hi, you all, I am a newbee for php and I need your help. One of my coworker and I are both developing a webpage for our project using php. We have a copy of the same files in different location...
0
by: Richard Spooner | last post by:
Chaps, I've written a piece of python code below that when called with a line such as x = getdata(9999), listens on that port for data I'm sending it and puts the data in a list. If I delete x...
1
by: DrewM | last post by:
I'm still thinking about session variables :-) Does anyone know the detail of how session variables are actually stored? The question I'm trying to answer is: Is it more efficient to store and...
11
by: Ohaya | last post by:
Hi, I'm trying to understand a situation where ASP seems to be "blocking" of "queuing" requests. This is on a Win2K Advanced Server, with IIS5. I've seen some posts (e.g.,...
9
by: lbj137 | last post by:
I have two files: A.c and B.c. In both files I define a global variable, int xxxx; When I compile with a green hills compiler (and also i think with a GNU compiler) I get no errors or warnings....
3
by: Carl Johansen | last post by:
I have a big ASP website (used by several thousand car dealers) that is a collection of lots of small and medium-sized applications. Now I want to start adding ASP.NET applications to it. I have...
6
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing...
9
by: Bob Day | last post by:
VS 2003, vb.net , sql msde... I have an application with multiple threads running. Its a telephony application where each thread represents a telephone line. For code that would be the same...
6
by: Gaijinco | last post by:
I'm having a weird error compiling a multiple file project: I have three files: tortuga.h where I have declared 5 global variables and prototypes for some functions. tortuga.cpp where I...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.