how to give focus to another application

2008-06-25 Thread massimo s.
Hi,

I would like to know if 1)there is a Python way to tell under which
terminal process a Python command-line application is running 2)there
is a Python way to tell the OS to give focus to another window.

Solutions for Windows, Linux and OS X are welcome, even if OS-specific
(of course general solutions are better, but I can kludge  check the
platform).

Thanks,
M.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is anyone happy with csv module?

2007-12-12 Thread massimo s.
Thanks to everyone in this thread. As always on this newsgroup, I
learned very much.

I'm also quite embarrassed of my ignorance. Only excuse I have is that
I learned programming and Python by myself, with no formal (or
informal) education in programming. So, I am often clumsy.

On Dec 12, 1:29 am, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
  I'm just trying to use the CSV module
  and I mostly can get it working. I just think its interface is much
  less than perfect. I'd like something I can, say, give a whole
  dictionary in input and obtain a CSV file in output, with each key of
  the dictionary being a column in the CSV file. Or a row, if I prefer.
  Something like:

  dict={'First':[1,2,3,4],'Second':[10,20,30,40],'Third':
  [100,200,300,400]}

 ot
 you're shadowing the builtin 'dict' type here, which is usalluy a bad idea
 /ot

Yes, this I know, I just overlooked it when improvising the example.

  f=open('test.csv','w')
  try:
  csv_write_dict(f,dict,keys='columns',delimiter=',')
  finally:
  f.close()

  and obtaining:
  First,Second,Third
  1,10,100
  2,20,200
  3,30,300
  4,40,400

 Doing the needed transformation (from a column:rows dict to the required
 format) is close to trivial. So you could actually implement it
 yourself, monkeypatch the relevant csv class, and submit a patch to the
 maintainer of the module.

 FWIW, I never had data structured that way to pass to the csv module -
 to be true, I think I never had a case where tabular data were
 structured by columns.

FWIW, I never had data structured by row. At most, I had data
structured by *both* row and column.
Vive la différence. :)

  Doing the same thing with the current csv module is much more
  cumbersome: see this example 
  fromhttp://www.oreillynet.com/onlamp/blog/2007/08/pymotw_csv.html

  f = open(sys.argv[1], 'wt')
  try:
  fieldnames = ('Title 1', 'Title 2', 'Title 3')
  writer = csv.DictWriter(f, fieldnames=fieldnames)
  headers = {}
  for n in fieldnames:
  headers[n] = n
  writer.writerow(headers)

 # same as the 4 lines above
 writer.writerow(dict((item, item) for item in fieldnames))

  for i in range(10):
  writer.writerow({ 'Title 1':i+1,
'Title 2':chr(ord('a') + i),
'Title 3':'08/%02d/07' % (i+1),
})

 This one looks so totally unrealistic to me - I mean, wrt/ to real-life
 use cases - that I won't even propose a rewrite.

I can frankly think of a lot of cases where this kind of pattern makes
a lot of sense, but in that case it was just for the example purpose.

  finally:
  f.close()

 A bit of a WTF, indeed. But most of the problem is with this example
 code, not with the csv module (apologies to whoever wrote this snippet).

Thank you. Let me say it was the *best* tutorial I found online -much
better than official docs, IMHO. Maybe it is the reason I felt dizzy
when trying to use csv.

 FWIW, here's a function what you want, at least for your first use case:

 def csv_write_cols(writer, data):
  keys = data.keys()
  writer.writerow(dict(zip(keys,keys)))
  for row in zip(*data.values()):
  writer.writerow(dict(zip(keys, row)))

Thanks!

 Now you do what you want, but as far as I'm concerned, I wouldn't start
 a total rewrite of an otherwise working (and non-trivial) module just
 for a trivial four (4) lines function.

I fully agree. I would like to add a bit of other trivial functions,
but this is a *clear* example of csv writer usage, which I did not
find.

 Also, have you considered that your columns may as well be rows, ie:

 First,  1,   2,   3,   4
 Second, 10,  20,  30,  40
 Third,  100, 200, 300, 400

