The file executing

2007-07-02 Thread Benjamin
How does one get the path to the file currently executing (not the
cwd). Thank you

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


Re: The file executing

2007-07-03 Thread Benjamin
On Jul 2, 9:47 pm, Justin Ezequiel <[EMAIL PROTECTED]>
wrote:
> On Jul 3, 9:40 am, Benjamin <[EMAIL PROTECTED]> wrote:
>
> > How does one get the path to the file currently executing (not the
> > cwd). Thank you
>
> os.path.dirname(sys.argv[0])
The returns the file that was called first, but not the one currently
executing...

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


Re: The file executing

2007-07-06 Thread Benjamin
On Jul 3, 8:56 am, Sebastian Wiesner <[EMAIL PROTECTED]> wrote:
> [ Benjamin <[EMAIL PROTECTED]> ]
>
> > On Jul 2, 9:47 pm, Justin Ezequiel <[EMAIL PROTECTED]>
>
> > wrote:
> > > On Jul 3, 9:40 am, Benjamin <[EMAIL PROTECTED]> wrote:
> > > > How does one get the path to the file currently executing (not the
> > > > cwd). Thank you
>
> > > os.path.dirname(sys.argv[0])
>
> > The returns the file that was called first, but not the one currently
> > executing...
>
> Use __file__ instead of sys.argv[0]
So:
if __name__ == "main":
currentDir = os.path.dirname(sys.argv[0])
else:
currentDir = os.path.dirname(__file__)
>
> --
> Freedom is always the freedom of dissenters.
>   (Rosa Luxemburg)
>
>  signature.asc
> 1KDownload


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


Re: The file executing

2007-07-09 Thread Benjamin
On Jul 9, 6:42 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Fri, 06 Jul 2007 17:15:22 -0300, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> >> > > > How does one get the path to the file currently executing (not the
> >> > > > cwd). Thank you
> > So:
> > if __name__ == "main":
> > currentDir = os.path.dirname(sys.argv[0])
> > else:
> > currentDir = os.path.dirname(__file__)
>
> I think you meant to test for "__main__", but anyway, this should be  
Yes
> enough:
> currentDir = os.path.dirname(__file__)
> or perhaps os.path.dirname(os.path.abspath(__file__)). Try to determine  
> that early in your program because __file__ may contain a relative path  
> (and will give a wrong result after changing the current directory).
I do it right at the top of the first module. Thanks for the help.
>
> --
> Gabriel Genellina


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

wxPython, threads, and search engine

2007-07-17 Thread Benjamin
I'm writing a search engine in Python with wxPython as the GUI. I have
the actual searching preformed on a different thread from Gui thread.
It sends it's results through a Queue to the results ListCtrl which
adds a new item. This works fine or small searches, but when the
results number in the hundreds, the GUI is frozen for the duration of
the search. I suspect that so many search results are coming in that
the GUI thread is too busy updating lists to respond to events. I've
tried buffer the results so there's 20 results before they're sent to
the GUI thread and buffer them so the results are sent every .1
seconds. Nothing helps. Any advice would be great.

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


wxPython and threads

2007-07-17 Thread Benjamin
I'm writing a search engine in Python with wxPython as the GUI. I have
the actual searching preformed on a different thread from Gui thread.
It sends it's results through a Queue to the results ListCtrl which
adds a new item. This works fine or small searches, but when the
results number in the hundreds, the GUI is frozen for the duration of
the search. I suspect that so many search results are coming in that
the GUI thread is too busy updating lists to respond to events. I've
tried buffer the results so there's 20 results before they're sent to
the GUI thread and buffer them so the results are sent every .1
seconds. Nothing helps. Any advice would be great.

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


wxPython, searching, and threads

2007-07-18 Thread Benjamin
Hello! I am writing a search engine with wxPython as the GUI. As the
search thread returns items, it adds them to a Queue which is picked
up by the main GUI thread calling itself recursively with
wx.CallAfter. These are then added to a ListCtrl. This works fine for
small searches, but with larger and longer searchs the GUI is clogged
and won't respond. I suspect (I may be wrong) that there are so many
results being sent to the ListCtrl that the event loop doesn't have
time to respond to events. I've tried buffering the results before
sending them to the GIU, but that doesn't help at all. Please advise.

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


wxPython, searching, and threads

2007-07-18 Thread Benjamin
Hello! I am writing a search engine with wxPython as the GUI. As the
search thread returns items, it adds them to a Queue which is picked
up by the main GUI thread calling itself recursively with
wx.CallAfter. These are then added to a ListCtrl. This works fine for
small searches, but with larger and longer searchs the GUI is clogged
and won't respond. I suspect (I may be wrong) that there are so many
results being sent to the ListCtrl that the event loop doesn't have
time to respond to events. I've tried buffering the results before
sending them to the GIU, but that doesn't help at all. Please advise.

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


Re: Start

2007-05-19 Thread Benjamin
On May 19, 10:18 am, Nautilus <[EMAIL PROTECTED]> wrote:
> Can anybody halp me start using Python.

First you'll need to download Python. You can do that at http://www.python.org.
Then download and read the tutorial at http://python.org/doc/.

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


Re: Any python module for Traversing HTML files

2007-07-24 Thread Benjamin
On Jul 24, 12:12 pm, johnny <[EMAIL PROTECTED]> wrote:
> Any python module for navigating and selecting, parsing HTML files?

htmlparse

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


Re: wxPython - How to add sorting to a ListCtrl?

2007-07-24 Thread Benjamin
On Jul 24, 11:21 am, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have 3 columns in my list control, each with a different "type" of
> data (for example, one column has names, the other has dates, etc).
> Can anyone reference a tutorial for solving this issue? I've done my
> share of googling to no avail. I need the user to be able to click any
> of the column headers and sort the rows of data by that column in
> ascending or descending order.
There is a mixin for this at wx.lib.mixins.listctrl.ColumnSorterMixin.
To learn how to use it, take a look at the wxPython demo which comes
with the doc distribution. There's a good example in the ListCtrl
demo.
>
> Thanks for your time.


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


Re: Learning Jython?

2007-07-26 Thread Benjamin

Paul Rubin wrote:
> Matt Bitten <[EMAIL PROTECTED]> writes:
> > It looks like Jython is for me. That said, I have two questions:
> > (1) Am I thinking straight here? Or is there some other solution that
> > a knows-Python-but-not-Java programmer might use?
You could convert to the whole world to using the Grail (http://
grail.sourceforge.net), which can run Python applets, but Java applets
with Jython are probably the second best option. The java.awt.Applet
class isn't that bad. For simple applets, it's probably the only one
you'll need. After all, Jython makes Java classes look like Python.
Good Luck!
>
> You are thinking of embedding Jython in a web applet?  Probably not
> such a great idea, due to its size.
Ah, but Jython compiles Python to Java bytecode so browsers will run
it. However, it is true, that you'd have to include all of the
standard library modules you used.

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


Re: Tkinter -- Show Data in an Excel like Read-Only Grid

2007-07-28 Thread Benjamin
On Jul 27, 4:56 pm, beginner <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I am really new to Tk and Tkinter. I googled the web but it was not
> mentioned how to build a data grid with Tkinter.
>
> Basically, I want to show an excel like data grid with fixed column
> and row headers and sortable columns. But the grids can be read-only.
>
> Can anyone give some hint on implementing this?
If tkTable isn't what you're looking for, take a look at wxPython
(http://www.wxpython.org). It's a different widget set and bit of a
higher learning curve than Tkinter, but it has hundreds of widgets for
things like this (wx.Grid).
>
> Thanks,
> beginner


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


Icons for GUI development

2007-08-13 Thread Benjamin
I'm developing a mail client. Since GUI are usually improved with some
icons, I'm looking for some. Because I'm not a very gifted artist I'm
searching for a library of GPL or public domain icons. Any suggestions?

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


Re: Python question (PyNoob)

2007-08-19 Thread Benjamin
On Aug 19, 7:33 pm, Anonymous <[EMAIL PROTECTED]> wrote:
> I have exp with C/C++ (and a few other langs). I want to use Python to
> start doing the ff:
>
> 1). Data Munging (text processing) - instead of Perl
> 2). Automating my build process
> 3). (Possibly) some web data retrieval jobs
>
> Can anyone point me to resurces/possibly scripts that can get me up to
> speed (to do these 3 things) ASAP, without having to learn the basics of
> programming?

I think if you've chosen Python as a language to use for these things,
you could invest some time in learning the language. It is after all
very easy to learn and you just have to do it once and many of your
programming task will be taken care of.

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


Re: IDE for Python

2007-08-21 Thread Benjamin
On Aug 21, 5:00 am, Joel Andres Granados <[EMAIL PROTECTED]>
wrote:
> Hello list:
>
> I have tried various times to use an IDE for python put have always been
> disapointed.
> I haven't revisited the idea in about a year and was wondering what the
> python people
> use.
> I have also foundhttp://pida.co.uk/mainas a possible solution.  Anyone
> tried it yet?
>
> suggestions.
I like PyDev + Eclipse mostly because I develop Java, PHP, and C/C++,
so I like having a consistent interface between the languages.
Besides, the Eclipse updater makes updating and installing new
features really easy.
> Regards
> Joel Andres Granados
>
>  joel.granados.vcf
> 1KDownload


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


Re: The folder a script is executed in

2007-08-21 Thread Benjamin
On Aug 21, 4:10 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> How do I find out what folder a script is in while it is executing?
>
> For example, for the file "C:/folder/script.py" contain the following
> two lines of code -
>
> myLocation = GetMyLocation()
> print myLocation
def GetMyLocation():
runningFile = sys.argv[0] if __name__ == "__main__" else __file__
return os.path.dirname(runningFile)
>
> >> C:/folder
>
> Thanks,
>
> Aine.


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


Re: The folder a script is executed in

2007-08-22 Thread Benjamin
On Aug 21, 10:23 am, Benjamin <[EMAIL PROTECTED]> wrote:
> On Aug 21, 4:10 am, [EMAIL PROTECTED] wrote:> Hi,
>
> > How do I find out what folder a script is in while it is executing?
>
> > For example, for the file "C:/folder/script.py" contain the following
> > two lines of code -
>
> > myLocation = GetMyLocation()
> > print myLocation
>
> def GetMyLocation():
> runningFile = sys.argv[0] if __name__ == "__main__" else __file__
> return os.path.dirname(runningFile)
never mind that above
def GetMyLocation():
if __name__ == "__main__":
 runningFile = sys.argv[0] if os.path.isabs(sys.argv[0]) else
os.path.abs(sys.argv[0])
else:
 runningFile = __file__
return runningFile


>
>
>
> > >> C:/folder
>
> > Thanks,
>
> > Aine.


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


Re: Spell-checking Python source code