Doesn't play well with my data for a number of reasons. For example,
columns VS rows limits on spreadsheets.

  Another unrelated quirk I've found is that iterating the rows read by
  a csv reader object seems to erase the rows themselves; I have to copy
  them in another list to use them.

 It's not a quirk, Sir, it's a feature !-)

 The csv reader object - like file objects and a couple others - are
 iterators. In this case, it means the csv reader is smart enough to not
 read the whole file into memory - which is not necessarily what you
 want, specially for huge files - but iterating over lines as long as you
 ask for them.

 Note that if you need the whole thing in memory, copying the rows in a
 list is a no-brainer:
rows = list(reader)

I know. I just thought odd it was undocumented. But it's self-evident
now that I missed how iterators work.
I'll look into the issue.

  Probably it's me not being a professional programmer,

 ot
 Not sure the professional status is key here - I mean, it just mean
 you're getting paid for it, but says nothing about your competences.
 /ot

In the meaning that I have no formal training in it and the like.

  so I don't
  understand that somehow the csv module *has* to be done this way. If
  it's so, I'd like to 

Re: Is anyone happy with csv module?

2007-12-12 Thread massimo s.
On Dec 12, 2:58 pm, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-12-11, massimo s. [EMAIL PROTECTED] wrote:

  Hi,

  I'm struggling to use the python in-built csv module, and I
  must say I'm less than satisfied. Apart from being rather
  poorly documented, I find it especially cumbersome to use, and
  also rather limited. What I dislike more is that it seems
  working by *rows* instead than by *columns*.

 It is very *thoroughly* documented, which is a style that won't
 suit every purpose.
  So I have some questions:
  1) Is there a good tutorial, example collection etc. on the csv
  module that I'm missing?

 Just skip to 9.1.5 Examples, and you'll be on your way.

If by thoroughly you mean it actually describes technically what it
is and does but not how to really do things, yes, it is thoroughly
documented.
The examples section is a joke. It gives good examples for the
simplest usage cases (good), then it almost immediately digs into
details like the Unicode stuff, leaving aside the rest. DictWriter and
DictReader are absent from the examples. And also the Sniffer.

And, as a sidenote, why putting something useful like the unicode
decoder-encoders in the example section instead of inserting them
directly in the library?

I don't want to be mean with the author of csv and its docs. I now
understand there are excellent reasons for csv to be done the way it
is, and it's only my fault if I didn't see that before. I also know
first hand that documenting code is hard and boring stuff. Kudos to
anyone doing that, but in the Example section there is surely room for
improvement. It's probably OK for people doing things row-by-row and
that already know perfectly their way in and out all that, but if this
thread teaches us something, is that the same thing can be used for
vastly different purposes.

I will try to submit a patch to the documentation based on examples
coming from here and what I will learn by digging into csv.

  3) In case anyone else is as unhappy as me, and no tutorial
  etc. enlighten us, and no alternative is present, anyone is
  interested in an alternative csv module? I'd like to write one
  if it is the case.

 I was intimidated by it at first, implemented my own reader
 (mostly as a fun parsing exercise), used that for a while, and
 then threw it out.

 I advise you to spend time staring at the examples, and use the
 simplest example the suits your needs. Also search this archives
 of this group for examples.

OK, thanks!

As for people advicing xlrd/xlrwt: thanks for the useful tip, I didn't
know about it and looks cool, but in this case no way I'm throwing
another dependency to the poor users of my software. Csv module was
good because was built-in.

m.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is anyone happy with csv module?

2007-12-11 Thread massimo s.
Hi,

I'm struggling to use the python in-built csv module, and I must say
I'm less than satisfied. Apart from being rather poorly documented, I
find it especially cumbersome to use, and also rather limited. What I
dislike more is that it seems working by *rows* instead than by
*columns*.

So I have some questions:
1) Is there a good tutorial, example collection etc. on the csv module
that I'm missing?
2) Is there an alternative csv read/write module?
3) In case anyone else is as unhappy as me, and no tutorial etc.
enlighten us, and no alternative is present, anyone is interested in
an alternative csv module? I'd like to write one if it is the case.


Thanks,
Massimo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is anyone happy with csv module?

2007-12-11 Thread massimo s.
On 11 Dic, 22:37, John Machin [EMAIL PROTECTED] wrote:
 On Dec 12, 6:14 am, massimo s. [EMAIL PROTECTED] wrote:

  Hi,

  I'm struggling to use the python in-built csv module, and I must say
  I'm less than satisfied. Apart from being rather poorly documented,

 Patches are welcome :-)

Yes, but maybe I was in the wrong. I'm not so bold to submit patches
to an official Python module without asking.
*I* feel troubles, but maybe it's just me being dense.


  I
  find it especially cumbersome to use,

 Can you be more specific? What are you trying to do with it?

See examples in previous post.

  and also rather limited.

 What extra facilities do you think there should be?

Ability to work by columns together with rows and maybe some random
access facilities would be nice. A more user-friendly interface too.

 A CSV file is organised such that each line of the file represents a
 row, and the nth field in the line relates to the nth column, so it's
 natural for any CSV reader/writer to work by rows.

Yes, but it's natural for a spreadsheet-like thing to have organized
columns of data, often.
Often I want those columns to be read into lists, or to write lists
into columns. The actual csv doesn't allow this naturally. Especially
writing is a bit painful.

I just wanted to know if there was something allowing this with a
simple command, that I missed, or if just there wasn't.

 Accessing the data by columns *instead* of by rows would definitely
 not be appreciated by people who are using the csv module to read
 millions of lines of data.

I don't want anything *instead*, I would like *additional*. :)
(Btw: who is using csv to read 10**6 lines of data?)

  So I have some questions:
  1) Is there a good tutorial, example collection etc. on the csv module
  that I'm missing?

 AFAIK, no.

Ok. I found something on google but nothing answering to my questions.

  2) Is there an alternative csv read/write module?

 Is your googler broken?

Apparently, yes. I googled but apart from some hint here and there of
someone thinking about writing a pure Python csv module, I found
nothing. I'm usually decent at googling, but maybe my skills are
wearing out.

  3) In case anyone else is as unhappy as me, and no tutorial etc.
  enlighten us, and no alternative is present, anyone is interested in
  an alternative csv module?

 -1

Ok. :)

  I'd like to write one if it is the case.

 In what language?

Python.

m.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is anyone happy with csv module?

2007-12-11 Thread massimo s.
On 11 Dic, 20:24, Guilherme Polo [EMAIL PROTECTED] wrote:


 Post your actual problem so you can get more accurate help.

Hi Guilhermo,
I have not an actual problem. I'm just trying to use the CSV module
and I mostly can get it working. I just think its interface is much
less than perfect. I'd like something I can, say, give a whole
dictionary in input and obtain a CSV file in output, with each key of
the dictionary being a column in the CSV file. Or a row, if I prefer.
Something like:

dict={'First':[1,2,3,4],'Second':[10,20,30,40],'Third':
[100,200,300,400]}
f=open('test.csv','w')
try:
csv_write_dict(f,dict,keys='columns',delimiter=',')
finally:
f.close()

and obtaining:
First,Second,Third
1,10,100
2,20,200
3,30,300
4,40,400

Doing the same thing with the current csv module is much more
cumbersome: see this example from 
http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_csv.html

f = open(sys.argv[1], 'wt')
try:
fieldnames = ('Title 1', 'Title 2', 'Title 3')
writer = csv.DictWriter(f, fieldnames=fieldnames)
headers = {}
for n in fieldnames:
headers[n] = n
writer.writerow(headers)
for i in range(10):
writer.writerow({ 'Title 1':i+1,
  'Title 2':chr(ord('a') + i),
  'Title 3':'08/%02d/07' % (i+1),
  })