2007-09-09 Thread Benjamin
On Sep 8, 4:04 pm, John Zenger <[EMAIL PROTECTED]> wrote:
> To my horror, someone pointed out to me yesterday that a web app I
> wrote has been prominently displaying a misspelled word.  The word was
> buried in my code.
>
> Is there a utility out there that will help spell-check literal
> strings entered into Python source code?  I don't mean spell-check
> strings entered by the user; I mean, go through the .py file, isolate
> strings, and tell me when the strings contain misspelled words.  In an
> ideal world, my IDE would do this with a red wavy line.
>
> I guess a second-best thing would be an easy technique to open a .py
> file and isolate all strings in it.
>
> (I know that the better practice is to isolate user-displayed strings
> from the code, but in this case that just didn't happen.)

This is when it's good to use put all your UI strings in a file and
get the advantages of spelling checking ease and the ability to
translate the app.

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


Re: stopping a while True: with the keyboard

2007-09-25 Thread Benjamin
On Sep 25, 8:19 pm, patrick <[EMAIL PROTECTED]> wrote:
> hi all,
>
> i am looking for a way to break a while True: when pressing "s" on my
> keyboard. how can i do this?
>
> pat

Ctrl-C

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


Re: developing an application

2007-09-27 Thread Benjamin
On Sep 27, 5:06 pm, yadin <[EMAIL PROTECTED]> wrote:
> hi!
> i was buiding an application using python...a program
> this was my first one...now that i got it working perfectly
> how can i put the bunch of files into one package?
> the user of the appliation will not know where to start? that is which
> file to click on in oder to start the program?
> thanks a lot

also you can make MacOS apps with the standard MacOS Python
distribution

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


Re: gui toolkits: the real story? (Tkinter, PyGTK, etc.)

2007-10-01 Thread Benjamin
On Oct 1, 8:04 pm, bramble <[EMAIL PROTECTED]> wrote:
> What is the backstory to why Python includes Tk bindings, as opposed
> to some other set of bindings?
>
> I've written a few little Tkinter-based apps, and it's nice and
> simple. I like it well enough. That said though, I keep feeling the
> gravitational pull toward GTK+. I've been meaning to get the whole
> glade+gtk+python thing happening with my own projects, as soon as time
> allows. Is there resistance in the upper Python echelons to GTK
> because of its LGPL licensing?
>
> Reading Alex's Nutshell book, right off the bat he comments that "The
> most popular Python GUI toolkit today is probably wxPython". But then
> he goes on for 45 pages on Tkinter... Seems like he wanted to write
> that chapter on wx instead...
>
> WxWidgets, the last time I looked at it, seemed awfully like MS
> Window's MFC. The licensing seemed vague at the time, and it looks
> like wx contains an extra layer of GUI library, so I didn't spend any
> real time on it. But, regardless, it seems to get good press among
> python folk (I think I remember ESR noting how it was his GUI toolkit
> of choice).
>
> PyQt has had that issue (IIRC) about needing to pay for it for
> commercial apps, so I can see how there might be resistance to it
> being considered the "standard Python GUI toolkit".
>
> So, it would seem to me that Tkinter *might* remain in Python proper,
> but that I probably wouldn't see much effort put into it. Well, the
> Python standard library docs tell a different story. There's stuff in
> there about Tix, ScrolledText, turtle, and then the "other GUI
> packages" doc page goes on about Python megawidgets (Tk-based) and
> Tkinter3000 Widget Construction Kit (WCK). Wow. Looks like Tkinter is
> still having serious support -- even though in that same doc at the
> bottom notes, "PyGTK, PyQt, and wxPython, all have a modern look and
> feel and far more widgets and better documentation than Tkinter."
>
> So, that leaves me wondering, why is Tkinter still getting so much
> focus in the Python standard library?
>
> Maybe a better question is, how has Tk managed to keep beating up the
> newer, more modern, more featureful, better documented toolkits
> encroaching on his territory? What's Tk's secret weapon?

Tk was there at the beginning unlike bindings to wxWidgets or QT so it
got all the standard library modules, too and they are still supported
not to break compatability.

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


Jython import coventions

2007-10-09 Thread Benjamin
When importing Java packages in Jython, what is the convention to
simplify imports? For example:
import java.util as util
Is this correct? Or should I use from * import *?

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


Re: Newbi Q: What is a rational for strings not being lists in Python?

2007-10-15 Thread Benjamin
On Oct 15, 3:03 pm, "Matt McCredie" <[EMAIL PROTECTED]> wrote:
> On 10/15/07, Dmitri O.Kondratiev <[EMAIL PROTECTED]> wrote:
>
>
>
> > To clarify my point:
> > reverse()  is  a lucky one  - Python has variants of *this particular*
> > function both for lists and strings. Yet what about other list functions?
> > How in general, can I write a function that works  both on list and string
> > types? Both are sequences, right? Why string is not a subtype of a list
> > then?
> > The advantage of string being a list of elements, where element is a char is
> > that all list functions will work *without any modifications* on strings as
> > well as on other types of lists.
> > So, I am trying to understand: what is a rational for strings not being
> > lists in Python?
>
> > Thanks,
> > --
> > Dmitri O. Kondratiev
> > [EMAIL PROTECTED]
> >http://www.geocities.com/dkondr
>
> >  On 10/15/07, Dmitri O.Kondratiev <[EMAIL PROTECTED]> wrote:
> > > Gary, thanks for lots of info!
> > > Python strings are not lists! I got it now. That's a pity, I need two
> > different functions: one to reverse a list and one to reverse a string:
>
> > > def reverseList(xs):
> > > if xs == []:
> > > return xs
> > > else:
> > > return (reverseList (xs[1:])) + [xs[0]]
>
> > > def reverseStr(str):
> > > if str == "":
> > > return str
> > > else:
> > > return (reverseStr (str[1:])) + str[0]
>
> > > Ok. Now regarding in-place reversal of a list:
>
> > > >>> l = [1,2,3]
> > > >>> l
> > > [1, 2, 3]
> > > >>> l.reverse()
> > > >>> l
> > > [3, 2, 1]
>
> > > That was, as I expected. Good.
>
> > > Then why this ? :
>
> > > >>> ls = [1,2,3].reverse()
> > > >>> ls
>
> > > >>> print [1,2,3].reverse()
> > > None
>
> > > I mean, why ls is empty after assignment?
>
> > > Also, I couldn't find in the Python docs what this form of slicing means:
> > > xs[::-1]  ?
>
> > > It works for creating a reversed copy of either a string or a list, but
> > what does '::-1' syntax means?
>
> > > Thanks,
>
> > > Dmitri O. Kondratiev
> > > [EMAIL PROTECTED]
> > >http://www.geocities.com/dkondr
>
> > > On 10/15/07, Gary Herron < [EMAIL PROTECTED]> wrote:
> > > > Dmitri O.Kondratiev wrote:
>
> > > > > The function I wrote (below) reverses lists all right:
>
> > > > > def reverse(xs):
> > > > > if xs == []:
> > > > > return []
> > > > > else:
> > > > > return (reverse (xs[1:])) + [xs[0]]
>
> > > > > >>> reverse ([1,2,3])
> > > > > [3, 2, 1]
>
> > > > > Yet when I try to reverse a string I  get:
>
> > > > > >>> reverse ("abc")
>
> > > > > ...
> > > > > ...
> > > > > ...
>
> > > > >   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> > > > > return (reverse (xs[1:])) + [xs[0]]
>
> > > > >   File "C:\wks\python-wks\reverse.py", line 5, in reverse
>
> > > > > return (reverse (xs[1:])) + [xs[0]]
>
> > > > >   File "C:\wks\python-wks\reverse.py", line 2, in reverse
>
> > > > > if xs == []:
>
> > > > > RuntimeError: maximum recursion depth exceeded in cmp
>
> > > > > What's wrong? Why recursion never stops?
>
> > > > If you are doing this as an python-learning exercise, then read on.   If
> > > > you are doing this reversal for real code, then try:
>
> > > >   xs.reverse() for in-place reversal of a list (but not a string), or
> > > >   result = xs[::-1] for creating a reversed copy of either a string or a
> > > > list
>
> > > > Your recursion stops when xs == [], but when you're stripping characters
> > > > off a string,  like 'abc', the remaining portion will be 'bc', then 'c',
> > > > than '', but never [] so you 'll never stop.
>
> > > > Try:
>
> > > > if xs == []:
> > > > return []
> > > > elif xs == '':
> > > > return ''
> > > > else:
> > > > ...
>
> > > > Gary Herron
>
> > > > > Thanks,
> > > > > Dima
>
> The example you posted won't work with tuples either because they,
> like strings, are also immutable. So, the best way to get the posted
> code to work (which is a bad way to go about reversing a string, but I
> digress) is to cast the input parameter to a list first. The returned
> value will always be a list, but you will simply have to convert it
> back to the appropriate type when you are done.
>
> What is the purpose if immutability? It allows a value to be hashed. I
> don't want to get into a discussion about methods for hashing mutable
> types, if you are interested just do a search on the list archives.
> Hashing allows for quick comparisons of values, but more importantly
> it allows for values to be used as keys for the dict type. This is
> very important because, as you will soon find out if you keep learning
> the language, all namespaces in python are implemented as dicts.
Good explanation, but basically strings are immutable so they can be
used in dicts.
>
> So... if you want a mutable string, just cast it to a list, do your
> operations and cast it back to a string.
>
> Incidentally, the proper method for converting a list of characters to
> a string is by 

SIP won't compile on OSX 10.3

2007-11-05 Thread Benjamin
Hi! I'm trying to install SIP on my Mac with the eventual aim of
installing PyQt. The "python configure.py" stage works fine, but when
I type make this is what I see:
cc -c -pipe -Os -w -I. -o main.o main.c
cc -c -pipe -Os -w -I. -o transform.o transform.c
cc -c -pipe -Os -w -I. -o gencode.o gencode.c
cc -c -pipe -Os -w -I. -o export.o export.c
cc -c -pipe -Os -w -I. -o heap.o heap.c
cc -c -pipe -Os -w -I. -o parser.o parser.c
cc -c -pipe -Os -w -I. -o lexer.o lexer.c
c++ -headerpad_max_install_names -o sip main.o transform.o gencode.o
export.o heap.o parser.o lexer.o
cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/
Versions/2.5/include/python2.5 -o siplib.o siplib.c
cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/
Versions/2.5/include/python2.5 -o qtlib.o qtlib.c
cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/
Versions/2.5/include/python2.5 -o threads.o threads.c
cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/
Versions/2.5/include/python2.5 -o objmap.o objmap.c
c++ -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/
Versions/2.5/include/python2.5 -o bool.o bool.cpp
c++ -headerpad_max_install_names -bundle -F/Library/Frameworks -
framework Python -o sip.so siplib.o qtlib.o threads.o objmap.o bool.o
ld: Undefined symbols:
_fstatvfs referenced from Python expected to be defined in libSystem
_lchown referenced from Python expected to be defined in libSystem
_statvfs referenced from Python expected to be defined in libSystem
make[1]: *** [sip.so] Error 1
make: *** [all] Error 2

I'm not an expert at linking, but it looks like the Python lib was
built incorrectly. Or is this a SIP problem? Thanks.

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


Re: Interfaces.

2007-11-16 Thread Benjamin
On Nov 15, 7:55 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> Does anyone know what the state of progress with interfaces for python
> (last I can see ishttp://www.python.org/dev/peps/pep-0245/)
>
> I would argue that interfaces/(similar feature) are necessary in any
> modern language because they provide a way of separating the
> specification from the implementation of a module.
>
> I also had a new idea - when specifying the functionality of a module,
> it would be nice to combine examples of valid behaviour / some sort of
> testing.
>
> It might therefore be possible to combine unit testing with
> interfaces.
>
> What do you all think?
Python is has duck typing. "If it quacks like a duke, it's duck." That
means that you look for what an object can do and has not what it is.
hasattr and getattr are used more than isinstance.
>
> Peter
> (new to python so be nice :)

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


Buffer type

2007-11-21 Thread Benjamin
What's the point of the built in buffer type? The documentation
(http://docs.python.org/lib/typesseq.html) is not very enlightening.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, wxPython, PyGtk, or PyQt...

2007-11-28 Thread Benjamin


John Jameson wrote:
> hi carl,
>
> I'm totally new with graphics for python. I'm using windows, but you
> make it sound like I need to know how to program with MFC to use them?
> Is this true? Can't you just stay in python?
Yes, all of the libraries below let you stay in Python. (They have
binary backends, though.)
> best,
> John
>
>
>
> I would like like to start doing some GUI-programming in Python, but don't
> know which library to choose.
>
> Tkinter seems a bit old. Correct me if I am wrong! The layout doesn't look
> as nice as for the others.
Yes, and it's not very powerful. However, it's really easy to use and
bundled with every Python installation. I like to use it for little
internal projects.
>
> wxPython seems to be the first-hand choice for people doing W32-programming
> (with MFC-experience).
I started out with this kit until I discovered PyQt (and realized the
docs were all C++)...
>
> PyGtk seems to be a modern, very clean and nice approach, but with poor
> W32-support. Is PyGtk a mature library with respect to version stability
> and documentation.
I wouldn't know.
>
> PyQt is a huge library (thanks to Qt), but not free on W32, or?
All versions of Qt4 are available under GPL for Mac, X11, and Windows.
It's big, but very powerful. I have found it to work well on all 3
platforms. The documentation, in my opinion, the most important part,
is super. It's very easy to extend and make your own widgets. The only
thing I find rather clumsy is the I18N support. Pick this toolkit if
you're going to do any serious development.
>
> Is there any possibility that any of the above-mentioned libraries will be
> included as a standard library in any of the near-future Python
> distributions?
Not really
>
> I myself program on W32 at work, but use Linux at home. So, which one should
> I start with in order to reduce the effort of learning something new and to
> be productive in the shortest time possible?
Tkinter will get what you want done fast, but PyQt is much more
powerfull.
>
> By the way, how do I most easily include plotting capabilities to my
> Python-apps?
matplot-lib
>
> Carl
-- 
http://mail.python.org/mailman/listinfo/python-list


Bundling Python on Mac

2007-11-28 Thread Benjamin
Hello, I'm writing a Python/PyQt application. For my Mac distribution.
I would like to include all the needed libraries in the Mac bundle.
How should I go about doing this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, wxPython, PyGtk, or PyQt...

2007-11-29 Thread Benjamin
On Nov 29, 11:53 am, gsal <[EMAIL PROTECTED]> wrote:
> is PyQt related to Qt? I presume so.
I sure that if it wasn't, Trolltech would be on their back...
>
> is Qt needed for PyQt?
>
> is PyQt usable in all platforms Python is available and is it GPLed,
> too?
>
> I read TrollTech webpage on QT and the Windows version is not free for
> in-house development in the private industry; licenses start around
> $6000 for the first year and $2000-$3000 from then on.
>
> gsal

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


Re: Bundling Python on Mac

2007-11-29 Thread Benjamin
On Nov 29, 2:34 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Benjamin schrieb:
>
> > Hello, I'm writing a Python/PyQt application. For my Mac distribution.
> > I would like to include all the needed libraries in the Mac bundle.
> > How should I go about doing this?
>
> The py2app distutils extension should do that for you. It works flawless
> for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to
> admit that it sometimes had errors related to Qt when creating bundles -
> so maybe you need to tweak the support a bit.
Does it bundle the Python library with it, so there are no (excepting
system) dependencies?
>
> Diez

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


Re: Bundling Python on Mac

2007-11-30 Thread Benjamin
On Nov 30, 6:48 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Benjamin schrieb:
>
> > On Nov 29, 2:34 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Benjamin schrieb:
>
> >>> Hello, I'm writing a Python/PyQt application. For my Mac distribution.
> >>> I would like to include all the needed libraries in the Mac bundle.
> >>> How should I go about doing this?
> >> The py2app distutils extension should do that for you. It works flawless
> >> for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to
> >> admit that it sometimes had errors related to Qt when creating bundles -
> >> so maybe you need to tweak the support a bit.
> > Does it bundle the Python library with it, so there are no (excepting
> > system) dependencies?
>
> It does.
Beautiful!
>
> Diez

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


Re: pdf library.

2007-12-29 Thread Benjamin
On Dec 29, 12:54 pm, Shriphani <[EMAIL PROTECTED]> wrote:
> Hi,
> I am looking for a pdf library that will give me a list of pages where
> new chapters start. Can someone point me to such a module ?
ReportLab (ReportLab) might help.
> Regards,
> Shriphani P.

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


Re: Mix different C source files into a single one

2007-12-29 Thread Benjamin
On Dec 29, 12:05 pm, Horacius ReX <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a C program split into different source files. I am trying a
> new compiler and for some reason it only accepts a single source file.
> So I need to "mix" all my different C source files into a single one.
That sounds like one crumy compiler.
>
> Do you know about some type of python script able to do this kind of
> task ?
No, but we can write one:

import sys

if __name__ == "__main__":
glob = ""
for file in sys.argv[1:-1]:
glob += "\n" + open(file, "r").read()
open(sys.argv[-1], "w").write(glob)

It's stupid, but it'll work for basic tasks. (I would actually just
use cat; that's what it's for. :))
>
> Thanks

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


Re: What is the best way to do dynamic imports ?

2007-12-30 Thread Benjamin
On Dec 30, 8:24 am, [EMAIL PROTECTED] wrote:
> Hi list and python gurus :-)
>
> I'm playing with some mod_python and web development. And in me code I
> need to do som dynamic imports.
> Right now I just do a:
>
> exec 'import '+some_modulename
The correct way to do this is use the __import__ function. It takes
the string name of the module you want to import and returns the
module.
new_mod = __import__(some_modulename)
>
> But it seems to easy, is there a "dark side" to doing it this way?
> (memory use,processing ,etc)
Well, it's generally frowned on to use exec and eval.
> And have to I check if the modul is already loaded?
sys.modules is a list of all imported modules, but python won't import
a module if it's already been loaded.
>
> Another thing is how to call my dynamic imported moduls.
> Now I use exec (as with my modules), like this:
>
> exec 'newclass = '+classname+'()'
> newclass.somefunction()
>
> Again it seems to easy. Is there a better/proper way to do it?
If you just have the string name of a class, you have to use eval or
exec:
newclass = eval(classname)

However, if you have the class object, you can just instantiate that:
class LargeClass:
def meth(): pass
some_class = LargeClass
new_class = some_class()
some_class.meth()
>
> Do anybody now a good howto or tutorial to this?
>
> Many thanks and hope you all have a happy new year :-)
You, too!
>
> /marc

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