finally:
f.close()


Another unrelated quirk I've found is that iterating the rows read by
a csv reader object seems to erase the rows themselves; I have to copy
them in another list to use them.

Probably it's me not being a professional programmer, so I don't
understand that somehow the csv module *has* to be done this way. If
it's so, I'd like to know about it so I can learn something.

 For the questions you placed: google for them, look at python pep 305

I googled (before and after sending this post). I found mentions of
people writing a purely Python csv module but I didn't find their
code. As for pep 305, thanks, but it seems just to be a description of
the actual csv module (useful,anyway).

m.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is anyone happy with csv module?

2007-12-11 Thread massimo s.
On 12 Dic, 00:08, Gabriel Genellina [EMAIL PROTECTED] wrote:
 Note that all the above (as any operation involving a whole *column*)
 requires reading the whole file in memory. Working by rows, on the other
 hand, only requires holding ONE row at a time. For big files this is
 significant.

 An example of writing data given in columns:

  id = [1,2,3,4]
  name = ['Moe','Larry','Curly','Shemp']
  hair = ['black','red',None,'black']
  writer = csv.writer(...)
  writer.writerows(itertools.izip(id, name, hair))

 I think your problem is not with the csv module, but lack of familiarity
 with the Python language itself and how to use it efficiently.

Maybe. As stated at the beginning, I am not a professional programmer.
I am a scientist using Python at work. It's years I use it and I love
it, but I surely miss many nuances.

For example, I never ever looked into itertools. I am also not so
familiar with iterators. Itertools seem fantastic, and I'll definitely
look into them, however I can't but feel it's a bit strange that
someone wanting a quick csv parsing/writing has to dig into those
apparently unrelated stuff.

  (Btw: who is using csv to read 10**6 lines of data?)

 Me, and many others AFAIK. 1M lines is not so big, btw.

It's clear that I am thinking to completely different usages for CSV
than what most people in this thread. I use csv to export and import
numerical data columns to and from spreadsheets. That's why I found 1M
lines a lot. Didn't know csv had other uses, now I see more clearly
why the module is as it is.

Thanks for your tips, I've learned quite a lot.

m.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
Before all, I'm not a professional programmer but just a biophysics
ph.d. student, so if something makes you scream of horror, please
forgive me...

Ok, this is not straightforward at all.
I am working on an application that uses plugins. Plugins are coded as
small classes that become inherited by a main class ( a cmd.Cmd
actually) in the following way:

(see also this thread:
 
http://groups.google.it/group/comp.lang.python/browse_thread/thread/4d6da027bb9249bd/0f95c60add4ef5ad
)

---
... def do_this(self, arg):
... print THIS, arg
...
 class Bar:

... def do_that(self, arg):
... print THAT, arg
...
 plugins = [Foo, Bar]
 def make_command_class(*bases):

... return type(cmd.Cmd)(MyCli, bases + (cmd.Cmd,), {})
...
 cmd = make_command_class(*plugins)()
 cmd.cmdloop()

(Cmd) help

Undocumented commands:
==
help  that  this

(Cmd) that one
THAT one
(Cmd)

---

And it works. Now I'm trying to do the same trick for another base
class, this time a WxPython frame.
Also in this case, plugging seem to work, but with an important
difference.

In the command line plugin API, I define a _plug_init() method that is
called in the main class __init__ . This for adding plugin-specific
initializiations.
That's what I do in the command line __init__:

   for plugin_name in self.config['plugins']:
try:
plugin=__import__(plugin_name)
try:
print type(self)
eval('plugin.'+plugin_name
+'Commands._plug_init(self)')
except AttributeError:
pass
except ImportError:
pass

And it works flawlessly.
Problem is, the exact same code when done using the wxFrame as the
baseclass, doesn't work:

#make sure we execute _plug_init() for every command line
plugin we import
for plugin_name in config['plugins']:
try:
plugin=__import__(plugin_name)
try:
print type(self)
eval('plugin.'+plugin_name
+'Gui._plug_init(self)')
pass
except AttributeError:
pass
except ImportError:
pass

with the following error:

Traceback (most recent call last):
  File hooke.py, line 801, in module
main()
  File hooke.py, line 787, in main
main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke
'+__version__))
  File hooke.py, line 308, in __init__
eval('plugin.'+plugin_name+'Gui._plug_init(self)')
  File string, line 1, in module
TypeError: unbound method _plug_init() must be called with
dummyguiplugGui instance as first argument (got MainWindowPlugged
instance instead)

The problem seems to be that if I call type(self) before doing the
eval('plugin... ) line:
- in the working case, I get type type 'instance'
- in the not working case, I get class '__main__.MainWindowPlugged'

At this point, it seems too much a deep object-oriented hell to be
able to dig it myself. Would you help me getting some cue on the
problem?

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
 At this point, it seems too much a deep object-oriented hell to be
 able to dig it myself. Would you help me getting some cue on the
 problem?

Update. Now I know that:
- every sane Python class should return type 'instance' after
type(self)
- when disabling the multiple-inheritance-hack, the situation comes
back to normal

What happens that makes the wxFrame class different from the cmd.Cmd
class?

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 13:45, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 massimo s. a écrit :

  At this point, it seems too much a deep object-oriented hell to be
  able to dig it myself. Would you help me getting some cue on the
  problem?

  Update. Now I know that:
  - every sane Python class should return type 'instance' after
  type(self)

 Certainly not, unless you're using a pretty old Python version.
 'instance' type means old-style classes - the legacy Python object
 model, replaced some years ago with a *much* better one ('new-style'
 classes). IIRC, this (now dying) legacy object model should disappear
 with Py3K.

Oops. That's probably the problem.

I always followed the class syntax found in Section 9 of the tutorial,
and Python code I've seen uses the same syntax.

Where can I find the syntax of new-style classes?

  - when disabling the multiple-inheritance-hack, the situation comes
  back to normal

 I may be wrong here - I don't use old-style classes, and I avoid
 multiple inheritance whenever I can - but I think this may has to do
 with mixing old-style and new-style classes.

Probably it is.

 side-note
 wrt/ this snippet:

I'll try it ASAP. About logging the error, yes, I figured it out how
to do it some time ago but didn't have time (sigh).

Thanks,
m.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 13:45, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 side-note
 wrt/ this snippet:

 for plugin_name in self.config['plugins']:
  try:
  plugin=__import__(plugin_name)
  try:
  print type(self)
  eval('plugin.'+plugin_name+'Commands._plug_init(self)')
  except AttributeError:
  pass
  except ImportError:
  pass

 You may want to try this instead:

 for plugin_name in self.config['plugins']:
  try:
  plugin=__import__(plugin_name)
  except ImportError:
  # eventually do something like logging the error ?
  continue
  try:
  cmdplug = getattr(plugin, plugin_name+'Commands')
  cmdplug._plug_init(self)
  except AttributeError:
  # eventually do something like logging the error ?
  continue

Tried, same error as before :(

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 13:45, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:

 wxFrame is obviously a new-style class.

I don't know if it's true, however. I tried that:

 class A(object):
... def __init__(self):
... print type(self)
...
 a=A()
class '__main__.A'

so in fact what I see has something to do with new style classes (if
subclassing 'object' is enough).

The new-style behaviour only appears when wxFrame is plugged with the
current hack.
That is:

- print type(self) in wxFrame alone returns type 'instance'
- print type(self) in the plugged (multiply inherited) wxFrame returns
 class '__main__.MainWindowPlugged'

So the problem is that I acquire a new style behaviour somewhere!

I tried to let the plugin class be a new style class (subclassing
'object': again, I can't find a simple reference about it, I tried to
read www.python.org/doc/newstyle.html links but they are far too much
theoretical for my knowledge) and nothing seems to change at all.

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 14:41, massimo s. [EMAIL PROTECTED] wrote:

 The new-style behaviour only appears when wxFrame is plugged with the
 current hack.
 That is:

 - print type(self) in wxFrame alone returns type 'instance'
 - print type(self) in the plugged (multiply inherited) wxFrame returns
  class '__main__.MainWindowPlugged'

 So the problem is that I acquire a new style behaviour somewhere!

Forget this one, it is wrong (Don't know how did I obtain it).
I rechecked and, yes, problem is that cmd.Cmd is old-style (and the
plugin hack works) while wxFrame is new style (and the plugin hack
works no more).

Again: using a new-style plugin class for multiple inheritance does
not work.
What can I do now?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 15:37, Peter Otten [EMAIL PROTECTED] wrote:
 massimo s. wrote:
  Again: using a new-style plugin class for multiple inheritance does
  not work.

 This statement is certainly too broad.

 [earlier]

  TypeError: unbound method _plug_init() must be called with
  dummyguiplugGui instance as first argument (got MainWindowPlugged
  instance instead)

 So it looks like you failed to make dummyguiplugGui a base class of
 MainWindowPlugged.

Right (Checked with dir() -dummyguiplugGui methods do not appear ).

  What can I do now?

 Post a self-contained example.

I'll try.

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
On 28 Giu, 15:37, Peter Otten [EMAIL PROTECTED] wrote:

 Post a self-contained example.

Now I'm even more confused. The self-contained example is below... and
it works, using only old-style declarations.

#!/usr/bin/env python

import wx
import cmd

global CLI_PLUGINS
global GUI_PLUGINS

class MyCmd(cmd.Cmd):


def do_hello(self,args):
print 'hello'

class PlugCmd:

def _plug_init(self):
print 'init plugcmd'

def do_wow(self,args):
print 'wow'

#--
class MyFrame(wx.Frame):

def __init__(self,parent,id,title):

ID_FRAME=-1
 
wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|
wx.NO_FULL_REPAINT_ON_RESIZE)

print dir(self)

for item in GUI_PLUGINS:
item._plug_init(self)

class PlugFrame:

 def _plug_init(self):
 print 'init plugframe'


CLI_PLUGINS=[PlugCmd]
GUI_PLUGINS=[PlugFrame]

def main():
app=wx.PySimpleApp()


def make_cli_class(*bases):
#return type(MainWindow)(MainWindowPlugged, bases +
(MainWindow,), {})
return type(MyCmd)(CliPlugged, bases + (MyCmd,), {})

def make_gui_class(*bases):
#return type(MainWindow)(MainWindowPlugged, bases +
(MainWindow,), {})
return type(MyFrame)(MainWindowPlugged, bases +
(MyFrame,), {})