Re: reassign to builtin possible !?

2008-01-03 Thread Benjamin
On Jan 3, 7:04 am, Bernhard Merkle <[EMAIL PROTECTED]>
wrote:
> Hi there,
>
> I am reading Learning Python 3e from Mark Lutz and just found out that
> reassigning to builtins is possible.
> What is the reason, why Python allows this ? IMO this is very risky
> and can lead to hard to find errors.
I don't think it's a huge issue. In fact, I think it's a feature. For
example, it'd be extremely issue to reassign open, if you wanted to
implement a virtual file system, and you couldn't modify the module
the used open.
> (see also Learning Python 3e, Chapter 16, Page 315)
>
> >>> True
> True
> >>> False
> False
> >>> True = 1
> >>> True
> 1
> >>> True = 0
> >>> True
>
> 0
>
> TIA,
> Berni

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


Re: Detecting OS platform in Python

2008-01-10 Thread Benjamin
On Jan 10, 8:37 pm, Devraj <[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
> My Python program needs reliably detect which Operating System its
> being run on, infact it even needs to know which distribution of say
> Linux its running on. The reason being its a GTK application that
> needs to adapt itself to be a Hildon application if run on devices
> like the N800.
platform.dist might help you. It's not very complete at all, though.
(This is supposed to improve in 2.6, though)
>
> I have been searching around for an answer to this, and did find some
> messages on a lists that suggested the use of sys.platform to detect
> platform, with counter posts saying that it didn't work on Windows
> etc.
>
> Can anyone please shed some light on this?
>
> Thanks a lot.

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


Re: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug

2008-01-14 Thread Benjamin
On Jan 14, 6:26 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> I passed a dict for the "env" variable to Popen with Unicode strings
> for the dictionary values.
>
> Got:
>
>File "D:\Python24\lib\subprocess.py", line 706, in _execute_child
> TypeError: environment can only contain strings
>
> It turns out that the strings in the "env" parameter have to be ASCII,
> not Unicode, even though Windows fully supports Unicode in CreateProcess.

>
> John Nagle

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


Re: "env" parameter to "popen" won't accept Unicode on Windows - minor Unicode bug

2008-01-14 Thread Benjamin
On Jan 14, 6:26 pm, Bjoern Schliessmann  wrote:
> John Nagle wrote:
> > It turns out that the strings in the "env" parameter have to be
> > ASCII, not Unicode, even though Windows fully supports Unicode in
> > CreateProcess.
>
> Are you sure it supports Unicode, not UTF8 or UTF16? Probably using
> something like u"thestring".encode("utf16") will help.
Otherwise: bugs.python.org
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #31:
>
> cellular telephone interference

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


Unique thread ID

2008-01-17 Thread Benjamin
Is there a way to obtain a unique ID for the current thread? I have an
object that I need to store local thread data in, and I don't want to
use threading.local because each thread might have multiple instances
of my object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create graphs an embed them in GUI?

2008-01-17 Thread Benjamin
On Jan 17, 10:07 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-01-17, Heiko Niedermeyer <[EMAIL PROTECTED]> wrote:
>
> > As I'm learning Python from scratch, I don't care wether to use (=learn)
> > TKinter or PyQt or whatever, I just need some advice, which suits my
> > needs best.
> > It would be nice to have the programm working under win and linux
> > (shouldn't be a big Problem) and my requirements concerning the standard
>
> PyGTK is a 3rd option, and wxWindows + Python is a 4th option.
>
> TKinter is supplied with Python, which means everybody with Python also has
> TKinter. Main draw-backs are that it is quite old. Also, it has a peculiar way
> of getting stuff drawn at a canvas.
>
> PyQt is available free with some additional restriction (plz read the
> license) for the Linux system, I don't know whether you can also get a Win
> version under the same conditions (you couldn't when I looked the last time).
> PyGTK is said to be usable for both platforms. I know it works with Linux, and
> there exists a PyGTK installer for Win, but I hacve never used it.
PyQt 4+ is now available for MacOS, Windows, and X under GPL. I tried
Tkinter and wxPython before settling on PyQt. It's more powerful than
Tkinter and has a cleaner API than wxPython.
>
> No recent experience with wxWindows.
>
> > My problem is, that I want to add graph (simple, line connected X,Y-
> > scatter plots) and if possible the 3D representation of atoms in a
> > molecule (-> coloured spheres in space).
Qwt (Q Widgets for Technical Applications) provides graphs widgets
that plug into Qt. There are, of course, Python bindings (pyqwt).
>
> You should probably seperate both problems, in particular if you want to have
> the program do the layout for you. For 2D layout, Graphviz is one of the 
> better
> known packages, run it as a child process. There are several graphviv/dot
> Python libraries available, search PyPI for them.
>
> For 3D, I don't know any programs.
>
> > I think it would take me years to program those by myself, so I would ne
> > ready to use packages, if available.
> > Long story short: Are there packages that could do this, and does it
> > matter which GUI I want to embed them in?
>
> If you want a GUI that understands how to layout chemical structures, you 
> won't
> have many options (on the other hand, you never know, have you tried searching
> PyPI already?).
>
> On the other hand, once you have the coordinates, drawing them is kind of
> trivial in just about any GUI toolkit.
>
> (An alternative may be to have the user lay them out by dragging them with the
> mouse. Programming that is however probably a lot more work.)
>
> Sincerely,
> Albert

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


Re: Unique thread ID

2008-01-18 Thread Benjamin
On Jan 18, 2:31 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Benjamin wrote:
> > Is there a way to obtain a unique ID for the current thread? I have an
> > object that I need to store local thread data in, and I don't want to
> > use threading.local because each thread might have multiple instances
> > of my object.
>
> threading.get_ident() but please use threading.local. Nobody is going to
> stop you if you use a list or dict in threading.local.
then, I have to figure out how to represent an instance of my object
in threading.local. (The data also won't be garbage collect when my
object is, will it?) I think the unique id is elegant in this case.
>
> Christian

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


Re: Unique thread ID

2008-01-18 Thread Benjamin
On Jan 18, 8:31 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Fri, 18 Jan 2008 22:41:47 -0300, Benjamin <[EMAIL PROTECTED]>
> escribió:
>
> > On Jan 18, 2:31 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> >> Benjamin wrote:
> >> > Is there a way to obtain a unique ID for the current thread? I have an
> >> > object that I need to store local thread data in, and I don't want to
> >> > use threading.local because each thread might have multiple instances
> >> > of my object.
>
> >> threading.get_ident() but please use threading.local. Nobody is going to
> >> stop you if you use a list or dict in threading.local.
> > then, I have to figure out how to represent an instance of my object
> > in threading.local. (The data also won't be garbage collect when my
> > object is, will it?) I think the unique id is elegant in this case.
>
> I think you didn't get how threading.local works yet. It's a lot easier
> than you imply. Just store your instances as attributes of a
> threading.local object. You may use a list or dictionary if you want
> multiple instances.
> Read _threading_local.py, it contains a lot of examples.
You're correct. I misread the documentation. I now understand how it
works and am using it. Thanks for pointing me down the right path.
>
> --
> Gabriel Genellina

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


Re: read files

2008-01-21 Thread Benjamin
On Jan 21, 9:08 pm, Mel <[EMAIL PROTECTED]> wrote:
> J. Peng wrote:
> > first I know this is the correct method to read and print a file:
>
> > fd = open("/etc/sysctl.conf")
> > done=0
> > while not done:
> > line = fd.readline()
> > if line == '':
> > done = 1
> > else:
> > print line,
>
> > fd.close()
>
> > I dont like that flag of "done",then I tried to re-write it as:
>
> > fd = open("/etc/sysctl.conf")
> > while line = fd.readline():
> > print line,
> > fd.close()
>
> > this can't work.why?
>
> Formally, because line = fd.readline() is a statement, not an
> expression, and it can't be put into an if statement like that.
>
> The most idiomatic way is probably
>
> fd = open ("/etc/sysctl.conf")
> for line in fd:
> print line
more idiomatic in Python 2.5+:

from __future__ import with_statement
with open("/my/file.conf") as fd:
for line in fd:
print line
>
> Mel.

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


Cleanup when a object dies

2008-01-22 Thread Benjamin
I writing writing a class to allow settings (options, preferences) to
written file in a cross platform manner. I'm unsure how to go a about
syncing the data to disk. Of course, it's horribly inefficient to
write the data every time something changes a value, however I don't
see how I can do it on deletion. I've read that __del__ methods should
be avoided. So am I just going to have to force the client of my
object to call sync when they're done?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cleanup when a object dies

2008-01-23 Thread Benjamin
On Jan 22, 11:29 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On Jan 22, 7:54 pm, Benjamin <[EMAIL PROTECTED]> wrote:
>
> > I writing writing a class to allow settings (options, preferences) to
> > written file in a cross platform manner. I'm unsure how to go a about
> > syncing the data to disk. Of course, it's horribly inefficient to
> > write the data every time something changes a value, however I don't
> > see how I can do it on deletion. I've read that __del__ methods should
> > be avoided. So am I just going to have to force the client of my
> > object to call sync when they're done?
>
> Lots of ways
> 1. Try the atexit module
> 2. Use a weakref callback
So, I can keep a global list weakrefs to all the objects of my class
that have been created. Then have the callback call sync on them?
> 3. Embed a client callback in a try/finally.
> 4. Or, like you said, have the client call a sync() method -- this is
> explicit and gives the client control over when data is written.
>
> Raymond

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


Re: Convert list to file object without creating an actual file.

2008-01-24 Thread Benjamin
On Jan 24, 8:57 pm, Bart  Kastermans <[EMAIL PROTECTED]> wrote:
> I have written a little program that takes as input a text file,
> converts
> it to a list with appropriate html coding (making it into a nice
> table).
> Finally I want to upload this list as a textfile using ftp.
>
> If homeworkhtml contains the list of lines;
> e.g. homeworkhtml = ["", "", "", "test", "" .
>
> I want to call:
> ftp.storlines("STOR " + filename, homeworkhtml)
>
> which gives me the error
> Traceback (most recent call last):
>   File "./testhw.py", line 67, in ?
> ftp.storlines("STOR " + filename, homeworkhtml)
>   File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/ftplib.py", line 428, in storlines
> AttributeError: 'list' object has no attribute 'readline'
Perhaps what you want is StringIO. It lets your pretend a string is a
file so ftplib won't choke. You'll have to convert your list to a
string, though (perhaps with join):
from cStringIO import StringIO
fake_file = StringIO("".join(my_list))
>
> Expected since homeworkhtml is in fact not a file.  Is there a way
> to convert this list to a file object without first writing it to disc
> and
> then opening the resulting file?
>
> Best,
> Bart

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


Re: refcount

2008-01-29 Thread Benjamin
On Jan 29, 5:46 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Simon Pickles wrote:
> > Hi,
>
> > Is is possible to access the refcount for an object?
>
> > Ideally, I am looking to see if I have a refcount of 1 before calling del
>
> Help on built-in function getrefcount in module sys:
>
> getrefcount(...)
> getrefcount(object) -> integer
>
> Return the reference count of object.  The count returned is generally
> one higher than you might expect, because it includes the (temporary)
> reference as an argument to getrefcount().
Are there any cases when it wouldn't?
>
> Christian

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


Re: Python GUI toolkit

2008-02-03 Thread Benjamin
On Feb 3, 10:55 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-02-03, Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
> > Hallöchen!
>
> > [EMAIL PROTECTED] writes:
>
> >> [...]
>
> >> the only remaining are qt4 and wx, i would like to know if one of
> >> these or any other toolkit is capable of creating good-looking
> >> GUI's, like in other apps, for e.g, .net apps.
>
> > I think both Qt4 and wx create good-looking GUIs, since Qt4 now
> > tries to use the widgets from the platform it's running on.
>
> Really? Qt uses GTK when running uder Gnome or XFCE??
Qt doesn't use the any of the native APIs for making widgets. (Well,
it does on Mac and later Window's versions but that's beside the
point.) It draws a the widgets itself. So, it can use the Cleanlooks
style on GNOME which is supposed to imitate the GTK widgets and style.
>
> --
> Grant Edwards   grante Yow!  I will SHAVE and
>   at   buy JELL-O and bring my
>visi.comMARRIAGE MANUAL!!

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


Re: Edit Python code programmatically

2008-02-09 Thread Benjamin
On Feb 9, 5:47 am, "Guilherme Polo" <[EMAIL PROTECTED]> wrote:
> 2008/2/9, Alex <[EMAIL PROTECTED]>:
>
> > Which library could you recommend to perform simple editing of Python
> >  code (from Python program)? For example, open *.py file, find specific
> >  function definition, add another function call inside, find existing
> >  call and change parameter value, etc.
>
> You are after inspect, it is included with python.
>
> >  What I'm trying to implement isn't a real visual programming tool, but
> >  some code-generation is necessary. For now I think I can generate Python
> >  syntax manually (like any text file), but it can become more complicated
> >  in future (like partially implementing code-generation library), plus
> >  there'll always be possibility of corrupting files and losing data (or
> >  having to recover valid Python syntax manually) due to coding mistake.
>
> Generating code like this is always dangerous. Maybe you could
> generate some other kind of file, then use some library or build one,
> to operator over this file.
It can be quite useful, though, say when you're writing interfaces for
several languages and you want to follow DRY.
>
> >  Thanks
>
> >  --
> >  http://mail.python.org/mailman/listinfo/python-list
>
> --
> -- Guilherme H. Polo Goncalves

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


Re: Passing a callable object to Thread

2008-02-15 Thread Benjamin
On Feb 15, 6:51 pm, skawaii <[EMAIL PROTECTED]> wrote:
> On Feb 15, 7:23 pm, Paul Rubin  wrote:
>
> >  t = th.Thread(target=tribalwars.populate_all_tribes, args=("data/w7/",))
>
> Thanks, that did it. After playing around in the interpreter a bit, I
> realize now that args=("data/w7/") doesn't create a tuple, like I
> thought it would. I have to say, though, having to add a comma at the
> end is hideous syntax

You could type args=tuple("data/w7/").
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a callable object to Thread

2008-02-16 Thread Benjamin
On Feb 15, 9:31 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Fri, 2008-02-15 at 19:21 -0800, Benjamin wrote:
> > You could type args=tuple("data/w7/").
>
> That will produce an 8-tuple containing single-character strings, not a
> 1-tuple containing one string.
Opps. That iterable thing of string gets me often.
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

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


flattening a dict

2008-02-16 Thread Benjamin
How would I go about "flattening" a dict with many nested dicts
within? The dicts might look like this:
{"mays" : {"eggs" : "spam"},
"jam" : {"soda" : {"love" : "dump"}},
"lamba" : 23
}
I'd like it to put "/" inbetween the dicts to make it a one
dimensional dict and look like this:
{"mays/eggs" : "spam",
"jam/soda/love" : "dump",
"lamba" : 23
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flattening a dict

2008-02-21 Thread Benjamin
On Feb 17, 6:18 am, Terry Jones <[EMAIL PROTECTED]> wrote:
> Hi Arnaud & Benjamin
>
> Here's a version that's a bit more general. It handles keys whose values
> are empty dicts (assigning None to the value in the result), and also dict
> keys that are not strings (see the test data below). It's also less
> recursive as it only calls itself on values that are dicts.
>
> But it returns a dict whose keys are tuples. You then need to decide
> what to do with this. Hence the helper function strdictflatten for the case
> when all dict keys can be converted to str.
>
> As I told Arnaud in email, I greatly prefer his version for its elegance.
>
> Terry
>
> def dictflatten(d, prefix=None):
> result = {}
> if prefix is None: prefix = tuple()
> for k, v in d.iteritems():
> key = prefix + (k,)
> if isinstance(v, dict):
> if v:
> result.update(dictflatten(v, key))
> else:
> result[key] = None
> else:
> result[key] = v
> return result
>
> def strdictflatten(d, sep='/'):
> return dict((sep.join(map(str, k)), v) for k, v in 
> dictflatten(d).iteritems())
Thanks. This is great. Now, how would I restrict the depth of the
flattening? For example, what if I just wanted something like this:
{
"mays" : {"eggs" : "spam"},
"jam" : {"soda" : "soda/love" : "dump"},
lamba" : 23
}
They are left alone up the to second level of recursion.
> if __name__ == '__main__':
> test = {
> "" : {},
> 4 : 5,
> "mays" : {"eggs" : "spam"},
> "jam" : {"soda" : {"love" : "dump"}},
> "lamba" : 23
> }
>
> d = dictflatten(test)
> print strdictflatten(test)
>
> >>>> {'': None, 'lamba': 23, 'mays/eggs': 'spam', '4': 5, 'jam/soda/love': 
> >>>> 'dump'}

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


Re: flattening a dict

2008-02-21 Thread Benjamin
On Feb 21, 9:13 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Feb 21, 8:04 pm, Benjamin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 17, 6:18 am, Terry Jones <[EMAIL PROTECTED]> wrote:
>
> > > Hi Arnaud & Benjamin
>
> > > Here's a version that's a bit more general. It handles keys whose values
> > > are empty dicts (assigning None to the value in the result), and also dict
> > > keys that are not strings (see the test data below). It's also less
> > > recursive as it only calls itself on values that are dicts.
>
> > > But it returns a dict whose keys are tuples. You then need to decide
> > > what to do with this. Hence the helper function strdictflatten for the 
> > > case
> > > when all dict keys can be converted to str.
>
> > > As I told Arnaud in email, I greatly prefer his version for its elegance.
>
> > > Terry
>
> > > def dictflatten(d, prefix=None):
> > > result = {}
> > > if prefix is None: prefix = tuple()
> > > for k, v in d.iteritems():
> > > key = prefix + (k,)
> > > if isinstance(v, dict):
> > > if v:
> > > result.update(dictflatten(v, key))
> > > else:
> > > result[key] = None
> > > else:
> > > result[key] = v
> > > return result
>
> > > def strdictflatten(d, sep='/'):
> > > return dict((sep.join(map(str, k)), v) for k, v in 
> > > dictflatten(d).iteritems())
>
> > Thanks. This is great. Now, how would I restrict the depth of the
> > flattening? For example, what if I just wanted something like this:
> > {
> > "mays" : {"eggs" : "spam"},
> > "jam" : {"soda" : "soda/love" : "dump"},
> > lamba" : 23}
>
> > They are left alone up the to second level of recursion.
>
> Why don't you do your homework on your own for a change ? Or at least
> pretend you're even trying ?

Here's a attempt:
def dictflatten(d, prefix=None, depth=2, cur_depth=0):
result = {}
if prefix is None: prefix = tuple()
if isinstance(prefix, basestring): prefix = (prefix,)
cur_depth += 1
for k, v in d.iteritems():
key = prefix + (k,)
print key, cur_depth
if isinstance(v, dict):
if v:
if cur_depth >= depth:
result.update(dictflatten(v, key, depth,
cur_depth))
else:
result.update(dictflatten(v, k, depth, cur_depth))
else:
result[key] = None
else:
result[k] = v
return result

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


Re: Permission to use Mac OS 'rocketship' dock icon?

2008-02-28 Thread Benjamin
On Feb 28, 3:37 pm, "Anand Patil" <[EMAIL PROTECTED]>
wrote:
> Hi all,
>
> The image of a rocket with the Python logo that occasionally shows up
> in the dock would make part of a nice logo for PyMC, an open-source
> Python Bayesian statistics package. Anyone know who we would have to
> ask to get permission to use it?
Have at look at http://www.python.org/psf/trademarks/.
>
> Thanks,
> Anand

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


Re: metaclasses

2008-03-03 Thread Benjamin
On Mar 3, 7:12 pm, [EMAIL PROTECTED] wrote:
> What are metaclasses?

Depends on whether you want to be confused or not. If you do, look at
this old but still head bursting essay: 
http://www.python.org/doc/essays/metaclasses/.

Basically, the metaclass of a (new-style) class is responsible for
creating the class. This means when Python sees
class Foo(object):
__metaclass__ = FooMeta
class FooMeta(type):
def __new__(cls, name, bases, dct):
   #do something cool to the class
   pass
It asks FooMeta to create the class Foo. Metaclasses always extend
type because type is the default metaclass.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute

2008-03-09 Thread Benjamin
On Mar 9, 4:22 pm, Gif <[EMAIL PROTECTED]> wrote:
> i'm trying to execute a file without replacing the current process,
> but after searching the help file, documentations and the web, i can't
> a way of doing that.
>
> os.exec*() will close the current program.
Have a look at the subprocess module.
>
> ps: by executing i mean like typing "mspaint" in run dialog.. it's not
> a python file

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


Re: wxPython/wxWidgets ok for production use ?

2008-03-10 Thread Benjamin
On Mar 10, 2:11 pm, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Malcolm Greene wrote:
> >> My personal experience with wxPython has its ups and downs. Specifically
> >> when it comes to crashes, I wouldn't bet my life on it.
>
> > I'm new to Python and getting ready to build a small client based
> > application intended to run on Windows and Linux. I was planning on using
> > wxPython until I saw your comment above.
>
> Just to make this sound a bit less like FUD: my last experience with wxPython
> dates back a couple of years (2004/5?), but back then, we used BoaConstructor
> in a project, which crashed a bit too often to do real work with it - and with
> crashing I mean crashing Python, not just showing us its blank traceback. So
> this was definitely a problem either in wxWindows or in wxPython.
>
> I have no idea how well it works today, but this has definitely forged my
> opinion on wxPython.
>
> > Any suggestions on an alternative Python client-side GUI library (pyQT ?)
> > or tips on where I can find out more about wxPython/wxWidget problems?
>
> The only other GUI library I used was PyQT3. To me, it has proven to be very
> stable, pretty easy to use and feature rich. And from what I read about it,
> PyQT4 is supposed to be another lot better and has removed the few API quirks
> I found at the time (AFAIR, it finally returns plain Python strings from the
> API, for example).
No, it still returns QStrings, so it doesn't break tons of code. I
just always convert it to unicode if I'm going to keep the string
around.
>
> Stefan

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


Re: os.path.isdir question

2008-03-15 Thread Benjamin
On Mar 15, 8:12 pm, lampshade <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm having some problems with  os.path.isdir  I think it is something
> simple that I'm overlooking.
>
> #!/usr/bin/python
> import os
>
> my_path = os.path.expanduser("~/pictures/")
> print my_path
> results = os.listdir(my_path)
> for a_result in results:
> if os.path.isdir(str(my_path) + str(a_result)):
Try if os.path.isdir(os.path.join(my_path, a_result)):
> results.remove(a_result)
>
> for x in results: print x
>
> The problem is, that the directories are never removed.  Can anyone
> point out what I'm missing that is causing the bug?  Is there a better
> way of doing this?
You should always use os.path.join to join paths. You shouldn't add
them like normal strings. I suspect you're getting a combination which
doesn't exist, so it isn't a dir. :)
>
> Thanks,

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


Re: 'join' in the wrong word for the method in class Thread.

2008-03-15 Thread Benjamin
On Mar 15, 7:29 pm, [EMAIL PROTECTED] wrote:
> 'join' in the wrong word for the method in class Thread.
>
> The agent-patient semantics of calling functions can get ambiguous.
> It is not a problem of native Pythoners alone.  Is it due to lazy
> programming, an inability of English (do you have it in other
> languages?), or not a problem at all?
This is what Java uses, and Python's threading module tries to imitate
it.
>
> th1.join() doesn't mean, 'do something to th1', or even, 'have th1 do
> something to itself.'  In fact, if anything is doing anything
> differently, taking waiting to be doing something different, it's the
> caller.
>
> Translating literally,
>
>th1.join() -> join me here, th1.
>
> And,
>
>file1.close() -> close yourself, file1.
>
> But not,
>
>th1.join() -/> join yourself, th1.
>
> Worse,
>
>lock1.wait() -/> wait, lock1.  (For what?)
>
> Furthermore, in toolbars:
>
>File -> Open -/> file an open.
>
> and:
>
>File -> Load -/> load a file.  (It means, load the computer.)
>
> In English, the placements of identifiers isn't consistent.  IOW,
> there isn't a syntactic mapping into natural language sentences.
> (Though you can do it in Latin, German, Sanskrit, and Russian with
> case markers*.)  What are the true literals?  What's doing what?
>
> th1.join() -> 'be joined by th1'
> file1.close()-> 'close file1'
> lock1.wait()-> 'getinlinefor lock1'
>
> And of course, 'open' isn't a method of File objects at all.  The
> closest is, 'be loaded by file1'.
>
> Assuming speakers** of classical computer languages use OVS order--
> object-verb-subject***, the most literal transformations are:
>
> th1.bejoinedby()
> file1.close()
> lock1.getinlinefor().
>
> The mapping of identifiers to English isn't consistent.  It takes some
> knowledge to read them-- shuffle an English sentence and it changes
> meaning.
>
> Functional languages are one long sentence: True.  Declarative
> ones tell a story.  ('th1' joins him.)  Imperatives command an
> impartial audience.
>
> What do the docs say about it?
>
> '''
> Thread.join([timeout])
> Wait until the thread terminates. This blocks the calling thread until
> the thread whose join() method is called terminates - either normally
> or through an unhandled exception - or until the optional timeout
> occurs.
>
> When the timeout argument is present and not None, it should be a
> floating point number specifying a timeout for the operation in
> seconds (or fractions thereof). As join() always returns None, you
> must call isAlive() after join() to decide whether a timeout happened
> - if the thread is still alive, the join() call timed out.
>
> When the timeout argument is not present or None, the operation will
> block until the thread terminates.
>
> A thread can be join()ed many times.
>
> join() raises a RuntimeError if an attempt is made to join the current
> thread as that would cause a deadlock. It is also an error to join() a
> thread before it has been started and attempts to do so raises the
> same exception.
> '''
>
> The natural language meaning of 'join' isn't used.  Do benevolent
> dictators do this?  What do malevolent ones call themselves?
>
> *Latin, German, Sanskrit, and Russian can do it.  Latin, German,
> Sanskrit, and Russian -speakers- can do it.
> **It would be interesting to try to learn a language without ever
> speaking it.
> *** English is SVO, subject-verb-object.  French is too, unless the
> object is direct: subject- direct-object -verb.
>  The sum of the first three integers in the last two files, sorted
> alphabetically, in 'c:\programs'.

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


Re: os.path.isdir question

2008-03-16 Thread Benjamin
On Mar 16, 2:27 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Mar 16, 2:27 am, Benjamin <[EMAIL PROTECTED]> wrote:
>
> > On Mar 15, 8:12 pm, lampshade <[EMAIL PROTECTED]> wrote:> Hello,
>
> > > I'm having some problems with  os.path.isdir  I think it is something
> > > simple that I'm overlooking.
>
> > > #!/usr/bin/python
> > > import os
>
> > > my_path = os.path.expanduser("~/pictures/")
> > > print my_path
> > > results = os.listdir(my_path)
> > > for a_result in results:
> > > if os.path.isdir(str(my_path) + str(a_result)):
>
> > Try if os.path.isdir(os.path.join(my_path, a_result)):> 
> > results.remove(a_result)
>
> > > for x in results: print x
>
> > > The problem is, that the directories are never removed.  Can anyone
> > > point out what I'm missing that is causing the bug?  Is there a better
> > > way of doing this?
>
> > You should always use os.path.join to join paths. You shouldn't add
> > them like normal strings. I suspect you're getting a combination which
> > doesn't exist, so it isn't a dir. :)
>
> You are also removing items from 'results' while iterating over it,
> which has an undefined behaviour. It would be better to build a new
> list of those that aren't directories.

This list comprehension should do the trick pythonically:
final_results = [a_result for a_result in results if
os.path.isdir(os.path.join(my_path, a_result))]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using threads in python is safe ?

2008-03-16 Thread Benjamin
On Mar 16, 3:40 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Sat, 15 Mar 2008 11:57:44 -0200, Deepak Rokade <[EMAIL PROTECTED]>
> escribi�:
>
> > I want to use therads in my application. Going through the docs , I read
> > about GIL.
> > Now I am confused whether using threads in python is safe or not.
>
> > One thing I know that if I am accessing global variables in two or more
> > threads I need to synchronize them
> > using locking or such mechanism so that only one thread access them at a
> > time.
>
> Yes, altough some operations are known to be atomic so you don't need a
> lock in that cases. I think there is a list in the wiki somewhere  
> http://wiki.python.org/moinor perhaps at the effbot's site  
> http://www.effbot.org
Even for atomic operations, you should lock, though. That is not
consistent over different Python implementations and is not always
going to be in same in CPython.
>
> > 1.  In order to support multi-threaded Python programs, there's a global
> > lock that must be held
> > by the current thread before it can safely access Python objects.
> > Does this lock need to be held by python application script expliciltly
> > before accessing any python object or
> > interpreter takes acre of it ?
>
> No, the interpreter takes care of it. The GIL is a concern for those
> writing extensions using the Python API.
>
> > 2. Does multithreaded python script need to held lock before calling any
> > blocking I/O call?
> > Or one should not worry about GIL while using python threads if job to be
> > processed by thread does not call
> > any global variables and thread unsafe Python/C extension ?
>
> Python code should not worry about the GIL. The problem would be, a
> callback written in Python for a not-thread-aware extension that had
> released the GIL.
>
> --
> Gabriel Genellina

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

Re: Is IronPython real Python?

2008-03-24 Thread Benjamin
On Mar 24, 12:00 pm, jmDesktop <[EMAIL PROTECTED]> wrote:
> I know that IronPython and CPython are different in that one does not
> use the .net framework, but are they both really the same Python
> language.  From my basic understanding, it will depend on what the
> programmer's goal is as to which of the two would be used, but I
> didn't know if they were really the same language.

CPython is main implementation. The other implementations, PyPy,
Jython, and IronPython, are always playing catchup to CPython, so you
can't expected the latest CPython features in all the implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "python -3" not working as expected

2009-01-09 Thread Benjamin
On Jan 8, 11:35 pm, John Machin  wrote:
> On Jan 9, 1:56 pm, Benjamin  wrote:
>
> > On Jan 8, 4:21 pm, Thorsten Kampe  wrote:
>
> > > * Terry Reedy (Thu, 08 Jan 2009 17:04:04 -0500)
> > > > Since you are, I believe, at least the second person to report being bit
> > > > by this confusion, please open an issue at bugs.python.org and suggest a
> > > > couple of revised sentences that you think are more informative.
>
> > > Will do tomorrow. The revised sentence could be in the line of "warn
> > > about Python 3.x incompatibilities that cannot trivially be fixed by
> > > 2to3.py".
>
> > Actually, don't bother now; I've fixed it up in the trunk.
>
> Would you mind giving a pointer to where or what your fix is? The
> reason for asking is that Thorsten's suggestion is ambiguous: warn
> about some? all? 3.x problems that can't be trivially fixed by 2to3?
> Can't be "all"; there are in fact a number of problems that can't be
> trivially fixed by 2to3 and can't be detected by running 2.6 with the
> -3 option.

I added "and cannot by trivially fixed by 2to3".

>
> These include
> (a) problems that cause a reasonably informative exception in 3.x
> right at the point where the problem exists
> (b) problems where the behaviour has changed but no exception is
> raised, and your code lurches off down the wrong path, and you need to
> work backwards from subsequent exception(s) and/or failing test case
> (s) to pin-point the problem.
>
> I'll use string constants to provide an example of each type. When
> faced with "abcd", 2to3 has no way of telling whether that should be
> str ("abcd") or bytes (b"abcd"). In the vast majority of cases, to
> guess it should be str is correct, so there is no change to the source
> file, and a warning would  almostly always be noise.
>
> Example of problem (a): chunks is a list of slices of bytes read from
> a binary file.
> In 2.x you write
> glued = ''.join(chunks)
> In 3.0 you get this:>>> chunks = [b'x', b'y']
> >>> ''.join(chunks)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: sequence item 0: expected str instance, bytes found
>
> Example of problem (b): some_bytes has been read from a file that was
> opened in 'rb' mode and contains the 4 ASCII bytes 'abcd'
> # 2.x simulation>> some_bytes == "abcd"
>
> True
> # 3.0 simulation>>> type(some_bytes)
> 
> >>> type("abcd")
> 
> >>> some_bytes == "abcd"
>
> False # because the types are not comparable for equality.
>
> Another type (b) example is the (majority-guessed) 2to3 change from [c]
> StringIO.StringIO to io.StringIO ... if you really should feed some
> library an io.BytesIO instance instead, it can travel quite a distance
> before blowing up.

Yes, bytes/str is an excellent example of where the third part of the
porting helpers. We'll need good documentation. Unfortunately, as you
note below, this isn't exactly the case yet.

>
> Perhaps some of this info could be put 
> intohttp://docs.python.org/dev/py3k/whatsnew/3.0.html#porting-to-python-3-0
> ... or maybe a separate HOWTO or wiki chapter could be set up for
> porting to 3.x, including topics like:
> (1) maintaining one set of source files (when you are maintaining a
> package that must run on e.g. 2.1 through 3.x)
> (2) the possibility of a 3to2 kit for those who have the 2.1 to 3.x
> support-range issue but would like to have the one set of source
> looking like 3.x code instead of the ugliness of version-conditional
> stuff like
> BYTES_NULL = bytes(0) # 3.x
> or
> BYTES_NULL = '' # 2.x
> and (3) [getting in early] what about a %to{} kit (or a {}to% kit!)?
>
> Cheers,
> John

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


Re: "python -3" not working as expected

2009-01-10 Thread Benjamin
On Jan 9, 10:19 pm, John Machin  wrote:
> On Jan 10, 2:55 pm, Benjamin  wrote:
>
> > We'll need good documentation. Unfortunately, as you
> > note below, this isn't exactly the case yet.
>
> So is there a plot to remedy this? Where do we sign up?

Feel free to contribute to the wiki page: 
http://wiki.python.org/moin/PortingToPy3k

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


Re: does exec ignore the locals parameter?

2009-01-22 Thread Benjamin
On Jan 22, 6:45 pm, cburns  wrote:
> In the code below, bar() seems to work, foo() seems broken.
>
> % python -V
> Python 2.6.1
>
> % cat exec1.py
>
> def foo(i) :
>         exec "i = i + 1" in locals(), globals()
>         print "i=%d" % i
>
> def bar(j) :
>         exec "j = j + 1"
>         print "j=%d" % j
>
> foo(0)
> bar(0)
>
> % python exec1.py
> i=0
> j=1
>
> What I really wanted to do was something like:
>
>         exec text in globals(), inspect.currentframe(1).f_locals but
> that didn't work either.

Trying to modify locals() in a function is undefined behavior.

>
> Thanks,
>
> Charlie

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


Re: Dictionary : items()

2009-01-22 Thread Benjamin
On Jan 22, 2:53 am, Paul Rubin  wrote:
> Steven D'Aprano  writes:
> > That is better written as:
> > l = sorted(abcd.items(), key=lambda x:(x[1].lower(), x[0]))
>
> In Python 2.x, I prefer the style
>
>   l = sorted(abcd.iteritems(), key=lambda (k,v): (v.lower(), k))
>
> but Python 3.0 breaks the tuple unpacking per some PEP.

PEP 3113 if you really care.

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


Re: Exhaustive Unit Testing

2008-11-27 Thread Benjamin
On Nov 27, 5:47 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Emanuele D'Arrigo:
> >> I can fragment the code of the original method into one public method and 
> >> a few private support methods.<
>
> > Python also support nested functions, that you can put into your
> > method. The problem is that often unit test functions aren't able to
> > test nested functions.
>
> > A question for other people: Can Python change a little to allow
> > nested functions to be tested? I think this may solve some of my
> > problems.
>
> The problem is that inner functions do not exist until the outer
> function is called and the inner def is executed.  And they cease to
> exist when the outer function returns unless returned or associated with
> a global name or collection.

Of course, you could resort to terrible evil like this:

import types

def f():
def sub_function():
return 4

nested_function = types.FunctionType(f.func_code.co_consts[1], {})
print nested_function() # Prints 4

But don't do that!

>
> A 'function' only needs to be nested if it is intended to be different
> (different default or closure) for each execution of its def.

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


Re: Python 3.0 C API migration tools, or docs?

2008-12-04 Thread Benjamin
On Dec 4, 7:45 pm, illume <[EMAIL PROTECTED]> wrote:
> Hi,
>
> are there migration tools for C API migration to python 3?
>
> I'm sure there must be some code somewhere to help change stuff over
> right?
>
> I don't see any docs for migrating code from 2.x to 3.x 
> either:http://docs.python.org/3.0/c-api/index.html

At the moment all that is officially available is this rather
incomplete howto: http://docs.python.org/howto/cporting.html
>
> Help needed with this!
>
> cheers,

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


Re: Python 3.0 C API migration tools, or docs?

2008-12-05 Thread Benjamin
On Dec 4, 9:06 pm, illume <[EMAIL PROTECTED]> wrote:
> Cool thanks Benjamin!
>
> Maybe it should be in a wiki as well?  So that as people convert their
> modules we can add notes as well.
>
> I started a wiki with that in mind here:http://wiki.python.org/moin/cporting
>
> It'd be good if there was a link from the 2to3 docs, and in the C API
> docs to either/both of these resources.
>
> I thought there'd be much more help for people migrating considering
> the 2to3 tool exists... but I'll get over it... hehe.

Thanks for being so positive. If you'd like to help with the HowTo,
feel free to email [EMAIL PROTECTED]
>
> cheers,

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


Re: Python for kids?

2008-12-07 Thread Benjamin
On Dec 7, 2:13 pm, "Russ P." <[EMAIL PROTECTED]> wrote:
> I have a 12-year-old son who spends too much time playing Xbox live
> and watching silly YouTube videos. I would like to try to get him
> interested in programming. Is anyone aware of a good book or website
> that addresses this concern, preferably (but not necessarily) using
> Python? I could try to teach him Python myself, but I'm afraid I would
> just frustrate him and kill his interest in programming. I did a
> Google search and found a few things, but not a lot. Thanks.

Perhaps what he really needs is some time away from the screen.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Catching Python exceptions in C

2008-12-08 Thread Benjamin
On Dec 8, 12:42 pm, Senthil Kumar <[EMAIL PROTECTED]> wrote:
> Hi Pythoneers !
> Can somebody give a quick solution?
> I am trying to raise exceptions in python and trying to handle it in
> C.
> I am able to raise exceptions successfully. However could not catch
> those in C.
> I am using the following function to run the python from C:
> Pyrun_SimpleString().
> After the exception is raised, I am checking PyErr_Occurred(). It
> always returns NULL, and I cannot catch the exception.
> Pls help me a way out.

If a function returns NULL, you can use PyErr_ExceptionMatches to
check if it is the exception you want to catch.
>
> Thanx in advance !

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


Re: Relative imports in Python 3.0

2008-12-17 Thread Benjamin
On Dec 17, 4:01 am, Nicholas  wrote:
> Imagine a module that looks like
>
> ModuleDir
>      __init__.py
>      a.py
>      b.py
>
> In python 2.x I used to have tests at the end of each of my modules,
> so that module b.py might look something like
>
> import a
>  ..
>  ..
>
> if __name__ == '__main__':
>    runtests()
>
> But under Python 3.0 this seems impossible.  For usual use import a.py
> has to become the line:
>
> from . import a
>
> But if I use that form it is no longer possible to run b.py as a
> standalone script without raising an error about using relative
> imports.
>
> I am sure I am not the first to run into this issue, but what is the
> solution?

Use absolute imports:

from ModuleDir import a

>
> Best wishes,
>
> Nicholas

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


Re: "return" in def

2008-12-28 Thread Benjamin
On Dec 28, 1:35 pm, Steven D'Aprano  wrote:
> The second thing I think is that maybe the function is a generator, and
> so I look for a yield.

You shouldn't, though; Generators can't contain any return statement.

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


Re: When does python 3.1, 3.2 version out?

2009-01-03 Thread Benjamin
On Jan 3, 8:47 pm, 叮叮当当  wrote:
> Now, the 3.0 version is out for a time.
>
> I wonder when the python 3.1 is out, and what change is in python 3.1.

There's no schedule yet. Hopefully, one will come into being around
PyCon.

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


Re: Interpreter & Thread state & Frame structures.

2009-01-07 Thread Benjamin
On Jan 7, 7:42 am, alessiogiovanni.bar...@gmail.com wrote:
> Hi to all,
> there are some fields in the PyInterpreterState and PyThreadState
> obscures.
> PyInterpreterState:
>   1) Why there are the fields *next and *tstate_head?

When there are multiple interpreters active, they are kept in a linked
list. *next refers to the next interpreter state in the list.

>
> PyThreadState:
>   1) Why there is the field *next?