my_cli=make_cli_class(*CLI_PLUGINS)()
main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Test'))
main_frame.Show()

#run one loop or the other when testing
#app.MainLoop()
my_cli.cmdloop()

main()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with hack using multiple inheritance for plugins

2007-06-28 Thread massimo s.
Uh, oh.

I think I found the bug, and it was a *really stupid bug*.
The list of GUI_PLUGINS was empty... so there was no plugin class that
was inherited.

I'm embarrassed to have wasted your time that way. However I learned a
lot about new-style classes and so on, so for me it was a learning
experience nonetheless.

Really sorry for wasting your time. I should use a debugger, I know. :
(

Thanks a lot for your patience,

M.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: of destructors, open files and garbage collection

2007-05-26 Thread massimo s.
 No, it removes the association between the name 'item' and the object it is
 currently bound to.  In CPython, removing the last such reference will
 cause the object to be gc'ed.  In other implementations, actual deletion
 may occur later.  You probably should close the files directly and arrange
 code so that you can do so before too many are open.

Thanks a lot, I'll follow that way.

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


of destructors, open files and garbage collection

2007-05-24 Thread massimo s.
Hi,

Python 2.4, Kubuntu 6.06. I'm no professional programmer (I am a ph.d.
student in biophysics) but I have a fair knowledge of Python.