ditto for thread states

>
> An object PyFrameObject is a portion of code, with a state. But
> exactly? Contents of a method/function, or more simply any block
> indented of code? For example, this code:
>     def foo(s):
>         if s > 0:
>             return True
>         else:
>             return False
>
> how much frames are?

1 in this case.

Each, module, class, function (and method) have a code object which
corresponds to one frame when it is executed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "python -3" not working as expected

2009-01-08 Thread Benjamin
On Jan 8, 4:21 pm, Thorsten Kampe  wrote:
> * Terry Reedy (Thu, 08 Jan 2009 17:04:04 -0500)
> > Since you are, I believe, at least the second person to report being bit
> > by this confusion, please open an issue at bugs.python.org and suggest a
> > couple of revised sentences that you think are more informative.
>
> Will do tomorrow. The revised sentence could be in the line of "warn
> about Python 3.x incompatibilities that cannot trivially be fixed by
> 2to3.py".

Actually, don't bother now; I've fixed it up in the trunk.

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


Re: What AugStore and AugLoad AST nodes are?

2008-10-06 Thread Benjamin
On Oct 6, 7:00 am, franck <[EMAIL PROTECTED]> wrote:
> Dear all,
>
> I'm experimenting with new ast module.
> I'd like to have pieces of code that can generate AugLoad and AugStore
> AST nodes.
> Indeed, I actually do not know what they correspond to.

They aren't used by the current implementation.
>
> Thanks for any help!
> Franck

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


Re: Python pre-release announcements

2008-10-08 Thread Benjamin
On Oct 8, 12:42 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Martin v. Löwis" <[EMAIL PROTECTED]> writes:
>
> > > Is there some policy document or release management guide that could
> > > be updated for release teams to follow on this without needing to have
> > > this discussion every time?
>
> > It's in PEP 101.
>
> Thank you.
>
> > If it matters to you, please submit a patch to that document (which
> > is in subversion)
>
> Can do.
>
> > to bugs.python.org.
>
> Requires registration and management of yet another online identity
> :-(

And yet one that will never let you down. :)

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


Re: utf-8 read/write file

2008-10-08 Thread Benjamin
On Oct 8, 12:49 pm, Bruno <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I have big .txt file which i want to read, process and write to another .txt 
> file.
> I have done script for that, but im having problem with croatian characters
> (Š,Đ,Ž,Č,Ć).

Can you show us what you have so far?

> How can I read/write from/to file in utf-8 encoding?

import codecs
data = codecs.open("my-utf8-file.txt").read()

> I read file with fileinput.input.
>
> thanks

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


Re: What do _ast Load | Store | Del | AugLoad | AugStore | Param mean?

2008-10-11 Thread Benjamin
On Oct 11, 12:57 pm, Eloff <[EMAIL PROTECTED]> wrote:
> In the _ast module Attribute, Subscript, Name, List, Tuple all have an
> expr_context associated with them which is defined as:
>
> expr_context = Load | Store | Del | AugLoad | AugStore | Param
>
> I have no idea what they mean, and what's the difference between them.
> I'm porting _ast to IronPython and this is the only part I've had
> difficulty understanding. The only clue I've found is that all these
> expressions are unique in that they can occur in assignment context.
>
> Any insights at all?