I have a for loop that looks like the following :

for item in long_list:
   foo(item)

def foo(item):
   item.create_blah() #--this creates item.blah; by doing that it
opens a file and leaves it open until blah.__del__() is called

Now, what I thought is that if I call

del(item)

it will delete item and also all objects created inside item. So I
thought that item.blah.__del__() would have been called and files
closed.
Question 1:
This is not the case. I have to call del(item.blah), otherwise files
are kept open and the for loops end with a Too many open files
error. Why isn't __del__() called on objects belonging to a parent
object? Is it OK?

So I thought:
oh, ok, let's put del(self.blah) in item.__del__()
Question 2:
This doesn't work either. Why?

Thanks a lot,
M.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: of destructors, open files and garbage collection

2007-05-24 Thread massimo s.
 It will delete the *name* `item`.  It does nothing to the object that was
 bound to that name.  If the name was the only reference to that object, it
 may be garbage collected sooner or later.  Read the documentation for the
 `__del__()` method for more details and why implementing such a method
 increases the chance that the object *won't* be garbage collected!

 Relying on the `__del__()` method isn't a good idea because there are no
 really hard guaranties by the language if and when it will be called.

Ok, I gave a look at the docs and, in fact, relying on __del__ doesn't
look like a good idea.

Changing the code as to add an explicit method that closes dangling
filehandles is easy. It would be somehow nice because -since that
method would be added to a plugin API- it *forces* people writing
plugins to ensure a way to close their dangling files, and this may be
useful for a lot of future purposes. However I'd also like to track
references to my objects -this would help debugging a lot. How can I
do that?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: of destructors, open files and garbage collection

2007-05-24 Thread massimo s.
 Relying on the `__del__()` method isn't a good idea because there are no
 really hard guaranties by the language if and when it will be called.

Ok, I read the __del__() docs and I understand using it is not a good
idea.

I can easily add a close_files() method that forces all dangling files
to be closed. It would be useful in a number of other possible
situations. However, as rightly pointed out by the exhaustive answer
of Paul Moore, tracking references of my objects would be very useful.
How can I do that?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pep 3105: the end of print?

2007-02-15 Thread massimo s.
Isn't the very concept of major releases (1.x, 2.x, 3.x) that they
*can* be not backwards-compatible with previous releases?

m.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple inheritance of a dynamic list of classes?

2007-02-13 Thread massimo s.
On 13 Feb, 12:46, Peter Otten [EMAIL PROTECTED] wrote:
 Well, what problems ocurring with

 class A: pass
 class B: pass
 class C(A, B): pass

 could be avoided by writing

 class A: pass
 class B(A): pass
 class C(B): pass

 instead? Classes have to be designed for subclassing, so essentially you get
 two interfaces, one for subclasses and one for client code instead of just
 the latter. A more relevant mantra governing inheritance is Flat is better
 than nested.

I am truly getting lost. Are you saying that doing A--B(A)--C(B) is
better than C(A,B)? And isn't the former thing nested? Or are you
saying that C(A,B) is better than A,B(A),C(B)? And in both cases:why?

And why classes have to be designed for subclassing? I often do
classes that are not thought to be subclassed.

 If you use attributes starting with two underscores inside a method, Python
 transparently prepends them with the class name. This allows to you to use
 the same variable name in two base classes and reduces coupling:

Wow, I didn't know it. Thanks a lot.

 But if two classes with the same name use the private variable, the
 mechanism fails:

Of course.I'll remember it.

m.

-- 
http://mail.python.org/mailman/listinfo/python-list