They refer to how the expression is used in its context. You can cross
AugLoad and AugStore off because they are not used by the current
implementation. I hope this code examples will explain the rest:

Load:
a = 2
Module(body=[Assign(targets=[Name(id='a', ctx=Store())],
value=Num(n=2))])

Store:
print a
Module(body=[Print(dest=None, values=[Name(id='a', ctx=Load())],
nl=True)])

Del:
del a
Module(body=[Delete(targets=[Name(id='a', ctx=Del())])])

Param:
def f(a): pass
Module(body=[FunctionDef(name='f', args=arguments(args=[Name(id='a',
ctx=Param())], vararg=None, kwarg=None, defaults=[]), body=[Pass()],
decorator_list=[])])

I hope that helps!
>
> Thanks,
> -Dan

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


Re: Transformation with ``parser`` ast

2008-10-13 Thread Benjamin
On Oct 13, 2:39 pm, Malthe Borch <[EMAIL PROTECTED]> wrote:
> (Note: repost from python-dev)
>
> The ``compiler.ast`` module makes parsing Python source-code and AST
> manipulation relatively painless and it's straight-forward to implement
> a transformer class.
>
> However, I find that the ``compiler.pycodegen`` module imposes a hard
> limit on the length of functions since it calculates jump points in a
> recursion.
>
> I'm using this module to compile an XML dynamic template into Python
> code (akin to "Mako") and functions may grow to a rather large size.
>
> Now it seems that the ``parser`` module, which parses source code into
> ``parser.st`` trees does not have the same limitations, however, I could
> not find a transformer class compatible with its tree structure.
>
> What's the recommended way of working with the AST tree from the
> ``parser`` module?

That's old. Use the shiny new ast module that has a higher level view
of the syntax. http://doc.python.org/library/ast.html should start you
off.
>
> \malthe

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


Re: ANN: pyparsing 1.5.1 released

2008-10-19 Thread Benjamin
On Oct 17, 11:14 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
>
> (Python 3.0 uses syntax for catching exceptions that is incompatible
> with Python versions pre 2.6, so there is no way for me to support
> both existing Python releases and Python 3.0 with a common source code
> base.  For those who wish to try out pyparsing with Python 3.0, there
> is a file pyparsing_py3.py in the SourceForge Subversion repository.
> I have done some testing of this code, but many of my unit tests
> still
> need to be converted to Python 3.)

As mentioned above it should be easy to convert this at release time
by running "2to3 -f except pyparsing.py". (Do tell me if you have any
feedback; I'm maintaining it at the moment.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How is the logical processing being done for strings like 'Dog' and 'Cat'

2008-10-20 Thread Benjamin
On Oct 20, 8:41 pm, Sumitava Mukherjee <[EMAIL PROTECTED]> wrote:
> Hi all,
> I am a novice programmer in Python.
> Please could you explain me the results (regarding logical operators).
>
> I get this:
>
> >>> print bool('God' and 'Devil')
>
> True
>
> [This is ok because (any) string is True, so; (True and True) gives
> True]
>
> >>> print('God' and 'Devil')
>
> Devil
>
> [This is what I don't get ]
> and for that matter,I also checked out this:
>
> >>> 01 and 10
>
> 10
>
> What is python doing when we type in ('God' and 'Devil') or key in (01
> and 10) ?

This is an interesting property of python's logical operators. They
don't have to return a boolean object. (It's documented here:
http://docs.python.org/reference/expressions.html#boolean-operations)

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


Re: set/dict comp in Py2.6

2008-10-25 Thread Benjamin
On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> dicts of Python 3.0, like:

Because nobody bothered to backport them.
>
> {x*x for x in xrange(10)}
> {x:x*x for x in xrange(10)}
>
> Bye,
> bearophile

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


Re: set/dict comp in Py2.6

2008-10-25 Thread Benjamin
On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> dicts of Python 3.0, like:

Because nobody bothered to backport them.

>
> {x*x for x in xrange(10)}
> {x:x*x for x in xrange(10)}
>
> Bye,
> bearophile

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


Re: set/dict comp in Py2.6

2008-10-26 Thread Benjamin
On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> dicts of Python 3.0, like:

Because nobody bothered to backport it.
>
> {x*x for x in xrange(10)}
> {x:x*x for x in xrange(10)}
>
> Bye,
> bearophile

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


Re: set/dict comp in Py2.6

2008-10-26 Thread Benjamin
On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> dicts of Python 3.0, like:

Because nobody bothered to backport it.
>
> {x*x for x in xrange(10)}
> {x:x*x for x in xrange(10)}
>
> Bye,
> bearophile

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


Re: print_function and unicode_literals cannot be used at the same time?

2008-10-28 Thread Benjamin
On Oct 27, 1:00 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Gabriel Genellina wrote:
> > En Sun, 26 Oct 2008 12:13:08 -0200, Christian Heimes <[EMAIL PROTECTED]>
> > escribió:
>
> >> ?? wrote:
> >>> Any ideas?
> >>>  Code 1:
> >>>  from __future__ import print_function, unicode_literals
> >>> import sys
> >>> print(type('HELLO, WORLD!'), file=sys.stderr)
>
> >> You have to do each future import in a separate line:
>
> >>  >>> from __future__ import unicode_literals
> >>  >>> from __future__ import print_function
> >>  >>> print(type(""), file=sys.stderr)
> >> 
>
> > That's a bug, isn't it? The language reference explicitely allows it:
> >http://docs.python.org/reference/simple_stmts.html#future-statements
>
> Yes, and Benjamin Peterson already submitted a patch because of this 
> thread.http://bugs.python.org/issue4209

It will be fixed in 2.6.1.
--
http://mail.python.org/mailman/listinfo/python-list


Re: set/dict comp in Py2.6

2008-10-29 Thread Benjamin
On Oct 27, 3:38 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Sat, 25 Oct 2008 23:44:46 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > On Oct 25, 3:13 am, [EMAIL PROTECTED] wrote:
> >> I'd like to know why Python 2.6 doesn't have the syntax to create sets/
> >> dicts of Python 3.0, like:
>
> > Because nobody bothered to backport them.
>
> En Sat, 25 Oct 2008 23:47:32 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > Because nobody bothered to backport them.
>
> En Mon, 27 Oct 2008 00:17:20 -0200, Benjamin <[EMAIL PROTECTED]>  
> escribió:
>
> > Because nobody bothered to backport it.
> > En Mon, 27 Oct 2008 00:19:29 -0200, Benjamin  
> > <[EMAIL PROTECTED]> escribió:
> > Because nobody bothered to backport it.
>
> Yeah, we already know... :)

Sorry about that.
>
> --
> Gabriel Genellina

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


Re: what should we use instead of the 'new' module?

2008-11-12 Thread Benjamin
On Nov 12, 9:54 pm, [EMAIL PROTECTED] wrote:
> Robert,
>
> Appreciate your response.
>
> However Guido says here that types was never intended to be used like
> that:
>
> http://bugs.python.org/msg58023
>
> quote: "The types module was only ever intended for type
> checking, not for creating new instances.
>
> The correct solution will be to use whatever we end up deciding about
> pyvm. Certainly the types module will go."
>
> So that does not seem like a very long term solution to me?

Despite what Guido says, the types module will probably still be with
us for years to come, so I wouldn't worry about it.

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


Re: Performance of Python builtins

2008-05-25 Thread Benjamin
On May 25, 6:19 pm, [EMAIL PROTECTED] wrote:
> Is there any place outside the actual C source for Python that has
> information about the performance of Python's built-in operations? For
> example, I'd *expect* list.append to be O(1), and I hope that list[i]
> is O(1), but I don't really know that for sure, since it would depend
> a lot on the internal implementation.
>
> I'm really only asking this for curiosity's sake --- more as a
> reasonable, non-trollish version of the "Python is slow" post than
> anything. :-)  I've never really had any problems with the performance
> of Python code that I couldn't solve by either changing my algorithm
> or, if all else has truly failed, rewriting in C or Pyrex.
>
> What I'd like to see is something 
> likehttp://svn.python.org/projects/python/trunk/Objects/listsort.txt
> where Python's sorting algorithm is described, except with the focus
> on other built-in constructs.

http://wiki.python.org/moin/TimeComplexity is a start.
>
> Thanks!

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


Re: undocumented functions in pkgutil

2008-05-29 Thread Benjamin
On May 29, 12:34 pm, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> I see that the pkgutil module has many useful functions which are
> however undocumented.
> Does anybody know why it is so? In particolar, can I safely use
> pkg.walk_packages
> without risking a change of interface in the future? I looks unlikely,
> since pkgutil is
> used in setuptools, but I want to be sure before relying on it.

We don't change the API of undocumented functions. However, if you
find these functions useful and would like to work on documenting
these, please email [EMAIL PROTECTED]
>
> Michele Simionato

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


Re: New chairman

2008-05-29 Thread Benjamin
On May 27, 10:48 am, Sverker Nilsson <[EMAIL PROTECTED]> wrote:
> Good luck to you to. Its just that it .. well it has never been easy
> for me to introduce Python at work. This py3k, if I like it or not, is
> not making it easier.
>
> Praktical, pragmatic, you know --- as I said, its not broken so lets
> brake it
>
> I just try to get things to work. And with some style too. Their
> connected. I think a 6 cylinder engine is one of the most stylist
> things there are. And when I was at a museum in Stocholm, I saw Henry
> Fords original enginge and was amazed, it looks just like the one in
> dads car.
>
> Its not about changing and yes I dislike py3k, till somebody can
> convince me otherwise
>
> Guido just seems to not care to post here anyways, so we can try to
> make our own branch/business

Do you have any idea how brilliant Guido is? The reason he's not here
tending to your Python war wounds is that he's busy making important
decisions on python-dev and python-3000. Maintaining a programming
language is like raising 50 very unruly children, and Guido has done
an excellent job.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python blogs

2008-06-02 Thread Benjamin
On Jun 2, 1:49 pm, [EMAIL PROTECTED] wrote:
> Hello!
>
> It seems like Python blogs are gaining popularity. It seems to me that
> they play a crucial role in promoting Python as a language.
> Do you agree with that?
>
> Just a few days ago I've finished setting up a dedicated Python
> blogging environment at:http://www.pythonblogs.com
> Do you think it will be useful for Python community?
> By the way, everyone is welcome to join.

Thanks very much, but the extension says it's written in PHP!
>
> Sincerely yours,
> ~pyblog

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


Re: Register codec dynamically without copying module to lib/python/encodings/

2008-06-05 Thread Benjamin
On Jun 5, 2:57 pm, Michael Ströder <[EMAIL PROTECTED]> wrote:
> HI!
>
> I have a simple codec module for T.61 which principally works. I'd like
> to use this codec without having to copy the module to
> lib/python/encodings/. Is that possible? Can I can extend the encodings
> search path or register the module by calling a function?
codecs.register
>
> Ciao, Michael.

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


Re: ABC question: what is the purpose of the register() method?

2008-06-07 Thread Benjamin
On Jun 7, 1:37 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> I was reading PEP 3119 (http://www.python.org/dev/peps/pep-3119/) and
> have done some experiments using Python 3.0a5. Now I'm somewhat
> puzzled about the purpose of the ABCMeta.register() method.
>
> One can use the register() method to register any class as a virtual
> subclass of any ABC. For example one can register `int` on `Iterable`
> and therefore it is a subclass which is confirmed in the issubclass
> check. What is that good for?

It's mostly good for types created in C, where it's hard to inherit a
class. For example, builtin types register them selves under some ABCs
in collections.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Context manager for files vs garbage collection

2008-06-16 Thread Benjamin
On Jun 16, 8:24 am, Bruno Desthuilliers  wrote:
>
> IIRC (please someone correct me if I'm wrong), proper release of file
> resources as soon as the file object gets out of scope is not garanteed
> in the language spec and is implementation dependant.

Right. Resources are freed in CPython right after they drop out of
scope. This is not true in other implementations, so it's best to be
explicit.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python-3.0b1 build fails on Linux : _gestalt

2008-06-19 Thread Benjamin
On Jun 19, 5:07 am, Helmut Jarausch <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> trying to build Python-3.0b1 on my Gentoo Linux box fails with
>
> Failed to find the necessary bits to build these modules:
> _gestalt
>
> Looking at setup.py it seems that module '_gestalt'
> is only needed on Darwin but my build on Linux fails
> nevertheless.

Your build has not failed. The _gestalt module just didn't build and
was marked as missing. Note this has been fixed on the trunk.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >