Re: py2exe, pyparallel

2005-11-13 Thread Chris Mellon
On 13 Nov 2005 10:03:52 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I'm using py2exe to create a standalone program that uses pyparallel.
> When I run the created program an error occurs and a message directs me
> to
> the log file which contains:
>
> Traceback (most recent call last):
>   File "fg.py", line 30, in ?
> import dds2
>   File "dds2.pyc", line 24, in ?
> WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR
>   File "parallel\__init__.pyc", line 13, in ?
>   File "parallel\parallelwin32.pyc", line 59, in ?
>   File "ctypes\__init__.pyc", line 407, in __getattr__
>   File "ctypes\__init__.pyc", line 319, in __init__
> WindowsError: [Errno 1157] One of the library files needed to run this
> application cannot be found
>
> My setup.py is:
> from distutils.core import setup
> import py2exe
> setup(windows = ["fg.py"])
>
> Line 59 in parallelwin32.py is:  _pyparallel = ctypes.windll.simpleio.
>
> I'm using PythonWin 2.3.2 on Win98SE. I have ctypes 0.9.6, py2exe 0.6.3
> and pyparallel 0.2 installed.
>
> I posted a similar message to the py2exe mailing list but apparently
> that list is inactive. Any suggestions appreciated.
>
> Thanks,
> Gary Richardson
>

This *looks* like all that's happening is that ctypes is unable to
load the dll simpleio.dll , which is not a standard windows library
and therefore needs to be somewhere LoadLibrary can find it.

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


Re: extend

2005-11-14 Thread Chris Mellon
On 11/14/05, Ben Bush <[EMAIL PROTECTED]> wrote:
> is there any python code doing this:
> there are two line segments (2x+y-1=0 with the coordinates of two ending
> points are (1,-1) and (-1,3);
> x+y+6=0 with the coordinates of two ending points are (-3,-3) and
> (-4,-2);). They extend and when they meet each other, stop extending.
> how can i use python to implement this in Tkinter?
>
> --
> Thanks!
> Ben Bush
> --

the comp.graphics.algorithms FAQ may be of use to you:
http://cgafaq.info/wiki/Main_Page

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


Re: Addressing the last element of a list

2005-11-15 Thread Chris Mellon
On 11/14/05, Bengt Richter <[EMAIL PROTECTED]> wrote:
> On 14 Nov 2005 11:20:53 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
> >Op 2005-11-14, Paul Rubin schreef :
> >> Antoon Pardon <[EMAIL PROTECTED]> writes:
> >>> We could then have something like the following.
> >>>
> >>> a = 5
> >>> b = a
> >>> a @= 7
> >>> b ==> would result in 7.
> >>
> >> Ouch!  :-(((
> >>
> >> Can't you live with
> >>
> >> a = [5]
> >> b = a
> >> a[0] = 7
> >>
> >> so b[0] is now 7.
> >
> >And what do I have to do, in case of the following:
> >
> >a = [3, 5]
> >b = a[0]
> >b @= 7
> >a ==> would result in [7, 5]
> >
> >This may seem contrived, but in combination with
> >parameters it could be usefull.
> >
> >Something like:
> >
> >a = [3, 5]
> >
> >def treat(b):
> >  lots of code
> >  b @= new_value
> >
> >f(a[0])
> >a ==> would result in [7, 5]
> >
> >--
> You may be interested in reviewing
>
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/f96b496b6ef14e2/32d3539e928986b3
>
> before continuing this topic ;-)

I read that thread, and am glad I did before asking like I was going
to, if only to avoid being yelled at for not understanding Python
variables ;)

I understand them, I really do, and I know why they act the way they
do, but I still wanted a reference type for binding GUI objects to
data values - for example, a spinner control to an int value. In C++,
I do it by passing a pointer to an int to the control and letting it
do its thing. Theres no simple obvious way to do the same thing in
Python - I ended up by passing a namespace(any object) and an
attribute (by name) and then setting it via setattr in in the control,
which is non-obvious and icky.

>
> Regards,
> Bengt Richter
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-15 Thread Chris Mellon
On 11/15/05, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> The Eternal Squire a écrit :
> > Without copyright, how could one possibly earn a living writing a
> > novel?
>
> Without copyright, how could one possibly earn a living writing programs?-)
> --

I don't know about you, but I own the copyright to almost nothing that
I have written and been paid for, and further, none of has it's
copyright exploited to make money for the entity that does own the
copyright.

Thats not to say that there wouldn't be massive fallout from the lack
of copyright, or that I support that extreme of a solution, but many,
many programs would still be written, and people would still be paid
to write them, even in the absence of copyright. In fact, a few
decades ago, it was legally uncertain whether software qualified for
an IP protection at all, and people still wrote, and were paid to
write, programs.

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


Re: Python obfuscation

2005-11-17 Thread Chris Mellon
On 17 Nov 2005 01:29:23 -0800, Ben Sizer <[EMAIL PROTECTED]> wrote:
> Mike Meyer wrote:
> > > Are you claiming therefore that it's more acceptable to you to have to
> > > access the data remotely every time you use the software than once per
> > > install?
> >
> > Alex's solution doesn't require special treatment for disaster
> > recovery and/or planning, and as such is a valid answer to the
> > question. It may be unacceptable for *other* reasons, but it beats
> > dictating a disaster recovery plan for your software to the end user
> > hands down on that basis.
>
> Sorry, I just don't see this as being a significant difference that
> makes 'access-always' acceptable and 'access rarely' unacceptable.
>
> > > No, I am just pointing out that you are mixing up the concept of an
> > > actual 'right' such as one embodied in a state's constitution, with an
> > > implied 'right' that is just an exemption from committing an offence.
> > > The term 'right' does not even appear in the relevant part of US
> > > copyright law, except to state that it is a limitation on the copyright
> > > holder's rights.
> >
> > You're still just playing semantic games. The common usage is "fair
> > use rights." If you mean "... without infringing on the end users
> > rights, except for fair use rights", then you should say that.
>
> Call it what you like; still, I cannot be infringing on your right when
> such a right does not exist to be infringed. If you want to term it a
> 'right', feel free, but that's not what you're granted under US law or
> the Berne Convention. The 'common usage' here leads to a
> misinterpretation of what you're entitled to. What is actually stated
> is a limitation on the copyright holder's exclusive rights, which is a
> very different matter.
>

Do you have a legal right to wear an orange shirt? To sit backwards in
your chair?

Your rights are anything you can do that is not forbidden - the US
constitution is explicitly designed in this way, something that people
often forget. There is no difference between an "explicit" and an
"inferred" right, by design. If you read the text of the US
constitution, even the phrasing makes this clear. In fact, the format
of the Bill of Rights was considered harmful by some of the founding
fathers, because they felt that people would interpert it exactly as
they have - as enumerating the limits of government power, instead of
enumerating the powers themselves.

Therefore, by extending your rights via DRM, you are infringing upon
the rights of your customers. I *do* have a legal right to backup and
archive my purchased software, just as I have a legal right to write
this email, and I have a legal right to watch a DVD I've purchased.

The very basis of law is about drawing lines between where one persons
rights end and another begins. What (all current) DRM solutions do is
extend the rights of the copyright holder. This, *by definition*,
comes at the expense of the rights of everyone else. The granting of
copyright at all is a limitation of the rights of everyone else, but
one that is legally enshrined and that people (generally) accept as
being in the common good. It's very similar to the concept of private
property. The law grants you the right to keep people from walking
into your house. However, if you decide to build an electric fence
across the sidewalk and into the street, you are infringing on thier
right to walk past.

Further, if you decide to define "right" as something that is
specifically legally protected, then you have no right to embed DRM in
your software at all - you are *explicitly* expanding the rights
granted to you by copyright law, and you do not have explicit legal
rights to do that. Further, you do not have explicit legal rights to
prevent fair-use copying.


> --
> Ben Sizer
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python gui

2005-11-17 Thread Chris Mellon
On 11/16/05, batfree <[EMAIL PROTECTED]> wrote:
> Now GTK can use the local theme.You can choose the local theme to make
> your application windows style on Winodws and Mac likely on mac os.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

This is true only in an very, very loose sense. Gtk does not use the
native rendering tools, and does not have native behavior. The
"native" theme just mimics some of the basic shapes & colors of the
controls.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stringified cPickle

2005-11-17 Thread Chris Mellon
On 11/17/05, David Bear <[EMAIL PROTECTED]> wrote:
> I'm rather new to pickling but I have some dictionaries and lists I want to
> package and send to another process (on another machine).
>
> I was hoping I could just send a stringified pickle. However, the examples
> in the doc have:
>
> >>> import pickle
> >>> pickle.dump(obj,open('save.p','w'))
>
> I don't really want to write to a file. I know I could write to sys.stdout.
> But I'd rather collect the string and do some garbage collect, etc before I
> exit the script.
>
> Is there a way to have cPickle just hand me a string?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --
> --
> http://mail.python.org/mailman/listinfo/python-list
>

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


Re: check if com api is still available

2005-11-18 Thread Chris Mellon
On 11/18/05, Neil Hodgson <[EMAIL PROTECTED]> wrote:
> Hermann Maier:
>
> > i am using the com api of a program and if this program is shut down and
> > my program calls a method of the api, it crashs. that means, i need to
> > check, if the com server is still available, before i can call for it.
>
> The server should not shut down while clients have outstanding
> references to objects within it.
>

The Excel COM object has this behavior - if you call the Quit() method
or (if you're controlling an interactive instance) the excel window is
closed, further calls to the COM object will throw errors. I couldn't
find a solution to this other than to just make sure you didn't do
that. However, I didn't know about the ROT and maybe that will work.

> > but i would prefer a
> > solution that is more clean from the beginning. perhaps there is a
> > windows event that can tell me, wenn the other application, that hosts
> > the com server, is closed or perhaps i can do something with the guid of
> > the com server, maybe there is a call where i can check, if a certain
> > com server is available.
>
> All running COM servers should be in the "Running Object Table"
> (ROT). If you search the net for this term you will find code that can
> show what is in the ROT, so there must be an API.
>
> Neil
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: examining python objects

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 14:05:05 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> __repr__ almost always only prints a summary of it's
> object, not the detailed internal structure that I want to
> see.  When it prints values, that are not pretty-printed,
> nor are the objects that constitute the value printed
> recursively.
>
> Writing my own __repr__() is emphatically what I don't
> want to do!  That is no better than debugging by inserting
> print statements, a technique from the 1980's.
>

It's still a good idea, though

> I am surprised (err, astounded actually) that a basic
> tool like this isn't available.  Besides debugging, I would
> think it would be very helpful to people leaning python.
>

All of this functionality is intrinsically available within Python -
it's a dynamic language and you can easily inspect an object directly
to see what it looks like. Try (pretty) printing the objects __dict__
or __slots__.

> Perhaps one of the Python IDEs contains something
> like this I could extract from it but I was hoping to shortcut
> what will be a time consuming search.
>

wxPython includes a graphical shell & namespace browser which you may
find useful.

> Ben Finney wrote:
> > [EMAIL PROTECTED] wrote:
> > > Is there a function/class/module/whatever I can use to look at
> > > objects?
> >
> > The repr() function is what you want.
> >
> > > I want something that will print the object's value (if any) in
> > > pretty-printed form, and list all it's attributes and their values.
> > > And do all that recursively.
> >
> > The repr() function returns what the object's __repr__ method returns.
> > You'll notice that the builtin container types (string, set, list,
> > dict, ...) will show the values of their referred objects also.
> >
> > Define the __repr__ method on your classes so that they show whatever
> > information you think is useful for debugging.
> >
> > --
> >  \   "If you go flying back through time and you see somebody else |
> >   `\   flying forward into the future, it's probably best to avoid eye |
> > _o__)contact."  -- Jack Handey |
> > Ben Finney
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 15:04:23 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> to start with, excuse me, I'm still learning programming alltogether,
> probably I'm making some fundamental mistake here...
>
> I have the files settings.py, GUIclasses.py and main.py in the same
> directory. In the file main.py are the statements:
>
> import settings
> from GUIclasses import *
>
> class Toepassing(wx.App):
> def OnInit(self):
> window = KFrame(None, "Testerdetest", (1000,900))
> self.SetTopWindow(window)
> window.Show(True)
> return True
>
> app = Toepassing(None)
> app.MainLoop()
>
> In the file GUIclasses.py I have the statements:
>
> import wx
> import wx.lib.mixins.listctrl  as  listmix
>
> class KFrame(wx.Frame):
> def __init__(self, parent, title, Size):
> ...some code...
> self.lst = settings.attrLijst
> some more code..
>
> Now if I run the main.py file I get the error:
>
>   File "G:\Programmeren\Codes contactenlijst\GUIclasses.py", line 40,
> in __init_
> _
> self.lst = settings.attrLijst
> NameError: name 'settings' is not defined
>
> Why is this? Since "from GUIclasses import *" this KFrame is now at
> "the lowest" namespace and should therefore be able to make use of any
> variables living there, including "settings.*", no?
>

import is not like a C/C++ #include - the code in the imported module
is evaluated in it's own namespace, not in the namespace of the
importing file.

So no, this is expected behavior, and should be solved by importing
settings in GUIclasses.py as well.

You don't need to worry about multiple or redundent imports.


> Thanks in advance!
>
> - Kees
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web-based client code execution

2005-11-18 Thread Chris Mellon
On 11/18/05, Paul Watson <[EMAIL PROTECTED]> wrote:
> Steve wrote:
> > AJAX works because browsers can execute javascript.  I don't know of a
> > browser that can execute python.  Basically your stuck with java or
> > javascript because everything else really isn't cross platform.
>
> Well, I guess the Grail browser could run Python, but I do not think I
> can go there.
>
> I need READ access to the users local disk storage.  Can I do this in
> Javascript, or should I bite the bullet and turn to ActiveX?

This can only be done with scripts by disabling or bypassing browser
security restrictions. It can't even be done by zone in IE, only
globally, and I don't know if you can do it at all in Mozilla based
browsers.

A signed activex control or Java Applet (that registers for the
appropriate sandbox permissions) will work.

Overall, it's probably simplest not to do any of these and simply
write a standard application that you have users download and run.
This is the safest and most straightforward solution, and honestly
what you save in configuration managment when people call you
wondering why it doesn't work is probably worth the extra effort it
takes them to actually run your application.

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


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 15:29:43 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Ok, makes sense but didn't seem "natural" to me, although it is an
> obvious consequence of what you just pointed out, namely that modules
> are evaluated in their own namespace, something to keep in mind... On
> the other hand it does apparently work recursively "the other way
> around" since I didn't explicitly import wx in main.py but only
> indirect via importing GUIclasses in which wx is imported right?
>

it worked because all the code that used stuff from the wx namespace
was in GUIclasses.py. If you tried to use create wx classes directly
in your toplevel file it would fail unless you did an "import wx"
first.

Now, as a slight consequence of the specific way you imported, it may
appear to do something different - when GUIClasses.py imported wx, an
entry in the modules namespace was created with the value "wx", and
the value being the wx module. When you do "from GUIClasses import *",
that imports all the symbols in GUIClasses namespace into your local
namespace, including the "wx" entry. This kind of cascading behavior
is one reason that "from foo import *" is frowned up, because the
namespace pollution can cause confusing bugs.

> Thanks. :).
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about namespaces

2005-11-18 Thread Chris Mellon
On 18 Nov 2005 16:09:44 -0800, KvS <[EMAIL PROTECTED]> wrote:
> Hmm. But actually I was doing this import from GUIclasses with exactly
> this in mind, namely that it would make wx also available at top level.

There's no reason not to just "import wx" if you want that.

> I (in my naive understanding) see this as "natural" and actually
> desirable, how could this cause confusing bugs? Do you mean multiple
> "from ... import *"'s 'on top of each other' would cause foo1.foo2.attr
> and foo1.attr both would become just attr and therefore ambiguous at
> top level?

the second import will overwrite the first, making the first inaccessible

>
> If you import foo in two different modules, does the interpreter then
> create one instance of foo and create a reference in both modules to
> the same foo rather than creating two different instances of foo?
>

No. It creates the foos within each module, but which foo you have
access to in the importing module is determined by the order of
import.

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


Re: Guification of console app

2005-11-25 Thread Chris Mellon
On 11/25/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> "metiu" wrote:
>
> > you have a compression utility that works as a standard *nix filter, so
> > it takes something from stdin and gives it back compressed to stdout
> > you like to use it as such, because it's nice to call it from the
> > command line
> >
> > now someone finds your utility quite nice, and says it would be nice to
> > have a GUI that shows you, for example, how long it will take to
> > compress...
> >
> > one way for sure it would be to fork your app, but this would be a
> > waste of time
> >
> > you'd like to reuse the compression library you've already written for
> > your GUI and your console, but:
> > - you'd like to have your console app clean and simple, such as:
> >
> > import sys
> > import CompressLib
> >
> > data = sys.stdin.read()
> > cdata = CompressLib.compress(data)
> > print cdata
> >
> > but you'd like the GUI to show some progress and status info.
>
> here's a simple, stupid, and portable solution.  the first script simulates
> your compression utility:
>
> # compress.py (simulator)
>
> import time, sys
>
> for i in range(100):
> sys.stdout.write(".")
> sys.stderr.write("%d%% done\r" % i)
> sys.stderr.flush()
> time.sleep(0.1)
>
> (it prints "N% done" messages to stderr during the compression)
>
> the second script simulates your GUI.  the stuff in the while loop should
> be run by a timer/alarm function, at regular intervals:
>
> import re, subprocess, time, os
>
> class monitor:
> # looks for "N% done" messages in the output stream
> def __init__(self, tfile):
> # could use dup/reopen instead
> self.file = open(tfile.name, "r")
> def poll(self):
> pos = self.file.tell()
> data = self.file.read()
> if data:
> data = re.findall("(\d+)% done", data)
> if not data:
> self.file.seek(pos)
> else:
> return int(data[-1])
> def close(self):
> self.file.close()
>
> ifile = open("in.txt", "rb")
> ofile = open("out.dat", "wb")
> tfile = open("out.tmp~", "wb")
>
> p = subprocess.Popen(
> "python compress.py",
> stdin=ifile, stdout=ofile, stderr=tfile,
> )
>
> m = monitor(tfile)
>
> while 1:
> # this should be placed in a background task that's called
> # every second or so
> if p.poll() is not None:
> print "DONE"
> break
> status = m.poll()
> if status is not None:
> # update status monitor
> print status, "PERCENT DONE"
> # wait a while before calling the background task again
> print "."
> time.sleep(0.5)
>
> # clean up
> ifile.close()
> ofile.close()
> m.close()
> name = tfile.name
> tfile.close()
> os.remove(name)
>
> if you limit yourself to Unix only, you can simplify things quite a bit (e.g.
> using a pipe instead of the temporary file and use select to poll it, or use
> dup/reopen tricks to avoid opening the temporary file twice; if you do
> the latter, you can also use safe tempfile creation methods (see the
> "tempfile" method for details.  etc).
>
> hope this helps!
>
> 
>
>

If you are using wxPython, you can skip writing this scaffolding
yourself and use wx.Execute and wx.Process, which will allow you to
execute other processes and re-direct thier input and output. The
wxPython demo has an example.

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


Re: General question about Python design goals

2005-11-30 Thread Chris Mellon
On 11/30/05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Paul Rubin wrote:
> >>Look at the list.count() example at the start of this thread.
> >>Diagnosing it isn't hard.  Curing it isn't hard.  It doesn't bloat
> >>Python by an order of magnitude.  A suitably factored implementation
> >>might handle lists and strings with the exact same code and not incur
> >>any extra cost at all.  That type of thing happens all the time here.
> >
> > I believe the language creator use the "lack of" as a way to
> > prevent/discourage that kind of usage. Just like the ternary
> > operator(still don't know why it is finally accepted). It is not a
> > problem(not having), it is a feature(to teach you program better), so
> > what cure are we talking about ?
>
> Sorry, but I still do not get it. Why is it a feature if I cannot count
> or find items in tuples? Why is it bad program style if I do this? So
> far I haven't got any reasonable explanation and I think there is no.
>
> -- Christoph


I'd have to say this:

First, remember that while your idea is obvious and practical and
straightforward to you, everybodys crummy idea is like that to them.
And while I'm not saying your idea is crummy, bear in mind that not
everyone is sharing your viewpoint.

If you want to make changes to the language, you need to be prepared
to convince other people that your idea really is a good one.
Therefore:

Be prepared to present a use case. If your idea really is
straightforward, simple, and obvious this should be fairly easy. It is
possible that your idea is so simple and obvious that everyone will
agree with it, do not expect this to be the case no matter how simple
and obvious it seems to you.

Be prepared to defend your use case. If people show reasons why your
use case is invalid, be prepared to consider that you may be wrong. If
you're still sure that you aren't, present a different use case -
don't expect other people to imagine one for you.

If you *really* want a language feature changed, be prepared to
present a patch for it. If you aren't willing or able to implement it
yourself, you must convince someone else that not only is your change
a good idea, but that it's a good enough idea that they should work on
it, which is always more of an uphill battle.

There may be different subjective or conceptual reasonings at work -
like you wanting to treat tuples as first class sequences while others
(like Guido) want to treat them otherwise. There's no right answer in
a subjective argument, so be prepared to present practical support,
and, unless you're the BDFL, be prepared to be ignored. If it bothers
you enough, you know what your options are.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python string immutable?

2005-11-30 Thread Chris Mellon
On 11/30/05, could ildg <[EMAIL PROTECTED]> wrote:
> In java and C# String is immutable, str=str+"some more" will return a new
> string and leave some gargabe.
> so in java and C# if there are some frequent string operation,
> StringBuilder/StringBuffer is recommanded.
>
> Will string operation in python also leave some garbage? I implemented a
> net-spider in python which includes many html string procession. After it
> running for sometime, the python exe eats up over 300M memory. Is this
> because the string garbages?
>
> If String in python is immutable, what class should I use to avoid too much
> garbages when processing strings frequently?

Python strings are immutable. The StringIO class provides a buffer
that you can manipulate like a file, and then convert to a string and
is probably most suitable for your purposes.

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


Re: wxPython installation issues on Debian

2005-11-30 Thread Chris Mellon
On 11/30/05, Robert Kern <[EMAIL PROTECTED]> wrote:
> Paul McNett wrote:
> > Robert Kern wrote:
> >
> >>Although Ubuntu is a Debian derivative, it does have different packages.
> >>At the moment, Debian's default Python is 2.3 although one can also
> >>install Python 2.4, and most Python packages in Debian have been built
> >>for both (that's why I erroneously recommended installing the apparently
> >>nonexistant python2.4-wxgtk2.4). However, it appears that the maintainer
> >>of the Debian wxPython is not building packages for both Python 2.3 and
> >>2.4. The maintainer of the Ubuntu wxPython package apparently is.
> >
> > As far as I know, the maintainer of the wxPython package is the same (Ron) 
> > and
> > Ubuntu just uses the upstream wxPython from Debian. However, I see above 
> > that
> > you are referencing wxPython 2.4 and not 2.6. It is very possible that for
> > wxPython 2.4, there is only a Python 2.3 package.
> >
> > wxPython 2.4 is obsolete. If possible, wxPython 2.6 should be used. But, I 
> > don't
> > know if it is available for Python 2.4 under Debian (or Ubuntu, for that 
> > matter).
>
> Still only available for Python 2.3 it seems.
>
> http://packages.debian.org/testing/python/python-wxgtk2.6
> http://packages.qa.debian.org/w/wxwidgets2.6.html
>

The ubuntu patch available from the second link seems to provide
support for Python 2.4 (judging from a quick skim). If you're feeling
adventurous, maybe you could try applying that and installing. Or
perhaps just installing the ubuntu package manually, or try using
alien on one of the official RPMs.

> --
> Robert Kern
> [EMAIL PROTECTED]
>
> "In the fields of hell where the grass grows high
>  Are the graves of dreams allowed to die."
>   -- Richard Harter
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: General question about Python design goals

2005-11-30 Thread Chris Mellon
On 11/30/05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> Paul Rubin wrote:
> Look at the list.count() example at the start of this thread.
> Diagnosing it isn't hard.  Curing it isn't hard.  It doesn't bloat
> Python by an order of magnitude.  A suitably factored implementation
> might handle lists and strings with the exact same code and not
incur
> any extra cost at all.  That type of thing happens all the time
here.
> 
> I believe the language creator use the "lack of" as a way to
> prevent/discourage that kind of usage. Just like the ternary
> operator(still don't know why it is finally accepted). It is not a
> problem(not having), it is a feature(to teach you program better),
so
> what cure are we talking about ?
> 
> Sorry, but I still do not get it. Why is it a feature if I cannot
count
> or find items in tuples? Why is it bad program style if I do this?
So
> far I haven't got any reasonable explanation and I think there is
no.
> 
> -- Christoph
> 

I'd have to say this:

First, remember that while your idea is obvious and practical and
straightforward to you, everybodys crummy idea is like that to them.
And while I'm not saying your idea is crummy, bear in mind that not
everyone is sharing your viewpoint.

If you want to make changes to the language, you need to be prepared
to convince other people that your idea really is a good one.
Therefore:

Be prepared to present a use case. If your idea really is
straightforward, simple, and obvious this should be fairly easy. It is
possible that your idea is so simple and obvious that everyone will
agree with it, do not expect this to be the case no matter how simple
and obvious it seems to you.

Be prepared to defend your use case. If people show reasons why your
use case is invalid, be prepared to consider that you may be wrong. If
you're still sure that you aren't, present a different use case -
don't expect other people to imagine one for you.

If you *really* want a language feature changed, be prepared to
present a patch for it. If you aren't willing or able to implement it
yourself, you must convince someone else that not only is your change
a good idea, but that it's a good enough idea that they should work on
it, which is always more of an uphill battle.

There may be different subjective or conceptual reasonings at work -
like you wanting to treat tuples as first class sequences while others
(like Guido) want to treat them otherwise. There's no right answer in
a subjective argument, so be prepared to present practical support,
and, unless you're the BDFL, be prepared to be ignored. If it bothers
you enough, you know what your options are.

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


Re: General question about Python design goals

2005-12-01 Thread Chris Mellon
On 12/1/05, Christoph Zwerschke <[EMAIL PROTECTED]> wrote:
> I think this all boils down to the following:
>
> * In their most frequent use case where tuples are used as lightweight
> data structures keeping together heterogenous values (values with
> different types or meanings), index() and count() do not make much sense.
>
> I completely agree that his is the most frequent case. Still there are
> cases where tuples are used to keep homogenous values together (for
> instance, RGB values, points in space, rows of a matrix). In these cases
> it would be principally useful to have index() and count() methods.
>
> But:
>
> * Very frequently you will use only 2- or 3-tuples, where direct queries
> may be faster than item() and count(). (That's probably why Antoon's RGB
> example was rejected as use case though it was principally a good one).
>
> * Very frequently you want to perform operations on these objects and
> change their elements, so you would use lists instead of tuples anyway.
> See my use case where you would determine whether a vector is zero by
> count()ing its zero entries or the rank of a matrix by count()ing zero rows.
>
> * You will use item() and count() in situations where you are dealing
> with a small discrete range of values in your collection. Often you will
> use strings instead of tuples in these cases, if you don't need to sum()
> the items, for instance.
>
> So, indeed, very few use cases will remain if you filter throught the
> above. But this does not mean that they do not exist. And "special cases
> aren't special enough to break the rules." It should be easy to imagine
> use cases now.
>
> Take for example, a chess game. You are storing the pieces in a
> 64-tuple, where every piece has an integer value corresponding to its
> value in the game (white positive, black negative). You can approximate
> the value of a position by building the sum(). You want to use the tuple
> as a key for a dictionary of stored board constellations (e.g. an
> opening dictionary), therefore you don't use a list.
>

This really looks to me like you have your priorities inverted.
Practically everything you want to do with this structure is
list-like, so why not make it a list and convert it to a tuple when
you need to use it as an index? Even better, since you're doing a lot
of list operations, why not make it a list and define unique IDs or
something to use as indices?

A minor change in your design/thinking (not trying to use a tuple as a
frozen list) instead of a change in the language (making tuples more
like frozen lists) seems to be the warranted solution. But maybe thats
just me.


> Now you want to find the field where the king is standing. Very easy
> with the index() method. Or you want to find the number of pawns on the
> board. Here you could use the count() method.
>
> -- Christoph
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which License Should I Use?

2005-12-01 Thread Chris Mellon
On 11/30/05, Robert Kern <[EMAIL PROTECTED]> wrote:
> Paul Boddie wrote:
> > Paul Rubin wrote:
> >
> >>That is the guy who claims it is impossible to release anything into
> >>the public domain, other than by dying and then waiting 70 years.
> >
> > Is that an indirect reference to the following article?
> >
> > http://www.linuxjournal.com/article/6225
>
> Among other places where Rosen has said it, like his book.
>

In fairness, when on the one hand a lawyer (or 2, in this case) who
specializes in IP law tell you that something is uncertain, and on the
other hand, a non-lawyer (but certainly a smart guy) dismisses the
whole thing as stupid, I kinda tend toward listening to the lawyer.
Especially as, if you carefully read what is and isn't said, DJB
doesn't actually contradict Rosen or Lessig - he says that "as far as
he knows nobody has ever bothered the court with it", which is one way
of telling he's not a lawyer - a lawyer would say (as Lessig does in
his blog post) that there have been no test cases but his analysis of
the law is that there are inconsistencies and that were such a case to
occur, he is not sure who who would prevail. I'm not a legal expert or
a lawyer. But I certainly find Rosens detailed and well-explained
analysis of the situation to be much more convincing than Dans
hand-waving.

> --
> Robert Kern
> [EMAIL PROTECTED]
>
> "In the fields of hell where the grass grows high
>  Are the graves of dreams allowed to die."
>   -- Richard Harter
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: register keyevent in wxpython

2005-12-09 Thread Chris Mellon
On 9 Dec 2005 01:52:27 -0800, ash <[EMAIL PROTECTED]> wrote:
> hi,
> is there a way to register application wide hotkey in wxpython?
> i tried wxWindow::RegisterHotKey(). but the problem is it registers the
> hotkey as a system wide hotkey. this causes problems in other
> applications running concurrently which use the same hotkey.
> i want to do this because i want my app frame (a mdi frame) to accept
> the key event and wx.frame accepts only wx.eventCharHook() which raises
> no keyevent for normal alphanumeric keys.
> any ideas??
> thanks in advance for any help.
>

wx.AcceleratorTable

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


Re: Managing import statements

2005-12-10 Thread Chris Mellon
On 12/10/05, Shane Hathaway <[EMAIL PROTECTED]> wrote:
> Let's talk about the problem I really want help with.  I brought up a
> proposal earlier, but it was only half serious.  I realize Python is too
> sacred to accept such a heretical change. ;-)
>
> Here's the real problem: maintaining import statements when moving
> sizable blocks of code between modules is hairy and error prone.
>
> I move major code sections almost every day.  I'm constantly
> restructuring the code to make it clearer and simpler, to minimize
> duplication, and to meet new requirements.  To give you an idea of the
> size I'm talking about, just today I moved around 600 lines between
> about 8 modules, resulting in a 1400 line diff.  It wasn't just
> cut-n-paste, either: nearly every line I moved needed adjustment to work
> in its new context.
>

You might want to invest in refactoring tools, like the ever-popular
Bicycle Repair Man, which can help ensure that you rename things
correctly.

> While moving and adjusting the code, I also adjusted the import
> statements.  When I finished, I ran the test suite, and sure enough, I
> had missed some imports.  While the test suite helps a lot, it's
> prohibitively difficult to cover all code in the test suite, and I had
> lingering doubts about the correctness of all those import statements.
> So I examined them some more and found a couple more mistakes.
> Altogether I estimate I spent 20% of my time just examining and fixing
> import statements, and who knows what other imports I missed.
>

Both PyLint and PyChecker can detect missing imports (as well as
redundant ones) for you.

> I'm surprised this problem isn't more familiar to the group.  Perhaps
> some thought I was asking a newbie question.  I'm definitely a newbie in
> the sum of human knowledge, but at least I've learned some tiny fraction
> of it that includes Python, DRY, test-first methodology, OOP, design
> patterns, XP, and other things that are commonly understood by this
> group.  Let's move beyond that.  I'm looking for ways to gain just a
> little more productivity, and improving the process of managing imports
> could be low-hanging fruit.
>

It is probably because most people don't regularly switch that much
code around, or use that many modules. I think the fact that you move
that much code between modules is probably a code smell in and of
itself - you're clearly moving and changing responsibilities.
Refactoring in smaller chunks, less extreme refactoring, correcting
the imports as you go, and avoiding inline imports without a really
good reason will probably help you a lot more than a new syntax.

> So, how about PyDev?  Does it generate import statements for you?  I've
> never succeeded in configuring PyDev to perform autocompletion, but if
> someone can say it's worth the effort, I'd be willing to spend time
> debugging my PyDev configuration.
>

PyDev will not generate import statements for you.

> How about PyLint / PyChecker?  Can I configure one of them to tell me
> only about missing / extra imports?  Last time I used one of those
> tools, it spewed excessively pedantic warnings.  Should I reconsider?
>

Yes. Spend an afternoon looking at PyLints options, get rid of the
stuff you don't like, and use it regularly. PyDev has PyLint
integration, which is nice.

> Is there a tool that simply scans each module and updates the import
> statements, subject to my approval?  Maybe someone has worked on this,
> but I haven't found the right Google incantation to discover it.
>

Assuming that you keep your global namespace pure, then you can do
this yourself pretty simply. If you don't, there is no way for
anything to know that you want symbol foo from module bar and not from
module baz.

I don't think I've ever imported more than a dozen modules into any
given file. I rarely find it neccesary to move huge chunks of code
between my modules - the biggest such I did was when I moved from a
single-file proof of concept to a real modular structure, and that
only took me an hour or so. If I'd done it modularly to start with it
would have been fine.

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


Re: lambda (and reduce) are valuable

2005-12-10 Thread Chris Mellon
On 12/9/05, David Isaac <[EMAIL PROTECTED]> wrote:
> >>> Jibes against the lambda-clingers lead eventually to serious
> >>> questions of style in regard to variable namespacing,
> >>> lifespan, cleanup, and so on:
> >>>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ad0e15cb6b8f2c32/
>
> Alan Isaac <[EMAIL PROTECTED]> wrote:
> >> #evaluate polynomial (coefs) at x using Horner's rule
> >> def horner(coefs,x): return reduce(lambda a1,a2: a1*x+a2,coefs)
>
> "Cameron Laird" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > I *think* you're supporting a claim
> > about the value of lambda with a specific example.  Do I have that
> > right?  Are you saying that your definition of horner() would suffer
> > greatly without lambda?
>
> It is a simple example of how lambda and reduce can be very expressive.
> Anyone who understands Horner's rule can see at a glance that this code
> implements it.  Anyone who has bothered to learn what lambda and reduce
> do can see at a glance what the algorithm is.
>
> It just cannot get simpler or more expressive.
>
> Suffer greatly?  Surely not.  For "suffer greatly" you would probably need
> to turn to people who do a lot of event-driven GUI programming.
> But suffer, yes.  Simplicity and expressiveness are valuable.
> That is the point.
>

As someone who does a tremendous amount of event-driven GUI
programming, I'd like to take a moment to speak out against people
using us as a testament to the virtues of lamda. Event handlers are
the most important part of event-driven code, and  making them real
functions with real names is crucial to maintainable code. The only
reason to ever use a lamdba in Python is because you don't want to
give a function a name, and that is just not a compelling use case for
GUI events.

> Cheers,
> Alan Isaac
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-11 Thread Chris Mellon
On 12/11/05, Matthias Kaeppler <[EMAIL PROTECTED]> wrote:
> Brian Beck wrote:
> > def foo(self):
> > raise NotImplementedError("Subclasses must implement foo")
>
> That's actually a good idea, though not as nice as a check at
> "compile-time" (jesus, I'm probably talking in C++ speech again, is
> there such a thing as compile-time in Python at all?!)
>
> Another thing which is really bugging me about this whole dynamically
> typing thing is that it seems very error prone to me:
>
> foo = "some string!"
>
> # ...
>
> if (something_fubar):
> fo = "another string"
>
> Oops, the last 'o' slipped, now we have a different object and the
> interpreter will happily continue executing the flawed program.
>
> I really see issues with this, can anyone comment on this who has been
> working with Python more than just a day (like me)?

You are totally correct and this does cause errors. However, I'd like
you to take a few minutes and go back over all your C and C++ and Java
code and make note of how many lines of code and how many complicated
constructs you've used over the years to subvert the type system in
those languages. In my experience, and in many other peoples
experience, dynamic ducky typing saves far more work than it costs,
even when you factor in "typo bugs" which would be prevented by static
typing. Thats not even counting bugs in the extra code you've written
to work around the compiler. In fact, I'd say that a signifigant
portion of my time in writing C++ code is spent convincing the
compiler to do what I want, and not figuring out what I want. In
Python,  the opposite is true. My experience in that regard is pretty
typical - you'll find scores of stories on the web of C++ programmers
who switched to Python and breathed a sigh of relief.

All that said, there are automated checkers that can assist in
avoiding these kind of
bugs (as well as several others). Look into PyChecker and PyLint.

>
> Regards,
> Matthias
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "0 in [True,False]" returns True

2005-12-13 Thread Chris Mellon
On 13 Dec 2005 11:29:10 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> Op 2005-12-13, Steve Holden schreef <[EMAIL PROTECTED]>:
> > Antoon Pardon wrote:
> >> Op 2005-12-13, Steve Holden schreef <[EMAIL PROTECTED]>:
> >>
> >>>Pierre Quentel wrote:
> >>>
> Hi all,
> 
> In some program I was testing if a variable was a boolean, with this
> test : if v in [True,False]
> 
> My script didn't work in some cases and I eventually found that for v =
> 0 the test returned True
> 
> So I changed my test for the obvious "if type(v) is bool", but I still
> find it confusing that "0 in [True,False]" returns True
> 
> By the way, I searched in the documentation what "obj in list" meant and
> couldn't find a precise definition (does it test for equality or
> identity with one of the values in list ? equality, it seems) ; did I
> miss something ?
> 
> >>>
> >>>It actually uses the __contains__() method of the right-hand operand,
> >>>and in the case of a list that will test for equality of the left-hand
> >>>operand to one of the list elements. Since False == 0 that's why you see
> >>>what you do.
> >>>
> >>>The really interesting question your post raises, though, is "Why do you
> >>>feel it's necessary to test to see whether a variable is a Boolean?".
> >>
> >>
> >> I can give you one example. I have written a tube class. A tube behaves
> >> like Queue but it has additional code so that it can be registed with
> >> gtk in the same way as file descriptor can be registered with
> >> io_add_watch. The way this is implemented is by registering an idle
> >> handler when the tube is not empty and removing it when the tube is
> >> empty. So I have a variable cb_src (for callback source) that can be
> >> a boolean or an integer. The possible values are
> >>
> >>   False: Not registered by the user
> >>   True: Registered by the user but no nternal idle callback registerd
> >>   a number: gtk integer ID, from the registered idle callback handler.
> >>
> > Well I guess you'd better hope that gtk never returns a zero or one, then.
>
> Why? It won't break my code.
>
> > Note, though, that True and False are defined to be singleton instances,
> > so it *is* permissible to say
> >
> >  if i is False:
> >
> > >>> 0 is False
> > False
> > >>> 1 is True
> > False
> > >>>
> >
> > However I must say the coupling in that interface has a very definite
> > code smell. Why not use two variables, a Boolean "registered" and an
> > integer ID that is meaningless when registered is False?
>
> Because the integer ID can be meaningless when registered is True.
> If I should use two variables, the "registered" variable should
> be a three value variable. Something like:
>
>   0: Not registered by the user
>   1: Registered by the user but no internal idle callback registerd
>   2: internal idle callback registerd
>
> Only in the last case is the integer ID meaningfull. But IMO I buy
> nothing buy seperating the information over two variables. Checking
> whether the "registered" variable is 2 or not, doesn't buy me
> anything over checking whether the cb_src is of BooleanType or
> not.
>
> And having the information in one variable means I have to worry
> less about synchronisation. If I register the internal idle
> handler I just store its ID in cb_src, without having to worry
> about another variable that has to be set right.
>

This is the sort of horrible smelly wretchedness that makes me gag in
C. Bearing in mind that you of course are free to write your code in
whatever way you want, and I'm not your boss, this is horrible and
shouldn't be considered something to be catered for.

First and most importantly, you're replacing a literate,
self-documenting mechanism with an obtuse one.

if self.userRegisteredCallback:

is much, much better than

if type(self.callback) is bool:


If you have a consistent API and you're checking for error values from
your GTK functions, then you already have a lot more code than using 2
varaibles will cost you. 10 lines, maybe.

The fact that you think setting two variables is "too hard" but you're
perfectly happy with checking for boolean types instead just testing
truth values I think is a real problem. You aren't saving yourself any
performance. You're barely even saving yourself any typing, and you're
making your code (intentionally, it seems) that much more compllicated
and hard to understand.

Granted, of course, it's your code. But I wouldn't accept it in
anything I was in charge of.


> --
> Antoon Pardon
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why and how "there is only one way to do something"?

2005-12-15 Thread Chris Mellon
On 15 Dec 2005 04:32:39 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> [EMAIL PROTECTED] wrote:
> > Tolga wrote:
> > > As far as I know, Perl is known as "there are many ways to do
> > > something" and Python is known as "there is only one way". Could you
> > > please explain this? How is this possible and is it *really* a good
> > > concept?
> >
> > if you 'import this', you get a bit of Python Zen... from which I have
> > taken this line:
> > *...
> > There should be one-- and preferably only one --obvious way to do it.
> > ...*
> > If this is what you are referring to then here is an explanation.
> >
> > So there is not 'only one way', but rather there should be a way to do
> > something that is obvious, re easy to find, evident, 'given'...
> > The quality(ies) looked for here that makes this *really* good is
> > 1- that you don't spend an inordinate amount of time looking for it -
> > you just go along and use it so your mind can be focussed of what you
> > need to achieve instead of how you can achieve it.
> > 2- If it's 'obvious', then chances are others will see it and use it
> > also, so that their code is more understandable by others. For anyone
> > who has taken care of code of others this can be *really really good*
> > ;-)
> What I don't quite understand is, if it is "obvious", whether there is
> a Zen, people would still code it that way(unless of course they want
> to hide it from others or make it difficult to understand on purpose),
> there won't be any argument of "which one is the obvious way".
> And if there is an argument(or disagreement), which one is the obvious
> ?
>

Many programmers, being clever people, like to do clever things in
order to prove how clever they are. Python programmers are not immune
to this but Perl programmers absolutely revel in it.

As you may be able to tell, I place a very large value on readability
and obviousness and I despise cleverness in code and attempt to stamp
it out when I do it (although, of course, it's hard to see when you're
violating your own rules). As an example, if someone posts on this
list asking how to print the lines of a file, they'll probably get a
bunch of answers with the obvious for loop solution, and a couple from
people being clever with list comprehensions. Even the clever list
comprehension people will usually use the for loop in real code.
Asking the same question on a Perl list will result in 30 different
aswers from 20 different people, and all 30 of those will be used in
real code.

When there is one obvious way to do things, it makes for a large
degree of consistency in code. It improves the readability and
maintainability of Python code in general and flattens the learning
curve. When there is *only* one obvious way to do something, it's even
better.

By and large, programmers are smart people who enjoy solving problems.
That means that doing clever, different ways of doing things is like
candy to programmers and a real temptation. I'm no exception - I
started using perl very early in my programming career and I loved
using all the line noise and cute operators in clever ways. It took
time and some effort to drop that portion of ego from my code and
instead take pride in how mundane, straightforward, and obvious I
could make it, rather than how clever and tricky it was.

And thats why I love the "only one way to do it" thing in Python ;)

> I think it is more like there is a preferred way, by the language
> creator and those share his view.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why and how "there is only one way to do something"?

2005-12-15 Thread Chris Mellon
On 15 Dec 2005 05:08:02 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> Chris Mellon wrote:
> > On 15 Dec 2005 04:32:39 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > >
> > > [EMAIL PROTECTED] wrote:
> > > > Tolga wrote:
> > > > > As far as I know, Perl is known as "there are many ways to do
> > > > > something" and Python is known as "there is only one way". Could you
> > > > > please explain this? How is this possible and is it *really* a good
> > > > > concept?
> > > >
> > > > if you 'import this', you get a bit of Python Zen... from which I have
> > > > taken this line:
> > > > *...
> > > > There should be one-- and preferably only one --obvious way to do it.
> > > > ...*
> > > > If this is what you are referring to then here is an explanation.
> > > >
> > > > So there is not 'only one way', but rather there should be a way to do
> > > > something that is obvious, re easy to find, evident, 'given'...
> > > > The quality(ies) looked for here that makes this *really* good is
> > > > 1- that you don't spend an inordinate amount of time looking for it -
> > > > you just go along and use it so your mind can be focussed of what you
> > > > need to achieve instead of how you can achieve it.
> > > > 2- If it's 'obvious', then chances are others will see it and use it
> > > > also, so that their code is more understandable by others. For anyone
> > > > who has taken care of code of others this can be *really really good*
> > > > ;-)
> > > What I don't quite understand is, if it is "obvious", whether there is
> > > a Zen, people would still code it that way(unless of course they want
> > > to hide it from others or make it difficult to understand on purpose),
> > > there won't be any argument of "which one is the obvious way".
> > > And if there is an argument(or disagreement), which one is the obvious
> > > ?
> > >
> >
> > Many programmers, being clever people, like to do clever things in
> > order to prove how clever they are. Python programmers are not immune
> > to this but Perl programmers absolutely revel in it.
> >
> > As you may be able to tell, I place a very large value on readability
> > and obviousness and I despise cleverness in code and attempt to stamp
> > it out when I do it (although, of course, it's hard to see when you're
> > violating your own rules). As an example, if someone posts on this
> > list asking how to print the lines of a file, they'll probably get a
> > bunch of answers with the obvious for loop solution, and a couple from
> > people being clever with list comprehensions. Even the clever list
> > comprehension people will usually use the for loop in real code.
> > Asking the same question on a Perl list will result in 30 different
> > aswers from 20 different people, and all 30 of those will be used in
> > real code.
> >
> > When there is one obvious way to do things, it makes for a large
> > degree of consistency in code. It improves the readability and
> > maintainability of Python code in general and flattens the learning
> > curve. When there is *only* one obvious way to do something, it's even
> > better.
> >
> > By and large, programmers are smart people who enjoy solving problems.
> > That means that doing clever, different ways of doing things is like
> > candy to programmers and a real temptation. I'm no exception - I
> > started using perl very early in my programming career and I loved
> > using all the line noise and cute operators in clever ways. It took
> > time and some effort to drop that portion of ego from my code and
> > instead take pride in how mundane, straightforward, and obvious I
> > could make it, rather than how clever and tricky it was.
> >
> > And thats why I love the "only one way to do it" thing in Python ;)
> >
> It is perfectly ok to define coding policy within an organisation, for
> a project that have more than one developer and things like that. But
> if the language allows more than one way to do it, people would try if
> that is what they want and they can.

You can never stop people from being clever. You can only encourage
them to improve themselves. It's like when a teenager finally realizes
that exactly how many studs he has on his jacket really isn't that
important. (Am I dating m

Re: IsString

2005-12-15 Thread Chris Mellon

> Terminology is important, because we understand the world through
> language. If your language is confused or misleading, your understanding
> will also be confused or incomplete.

I think the issue is pretty simple, myself:

With mutable objects, Python has the semantics normally associated
with pass-by-reference.

With immutable objects, Python has the semantics normally associated
with pass-by-value.

So you could say that Python has both pass-by reference and
pass-by-value (modulo the fact that pass-by-reference doesn't exist at
some level, and is a semantic layer on top of pass-by-value. But
semantics are what we're talking about here).

However, there is *no way* in Python to get pass-by-value semantics
with a mutable object, or pass-by-reference semantics with an
immutable one (you can build your own scaffolding to mimic it, but the
language won't change it's semantics for you).

Therefore, it's more correct to say that Python has neither
pass-by-reference semantics or pass-by-value semantics, but some third
thing. And thus the name pass-by-object, where the calling semantics
are that you always get a reference to an object, but what (if any)
other names are bound to that object, or if they can be bound to that
object, depends on the object.

When you can pass a mutable int to a function (not pass a
namespace/name pair, but a real live mutable int), then Python will
have pass-by-reference.

When you can pass a list that isn't a shared reference without
explicitly copying it or subclassing it to be immutable, then Python
will have pass-by-value.

In the meantime, it has pass-by-object.

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


Re: IsString

2005-12-15 Thread Chris Mellon
On 12/15/05, Chris Mellon <[EMAIL PROTECTED]> wrote:
> 
> > Terminology is important, because we understand the world through
> > language. If your language is confused or misleading, your understanding
> > will also be confused or incomplete.
>
> I think the issue is pretty simple, myself:
>
> With mutable objects, Python has the semantics normally associated
> with pass-by-reference.
>
> With immutable objects, Python has the semantics normally associated
> with pass-by-value.


Meant to include this in first post:

This is all you have to know to use Python, even very advanced Python.
Everything after this point is basically comp-sci trivia and argument
about definitions.

>
> So you could say that Python has both pass-by reference and
> pass-by-value (modulo the fact that pass-by-reference doesn't exist at
> some level, and is a semantic layer on top of pass-by-value. But
> semantics are what we're talking about here).
>
> However, there is *no way* in Python to get pass-by-value semantics
> with a mutable object, or pass-by-reference semantics with an
> immutable one (you can build your own scaffolding to mimic it, but the
> language won't change it's semantics for you).
>
> Therefore, it's more correct to say that Python has neither
> pass-by-reference semantics or pass-by-value semantics, but some third
> thing. And thus the name pass-by-object, where the calling semantics
> are that you always get a reference to an object, but what (if any)
> other names are bound to that object, or if they can be bound to that
> object, depends on the object.
>
> When you can pass a mutable int to a function (not pass a
> namespace/name pair, but a real live mutable int), then Python will
> have pass-by-reference.
>
> When you can pass a list that isn't a shared reference without
> explicitly copying it or subclassing it to be immutable, then Python
> will have pass-by-value.
>
> In the meantime, it has pass-by-object.
>
> >
> >
> >
> > --
> > Steven.
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-12-25 Thread Chris Mellon
On 12/25/05, Peter Maas <[EMAIL PROTECTED]> wrote:
> yepp schrieb:
> > Once you got the model of free and open source software you can't but shake
> > your head at obfuscating people treating their users as enemies.
>
> Sorry but this is naive nonsense. Open source is a good model but
> it can't be applied everywhere. Look at the following example:
>
> There is a company who is developing and marketing a single application.
> It is a simulation software for industrial processes which embodies an
> enormous amount of knowledge accumulated by the hard work of many
> individuals since about twenty years, algorithmic, process, implementation,
> market knowlegde. This application is of great value to the customers
> because it helps them save lots of money and improve the quality of their
> products. No wonder that they have (and are willing) to pay a considerable
> price for it.
>

You just described UNIX, which has been all but replaced by open
source projects, and the general state of the operating system market
a few decades ago.

> If the company would decide to go open source it would be dead very soon
> because it wouldn't no longer have a competitive advantage. Most customers
> wouldn't see the necessity to pay high prices, the competition would use
> the source code in their own products, the earnings would fall rapidly and
> there wouldn't be enough money availabe to pay highly skilled developpers,
> engineers and scientists for continued development.
>
> In certain sense suppliers and customers ARE enemies because they have
> different interests. The customer will pay a price only if it is neccessary
> to get the product. If he can get it legally for nothing he won't pay anything
> or at least not enough.
>
> So please: continue praising OSS (as I do) but don't make ideological claims
> that it fits everywhere.

You're looking at the wrong things here. What you're describing is
actually a potentially very successfull open source project - many
companies, single source, highly technical, high price. An open source
project could easily succeed in this area. Of course, it would not be
in the interest of the current monopoly supplier to open source thier
product. But a third party that started such a project could quite
possibly succeed. Not that it neccesarily would, knowing what I know
about business - hell, I can't even get approval to use Eclipse on a
couple desktops.

>
> Peter Maas, Aachen
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP: method overriding works in mysterious ways?

2006-01-03 Thread Chris Mellon
On 1/2/06, Mike Meyer <[EMAIL PROTECTED]> wrote:
> "John M. Gabriele" <[EMAIL PROTECTED]> writes:
>
> > Consider the following:
> >
> > #!/usr/bin/python
> >
> > #-
> > class Grand_parent( object ):
> >
> >  def speak( self ):
> >  print 'Grand_parent.speak()'
> >  self.advise()
> >
> >  def advise( self ):
> >  print 'Grand_parent.advise()'
> >  self.critique()
> >
> >  def critique( self ):
> >  print 'Grand_parent.critique()'
> >
> >
> > #-
> > class Parent( Grand_parent ):
> >
> >  def speak( self ):
> >  print '\tParent.speak()'
> >  self.advise()
> >
> >  def advise( self ):
> >  print '\tParent.advise()'
> >  self.critique()
> >
> >  # ATM, the Parent is at a loss for words, and has no critique.
> >
> >
> > #-
> > class Child( Parent ):
> >
> >  def speak( self ):
> >  print '\t\tChild.speak()'
> >  self.advise()
> >
> >  # Currently, the Child has no really useful advice to give.
> >
> >  def critique( self ):
> >  print '\t\tChild.critique()'
> >
> >
> > #-
> > print 'speak() calls advise(), then advise() calls critique().'
> > print
> >
> > people = [ Grand_parent(), Parent(), Child() ]
> > for person in people:
> >  person.speak()
> >  print
> >
> >
> >
> > 
> > The output is:
> >
> > speak() calls advise(), then advise() calls critique().
> >
> > Grand_parent.speak()
> > Grand_parent.advise()
> > Grand_parent.critique()
> >
> >  Parent.speak()
> >  Parent.advise()
> > Grand_parent.critique()
> >
> >  Child.speak()
> >  Parent.advise()
> >  Child.critique()
> >
> >
> > What's going on here with that last "Child.critique()"? The
> > Parent called self.critique(), and since it *had* no critique()
> > method, it should've deferred to it's parent's critique()
> > method, right? But instead, somehow Child.critique() got called.
> > Why?
>
> Because that's the way Python searchs for object attributes. Nobody
> made it explicit, so I will. This is simplified, ignoring various
> complications:
>
> When looking up a value for self.foo, you first look for
> attribute foo of self. You then check the class of self for
> attribute foo. You then check the parent class of the last
> class you checked for attribute foo. You repeat that last step
> until there is no parent class.
>
> Like I said, that's simplified. But it's sufficent to explain what
> you're seeing.

If your interested in the non-simplified complicated rules for exactly
how methods are looked up (only different than the simple case when
you get into multiple inheritence), see
http://www.python.org/2.3/mro.html

>
> --
> Mike Meyer <[EMAIL PROTECTED]>  
> http://www.mired.org/home/mwm/
> Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with WX and program loop...

2006-01-11 Thread Chris Mellon
On 11 Jan 2006 10:33:08 -0800, Mr BigSmoke <[EMAIL PROTECTED]> wrote:
> Hi everybody... I have an app that has to controll some ascii files
> every 10/30 seconds... I was planning to have an GUI using wxpython.
> The problems is that i wasn't able to manage my application loop and
> the wxApp loop, so my interface is always freezing...
> My app do something like this:
> - creates a new wx and wxframe instance
> - loads some configuration info
> - starts looping every 30 seconds (while True: sleep(30); do something,
> bla,bla)
> - update some labels and textboxes on my frame...
>
> On every loop step, if i find some info in those ascii files i want to
> change some labels on my wxFrame... But my frame just freezes...
> because of the loop.
>
> Any hint?
>
> I'll post some of the code down here...
>

Welcome to the exciting world of event-based programming ;)

You want to use a wx.Timer to trigger your event every 30 seconds
instead of sleeping.



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


Re: Implied instance attribute creation when referencing a class attribute

2006-01-16 Thread Chris Mellon
On 16 Jan 2006 14:11:25 -0800, Russell Warren <[EMAIL PROTECTED]> wrote:
> I just ran across a case which seems like an odd exception to either
> what I understand as the "normal" variable lookup scheme in an
> instance/object heirarchy, or to the rules regarding variable usage
> before creation.  Check this out:
>
> >>> class foo(object):
> ...   I = 1
> ...   def __init__(self):
> ... print self.__dict__
> ... self.I += 1
> ... print self.__dict__
> ...
> >>> a=foo()
> {}
> {'I': 2}
> >>> foo.I
> 1
> >>> a.I
> 2
> >>> del a.I
> >>> a.I
> 1
> >>> del a.I
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: I
> >>> non_existent_var += 1
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'non_existent_var' is not defined
>
>
> In this case, 'self.I += 1' clearly has inserted a surprise
> behind-the-scenes step of 'self.I = foo.I', and it is this which I find
> interesting.
>
> As I understand it, asking for self.I at this point should check
> self.__dict__ for an 'I' entry, and if it doesn't find it, head on up
> to foo.__dict__ and look for it.
>
> So... I initially *thought* there were two possibilities for what would
> happen with the 'self.I += 1':
>   1. 'self.I += 1' would get a hold of 'foo.I' and increment it
>   2. I'd get an AttributeError
>
> Both were wrong.  I thought maybe an AttributeError because trying to
> modify 'self.I' at that point in the code is a bit fuzzy... ie: am I
> really trying to deal with foo.I (in which case, I should properly use
> foo.I) or am I trying to reference an instance attribute named I (in
> which case I should really create it explicitly first or get an error
> as with the non_existent_var example above... maybe with 'self.I =
> foo.I').
>
> Python is obviously assuming the latter and is "helping" you by
> automatically doing the 'self.I = foo.I' for you.  Now that I know this
> I (hopefully) won't make this mistake again, but doing this seems
> equivalent to taking my 'non_existent_var += 1' example above and
> having the interpreter interpret as "oh, you must want to deal with an
> integer, so I'll just create one for you with 'non_existent_var = 0'
> first".  Fortunately this is not done, so why do it with the instance
> attribute reference?
>
> Does anyone have any solid reasoning behind the Python behavior?  It
> might help drive it home more so than just taking it as "that's the way
> it is" and remembering it.
>
> It gets even more confusing for me because the behaviour could be
> viewed as being opposite when dealing with mutable class members.  eg:
>
> >>> class foo(object):
> ...   M = [1,2,3]
> ...   def __init__(self):
> ... self.M.append(len(self.M) + 1)
> ... print self.M
> ...
> >>> a=foo()
> [1, 2, 3, 4]
> >>> foo.M
> [1, 2, 3, 4]
> >>> del a.M
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'foo' object attribute 'M' is read-only
>
> By opposite I mean that with immutable objects, a sloppy self.I
> reference doesn't get you to the base class object, whereas with a
> mutable one you do get to the base object (although I do recognize that
> in both cases if you just remember that the interpreter will always
> stuff in a 'self.x = BaseClass.x' it works as expected in both the
> immutable and mutable case).
>
> After all that, I guess it boils down to me thinking that the code
> *should* interpret the attempted instance modification with one of the
> two possibilities I mentioned above (although after typing this I'm now
> leaning more towards an AttributeError rather than allowing 'self.I' to
> be synonymous with 'foo.I' if no local override).

I can see how this can be confusing, but I think the confusion here is
yours, not Pythons ;)

self.I += 10 is an *assignment*. Like any assignment, it causes the
attribute in question to be created. You wouldn't be suprised if you'd
done self.I='foo' and had it "create" the instance attribute, would
you?

If you write out the longhand for += it becomes totally obvious what
is happening and why it makes sense:

temp = self.I (ends up returning value bound to foo.I)
temp = temp+10 #if temp were mutable, this would modify it instead of
creating a new object
self.I = temp (binds name "I" in namespace "self" to the value bound
to temp, which will shadow the class attribute)

Note that nowhere is Python "inserting self.I = foo.I" for you - you
are (implicitly) retrieving the class attribute, and then inserting
that value into the instance attribute.

So your case 1 is actually exactly what is happening! Python is
getting a hold of foo.I and incrementing it (which you can see
happening when you use a mutable object). The bit you're missing is
after that, where you're then binding that value into the instance
attribute.


>
> Russ
>
> PS: Apologies if I mangled the "proper" terminology for talking about
> this... hopefully it makes sense.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http:/

Re: Python code written in 1998, how to improve/change it?

2006-01-19 Thread Chris Mellon
On 19 Jan 2006 15:53:54 -0800, Petr Jakes <[EMAIL PROTECTED]> wrote:
> Thanks for your comments,
> The mentioned "8 years old" code actually works somehow.
>
> I am trying to solve very similar problem about FSM as the code in the
> example does and I do not want to be overburden by the if/elif stuff or
> by declaring state functions (which IMHO is very similar approach as
> if/elif).
>

I'm not sure why nobody else in this thread said it, but the most
common way of implementing state machines I've seen in Python (unless
theres only a couple states you can manage with if/elif) is to use a
dict to map states to callables.



> Because of above mentioned, something like FSM-generator looks as a way
> to go for me (if I can judge with my poor skills).
>
> I am using Steve's book "Python Web Programming" which is actually the
> best I have found about OOP, classes etc. but as a newbie I am just
> lost with subclass and mapping attributes etc. while trying to study
> the code in the example (http://tinyurl.com/a4zkn).
>
> All I wanted to know, if, thanks to the improvements in the Python
> functionality over the years, it is possible to simplify somhow the old
> code.
>
> Otherwise I have to dig through :)
>
> Petr Jakes
>
> PS:
> I agree and I do understand the reasons why NOT to use GOTO statements
> in the code (aka spaghetti code).
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having trouble using CTypes with a custom function

2006-10-04 Thread Chris Mellon
On 4 Oct 2006 11:18:16 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I just started looking at Python's ctypes lib and I am having trouble
> using it for a function.
>
> For starters, here's my Python code:
>
>
> from ctypes import*;
> myStringDLL= cdll.LoadLibrary("myStringDLL.dll");
>
> GetMyString = getattr(myStringDLL,
> "?GetMyString@@[EMAIL PROTECTED]@[EMAIL PROTECTED]@@[EMAIL 
> PROTECTED]@2@@std@@@Z")
>
> strString =  create_string_buffer('\000' * 256);
> GetMyString.restype = c_int;
> GetMyString.argtypes = [c_char_p];
>
> bResult = GetMyString (strSerialNumber);
>
> print (bResult);
> print (strSerialNumber);
>
> #C++ Prototype of the function I want to call:
> #bool GetMyString (string& stringParam) ;
>
>
>
>
> I do not have access to the source code of this function so don't ask
> me to try different things in C++.  This DLL is working fine.
>
> The problem that I have is that print (strSerialNumber) does not seem
> to print the correct string.  What I get is some garbage value of
> unprintable characters.  Am I using this the correct way?
>




This function is expecting a C++ std::string object, not a regular C
style string. You'll need a wrapper function, and one which uses the
same compiler and STL as the C++ source.

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


Re: Having trouble using CTypes with a custom function

2006-10-04 Thread Chris Mellon


On 4 Oct 2006 11:35:11 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Would you have any example of a wrapper for such data types?
>
> Thanks.
>
> Chris Mellon wrote:
> > On 4 Oct 2006 11:18:16 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> > > Hi all.
> > >
> > > I just started looking at Python's ctypes lib and I am having trouble
> > > using it for a function.
> > >
> > > For starters, here's my Python code:
> > >
> > >
> > > from ctypes import*;
> > > myStringDLL= cdll.LoadLibrary("myStringDLL.dll");
> > >
> > > GetMyString = getattr(myStringDLL,
> > > "?GetMyString@@[EMAIL PROTECTED]@[EMAIL PROTECTED]@@[EMAIL 
> > > PROTECTED]@2@@std@@@Z")
> > >
> > > strString =  create_string_buffer('\000' * 256);
> > > GetMyString.restype = c_int;
> > > GetMyString.argtypes = [c_char_p];
> > >
> > > bResult = GetMyString (strSerialNumber);
> > >
> > > print (bResult);
> > > print (strSerialNumber);
> > >
> > > #C++ Prototype of the function I want to call:
> > > #bool GetMyString (string& stringParam) ;
> > >
> > >
> > >
> > >
> > > I do not have access to the source code of this function so don't ask
> > > me to try different things in C++.  This DLL is working fine.
> > >
> > > The problem that I have is that print (strSerialNumber) does not seem
> > > to print the correct string.  What I get is some garbage value of
> > > unprintable characters.  Am I using this the correct way?
> > >
> >
> >
> >
> >
> > This function is expecting a C++ std::string object, not a regular C
> > style string. You'll need a wrapper function, and one which uses the
> > same compiler and STL as the C++ source.
> >
> > > Thanks.
> > >
> > > --
> > > http://mail.python.org/mailman/listinfo/python-list
> > >
>

in this case it'd be very simple:

bool WrapGetMyString(char * c) {
  return GetMyString(c)
}


(Note: This isn't unicode safe).

The C++ compiler will handle converting from the char * to the std::string.





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


Re: Initialization of variables using no-arg constructor

2006-10-09 Thread Chris Mellon
On 10/9/06, Edward Waugh <[EMAIL PROTECTED]> wrote:
> Consider the following (working) Python code:
>
> import sys
>
> def sum(list):
> # total = 0 does not work for non-numeric types
> total = list[0].__class__()
> for v in list:
> total += v
> return total
>
> l = [1, 2, 3]
> print sum(l)
>
> l = [1.1, 2.2, 3.3]
> print sum(l)
>
> l = ["a", "b", "c"]
> print sum(l)
>
> In order for sum() to be generic I initialize total to the value of
> list[0].__class__().  This works but I would like to know if this is the
> correct or preferred way of doing it.  It means that sum() must be given a
> list whose elements are types or classes that have a no-arg constructor
> (through this is probably almost always the case).
>

I'd do this:

>>> def sum(list):
... total = list[0]
... for v in list[1:]:
... total += v
... return total

I'm not sure if regular slice notation makes a copy of the list or
not, if it does you can use itertools:

>>> def sum(list):
... total = list[0]
... for v in itertools.islice(list, 1, len(list)):
... total += v
... return total


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


Re: Can I use decorators to manipulate return type or create methods?

2006-10-19 Thread Chris Mellon
On 19 Oct 2006 06:43:49 -0700, WakeBdr <[EMAIL PROTECTED]> wrote:
> I'm writing a class that will query a database for some data and return
> the result to the caller.  I need to be able to return the result of
> the query in several different ways: list, xml, dictionary, etc.  I was
> wondering if I can use decorators to accomplish this.
>
> For instance, I have the following method
>
> def getUsers(self, params):
> return users.query(dbc)
>
> To get the appropriate return types, I also have these methods.  I have
> these convenience methods for every query method in my class.
>
> def getUsersAsXML(self, params):
> return self._toXML(self.getUsers(params))
> def getUsersAsDict(self, params):
> return self._toDict(self.getUsers(params))
> def getUsersAsList(self, params):
> return self._toList(self.getUsers(params))
>
> Instead of creating these three methods for every query method, is
> there a way to use decorators to manipulate the return type.  I'd still
> like to have the caller use getUsersAsXML, I just don't want to write
> the AsXML methods for every query method.  So the decorator would
> essentially create the convenience methods instead of me coding them.
>
> One solution that I don't want to use is passing a variable into the
> query method that determines the return type.  This is what I don't
> want to do.
> def getUsers(self, params, returnType):
>
> Any ideas on how I can accomplish this?


You can't do it as fully magically as I'd like, because at the time
decorators are run, the methods are just functions and aren't bound as
methods yet (so you can't automagically add methods to the class, for
example - you'd need to do that after the class definition finishes
executing). You *could* decorate all the functions you want to have
special return types, then (after the class definition) loop through
those to generate the extra return funcs.

You can do it with a minimum of boilerplate this way:

from functools import wraps #only in 2.5, you can do this by hand in 2.4
#wrapped is the function we're calling and returning as XML
#xmlfunc is the stub function we're replacing
def returnXML(wrapped):
def f(xmlfunc):
@wraps(xmlfunc)
def xmlMethod(self):
return self.asXML(wrapped(self))
return xmlMethod
return f

class T(object):
def getUser(self):
return "user"
def asXML(self, data):
return "%s"%(data)
@returnXML(getUser)
def getUserAsXML(self):pass



t = T()
print t.getUserAsXML()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending Dictionary via Network

2006-10-25 Thread Chris Mellon
On 24 Oct 2006 16:56:43 -0700, Simon Forman <[EMAIL PROTECTED]> wrote:
>
> mumebuhi wrote:
> > Thank you very much for the reply.
> >
> > Can pickle work directly with socket? The way I am doing right now is
> > to pickle the object to a file then send the file content through the
> > socket.
>
> Pickle aso has dumps() and loads() to work with strings rather than
> files.


I would recommend against using pickle if you're going to push it over
a network - there are signifigant dangers in unpickling anything
untrusted.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ini files and plugins

2006-11-16 Thread Chris Mellon
On 11/16/06, tool69 <[EMAIL PROTECTED]> wrote:
> Hi,
> I've made a basic LaTeX file editor in wxPython, but now I wanted to add
> it some features :
>
> 1 -  create a sort of ini file where I can put the user configuration
> that will load itself on the application startup ;

wxPython includes a configuration management system, it's a bit more
powerful and flexible than just using ConfigParser. See the wx.Config
classes (I believe theres some code in the demo as well)

> 2 -  a simple plugin system with python files ( maybe to add new
> langages, etc.) ;
>
> I'm looking for simple articles, modules or code snippets on these
> subjects;
> thanks,
> 6TooL9
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ctypes and freeing memory

2006-10-03 Thread Chris Mellon
On 10/3/06, Oliver Andrich <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> I am currently playing around with ctypes and a C library (libWand
> from ImageMagick), and as I want to easily deploy it on Mac, Linux and
> Windows, I prefer a ctypes solution over a C module. At least on
> windows, I would have resource problems to compile the C module. So,
> ctypes is the perfect choice for me.
>
> But I am currently encountering a pattern inside the C library, that
> has to be used to free memory. Coding in C I have to do the following
>
> char *description;
> long  severity;
>
> description = MagickGetException(wand, &severity);
> /*
> do something with the description: print it, log it, ...
> */
> description = (char *) MagickRelinquishMemory(description);
> exit(-1); /* or something else what I want to after an exception occured 
> */
>
> So, this looks easy and is sensible from C's point of view. Now I try
> to translate this to Python and ctypes.
>
> dll.MagickGetException.argtypes = [c_long, POINTER(c_long)]
> dll.MagickGetException.restype  = c_char_p
>
> severity = c_long()
> description = dll.MagickGetException(byref(severity))
>
> # So far so good. The above works like a charm, but the problem follows 
> now
> # ctypes already converted the char * for description to a String object.
> # That means description has arrived in an area under Python's control.
>
> # these definitions are the easy part
> dll.MagickRelinquishMemory.argtypes = [c_void_p]
> dll.MagickRelinquishMemory.restype  = c_char_p
>
> # but this obviously must cause problems and causes problems
> dll.MagickRelinquishMemory(description)
>
> So, my question is, how do I deal with this situation? Can I ignore
> the call to MagickRelinquishMemory, cause Python takes care of the
> resources already? Or is it impossible to use it at all, and I have to
> think about a different solution?
>

Not a ctypes expert but I can pretty much guaranteee that Python won't
correctly release that memory by itself. Are you sure that description
is actually a string object?

By my recollection it should be a c_char_p object, and if you pass it
to MagickRelinquishMemory ctypes should do the right thing.

If it doesn't, then you can use a more literal translation of the C
code, and use a c_void_p instead, using ctypes.string_at(description)
to get a string out of the buffer.


> Best regards,
> Oliver
>
> --
> Oliver Andrich <[EMAIL PROTECTED]> --- http://roughbook.de/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt app in seperate thread

2006-11-22 Thread Chris Mellon
On 22 Nov 2006 06:43:55 -0800, anders <[EMAIL PROTECTED]> wrote:
>
> Phil Thompson wrote:
> > On Wednesday 22 November 2006 2:06 pm, anders wrote:
> > > Phil Thompson wrote:
> > > > On Wednesday 22 November 2006 12:37 pm, anders wrote:
> > > > > I am writing a plugin for a piece of software in python, and I want to
> > > > > start up a PyQt GUI in the plugin, without stalling the main thread
> > > > > while the gui is running (later i will want to pass messages between
> > > > > the main thread and the gui thread).
> > > > >
> > > > > I'm new to pyqt, so I'm probably doing something very silly, but for
> > > > > the moment I'm just trying to get the first pyqt tutorial example
> > > > > running in a seperate thread:
> > > > >
> > > > > 8<
> > > > >
> > > > > import sys
> > > > > from PyQt4 import QtGui
> > > > > from PyQt4 import QtCore
> > > > >
> > > > > class MyThread( QtCore.QThread ):
> > > > > def __init__( self ):
> > > > > QtCore.QThread.__init__( self )
> > > > >
> > > > > def run( self ):
> > > > > app = QtGui.QApplication( sys.argv )
> > > > > hello = QtGui.QPushButton( 'Hello world!' )
> > > > > hello.resize( 500, 500 )
> > > > > hello.show()
> > > > > app.exec_()
> > > > > QtCore.QThread.terminate(  )
> > > > >
> > > > >
> > > > >
> > > > > mt = MyThread()
> > > > > mt.start()
> > > > > print 'Main thread continuing...'
> > > > > mt.wait()
> > > > > print 'GUI thread finished.'
> > > > >
> > > > > 8<
> > > > >
> > > > > The app starts up (with a warning WARNING: QApplication was not 
> > > > > created
> > > > > in the main() thread. ). I get a window, but no button, and clicking 
> > > > > on
> > > > > the close button does nothing and I have to force the program to quit.
> > > > >
> > > > > There's got to be a way to get this working, right? Can anyone help me
> > > > > along the right path?
> > > >
> > > > Read http://doc.trolltech.com/4.2/threads.html
> > > >
> > > > In particular the bit that says that exec_() must be called from the 
> > > > main
> > > > thread and not from a QThread.
> > > >
> > > > Phil
> > >
> > > OK so that's all good... so how do I go about doing what I want then?
> > > Can I set up a window in the second thread and start its event loop
> > > without running the event loop in the core app?
> >
> > No. Read the second sentence of the paragraph I referred to. Also read the
> > section "QObject Reentrancy".
> >
> > Phil
>
> OK I see that now. Thanks for pointing that out. So basically, I can't
> do what I want at all. That's a bit of a pain. Is there no way of
> tricking Qt into thinking I'm running it in the main thread?
>

It's possible with hackery from C++ but I seriously doubt you can do
it from PyQt.


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


Re: Abelson and Python

2006-11-24 Thread Chris Mellon
On 11/23/06, Scott David Daniels <[EMAIL PROTECTED]> wrote:
> markscottwright wrote:
> > Fredrik Lundh wrote:
> >> markscottwright wrote:
> >>
> >>  > If it were that easy, the PyPy guys would be done by now.
> >>
> >> if the PyPy guys had focused on writing a Python interpreter in Python,
> >> they'd been done by now.
> >>
> >> 
> >
> > Isn't that the point of PyPy?  It's what their mission statement says
> > (http://codespeak.net/pypy/dist/pypy/doc/architecture.html#mission-statement):
> >
> > "PyPy is an implementation of the Python programming language written
> > in Python itself, flexible and easy to experiment with."
> >
> > This is something that is amazingly easy to do in scheme, since the
> > language is so simple, but is typically pretty difficult to do in other
> > languages
> >
> > That said, I see now that the course we're talking about isn't the same
> > as the old 6.001 course, and presumably has different pedagogical goals.
> >
> There are a more than a few library functions in the Python code that
> are written in C in CPython.  Not only is PyPy trying to get the
> _entire_ Python system into Python, it is trying to do so in a
> friendly-to-translation-in-a-statically-typed-language way.
>
> Besides, if you can freely use "eval" and "exec", how hard is a pure
> python language interpreter?
>

It's pretty trivial, and thats why I've always been unimpressed by
"implemente a  language interpreter in  lines" type statements.
It's a cute toy but what's the real learning  opportunity there?

Now, writing a compiler/interpreter from the ground up is a more
valuable experience, but does it really matter if the language is the
same one you wrote the compiler in? It gets harder the more
complicated the syntax and semantics of the language are, but, say,
python 1.0 would probably be a suitable goal for coursework.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How good is CORBA?

2006-11-27 Thread Chris Mellon
On 11/24/06, Piet van Oostrum <[EMAIL PROTECTED]> wrote:
> >>>>> "Chris Mellon" <[EMAIL PROTECTED]> (CM) wrote:
>
> >CM> FYI: Ice is available under the GPL, so if by "pay" you mean "pay
> >CM> money" that's not your only option. You can also get a commercial
> >CM> license, similiar to Qt.
>
> >CM> I like Ice a lot, it's got hardly any of the ramp up time and learning
> >CM> curve that CORBA does, and it's extremely efficent. If GPL or cash are
> >CM> acceptable licensing options to you, then I encourage you to use it
> >CM> before you head to CORBA.
>
> OmniORB's author did some benchmarking and it appeared that omniORB was
> faster than Ice.

Nowhere did I say that Ice was faster than any given CORBA
implementation. People who want to do benchmark shootouts are on their
own. Ice is quick to learn, easy to use, and fast on the wire. That's
a good step up over CORBA to me.

> --
> Piet van Oostrum <[EMAIL PROTECTED]>
> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
> Private email: [EMAIL PROTECTED]
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


super() and type()

2006-11-27 Thread Chris Mellon
I see super documented, and in use, as below (from the Python documentation)

class C(B):
def meth(self, arg):
super(C, self).meth(arg)

I'd like to not write C all the time, so is there any problem with writing:

class C(B):
def meth(self, arg):
super(type(self), self).meth(arg)


This seems to work in practice but I don't see it used anywhere and
I'm worried what I might be missing.

This was especially brought to my attention because pylint flags the
second usage as invalid, and I'm not sure if it should be considered a
false positive or not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type(foo) == function ?

2006-11-29 Thread Chris Mellon
On 11/29/06, Tom Plunket <[EMAIL PROTECTED]> wrote:
> I'd like to figure out if a given parameter is a function or not.
>
> E.g.
>
> >>> type(1)
> 
> >>> type(1) == int
> True
>
> implies:
>
> >>> def foo():
> ...   pass
> ...
> >>> type(foo)
> 
> >>> type(foo) == function
> Traceback (most recent call last):
>   File "", line 1, in ?
> NameError: name 'function' is not defined
>
> Is there a way I can know if 'foo' is a function?
>

>>> def foo():
... pass
...
>>> from inspect import isfunction
>>> isfunction(foo)
True
>>>


But you probably want the callable() builtin instead.

> thanks,
> -tom!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type(foo) == function ?

2006-11-29 Thread Chris Mellon
On 11/29/06, Tom Plunket <[EMAIL PROTECTED]> wrote:
> Erik Max Francis wrote:
>
> > In dynamically-typed languages in general, explicit typechecks are not
> > a good idea, since they often preclude user-defined objects from being
> > used.  Instead, try performing the call and catch the resulting
> > TypeError:
>
> Good point, although I need to figure out if the thing can be called
> without calling it, so I can build an appropriate UI.  Basically I
> expect three types of things in the 'value' field of the top-level
> dictionary.  The three sorts of things that I will deal with in the UI
> are callable things (e.g. functions, for which Chris Mellon reminds me
> about callable()), mappings (e.g. dictionaries, used similarly to the
> top-level one), and sequences of strings.
>
> So I think callable() works for me in the general case, but now
> trawling the documentation in that area I'm not sure how I can tell if
> something is a mapping or if it's a sequence.
>
> The gist of the UI generation may be envisioned as:
>
> key is the name that gets assigned to the control.
> value indicates that the UI element is a:
>"group box" if the value is a mapping
>series of "radio buttons" if the value is a sequence of strings
>"check box" if the value is a function
>
> ...I've still gotta figure out the exact API, this is for a plugin
> sort of system that'll be used by the manually-driven version of the
> build process and this data is explicitly to build the UI for the
> various tools that are available.
>

Since a sequence can be viewed as a special case of a mapping (a dict
with integer keys) I don't think there's a good general case way to
tell.

You could try indexing it with a string, a sequence will throw a
TypeError, while a mapping will give you a result or a KeyError.

You could also just rely on isinstance() checks.

> thanks,
> -tom!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easier way to express this list slicing?

2006-11-30 Thread Chris Mellon
On 11/30/06, Thomas Ploch <[EMAIL PROTECTED]> wrote:
> John Henry schrieb:
> > If I have a list of say, 10 elements and I need to slice it into
> > irregular size list, I would have to create a bunch of temporary
> > variables and then regroup them afterwords, like:
> >
> > # Just for illustration. Alist can be any existing 10 element list
> > a_list=("",)*10
> > (a,b,c1,c2,c3,d1,d2,d3,d4,d5)=a_list
> > alist=(a,)
> > blist=(b,)
> > clist=(c1,c2,c3)
> > dlist=(d2,d3,d4,d5)
> >
> > That obviously work but do I *really* have to do that?
> >
> > BTW: I know you can do:
> > alist=a_list[0]
> > blist=a_list[1]
> > clist=a_list[2:5]
> > dlist=a_list[5:]
> >
> > but I don't see that it's any better.
> >
> > Can I say something to the effect of:
> >
> > (a,b,c[0:2],d[0:5])=a_list# Obviously this won't work
> >
> > ??
> >
> > I am asking this because I have a section of code that contains *lots*
> > of things like this.  It makes the code very unreadable.
> >
> > Thanks,
> >
>
> Nothing in your code actually __is__ a list. they are all tuples...
> A list is:
> aList = [a,b,c1,c2,c3,d1,d2,d3,d4,d5]
>

True but not relevant, really, he should have said "sequence". But
more importantly,
you don't show what you do with alist, blist,clist,dlist. Without
knowing what the end result is, nobody is going to be able to help you
eliminate the middle steps.

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


Re: Beautiful Soup Question: Filtering Images based on their width and height attributes

2006-11-30 Thread Chris Mellon
On 30 Nov 2006 12:43:45 -0800, PicURLPy <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I want to extract some image links from different html pages, in
> particular i want extract those image tags which height values are
> greater than 200. Is there an elegant way in BeautifulSoup to do this?
>

Most image tags "in the wild" don't have height attributes, you have
to download the image to see what size it is.

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


Re: WxPython

2006-12-04 Thread Chris Mellon
On 3 Dec 2006 04:14:08 -0800, Raja <[EMAIL PROTECTED]> wrote:
> Hi,
>   I am trying to develop an application which would mainly do the
> following 2 things . I would like to know how it can be achieved and
> also the libraries needed for it .
>
> i)  active window tracking
>  In this substate, the application records the title bar
> contents of the active/foreground window
>  and how long, in seconds, that that window is active/in
> the foreground.  If the same window
>  remains in the foreground but the title bar changes (as
> happens with a web browser application)  then a new record is created
> for each new window title.  If a window title is recorded that
>  was previously recorded (on the same date -- see "Data
> Structures" info in section 4.4),
>  then the time should be added to the previously recorded
> active time for that window title.
>  -- Example --
>1) User clicks "Start" -> app enters "recording" state.
>2) User opens window titled "Window 1" -> app looks for
> any prior records for "Window 1"
> on current date.  Finding none, it creates a new
> record.
>3) User opens another window titled "Window 2" -> app
> records total time spent in "Window 1", then looks for any prior
> records for "Window 2" on current date.  Finding none,
>it creates a new record.
>4) User re-raises/re-activates previous window "Window
> 1" -> app records total time spent
>  in  "Window 2", then looks for any prior records for
> "Window 1" on current date.  It finds
>the record created earlier, so no new record is
> created.
>5) User clicks "Stop" (or "Exit") -> the app adds the
> time just spent in "Window 1" to the
> previously recorded time spent in "Window 1".  App
> then returns to "ready" state.
>  ii) idle
>  In this substate, the app has detected that the computer's
> screensaver is active and no time
>  will be recorded for the active/foreground window.  This
> substate is entered automatically
> (from the active window tracking state) when the
> screensaver activates and exited
> automatically (returning to the active window tracking
> state) when the screensaver is
>   deactivated.  Note that this substate should only be
> entered if the app was in the active
> window tracking state when the screensaver activated.
>
>
> Awaiting Your Reply,
> Thank You ,
> Raja.
>


wxPython is a toolkit for writing interfaces, and most of the
functionality you want are systems tasks. wxPython can provide the UI,
but for the system calls you'll need to use the pywin32 module or
ctypes to work directly with the win32 api.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Factory pattern implementation in Python

2006-12-04 Thread Chris Mellon
On 4 Dec 2006 08:39:17 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hi,
>
> I need to parse a binary file produced by an embedded system, whose
> content consists in a set of events laid-out like this:
>
> ...  
>
> Every "event" is a single byte in size, and it indicates how long is
> the associated "data". Thus, to parse all events in the file, I need to
> take it like a stream and read one event at a time, consuming bytes
> according to the event value, and jumping to the next event, until an
> EOF is reached.
>
> Since there are dozens of almost completely heterogeneous events and
> each one of them may imply different actions on the program parsing the
> file, I thought it would be convenient to have one class encapsulating
> the logic for every event. The parser would then sit in a loop,
> creating objects of different classes and calling a method (say
> "execute"). That method (different in every class) is responsible for
> consuming the bytes associated with the event.
>
> Hence, as the class the parser needs to instantiate in each iteration
> is not known in advance, a factory should be implemented. Somehow the
> factory should know how to map an event to a class. I don't know of the
> best way I should do that in Python. I made an attempt along the
> following lines:
>
> 1. Create a base class for the events;
> 2. For every descendant class declare (in the class body) a public
> attribute "eventNum" and assign it the value of the event it will be
> responsible for;
> 3. At runtime, the factory constructor scans the event class hierarchy
> and builds a dictionary mapping "eventNum"'s to classes.
>
> A draft of the implementation follows:
>
> #
>
> #  #
>
> class EvtBase:
>   def __init__(self, file):
> self.file = file
>
>   def execute(self):
> pass
>
> class Evt1(EvtBase):
>   eventNum = 1
>   def execute(self):
> ...
>
> class Evt2(EvtBase):
>   eventNum = 2
>   def execute(self):
> ...
>
> ...
>
> class EvtN(EvtBase):
>   eventNum = N
>   def execute(self):
> ...
>
>
> #  #
>
> import inspect
> import events
>
> class Factory:
>   def __isValidEventClass(self, obj):
> if inspect.isclass(obj) and obj != events.EvtBase and \
> events.EvtBase in inspect.getmro(obj):
>   for m in inspect.getmembers(obj):
> if m[0] == 'eventNum':
>   return True
> return False
>
>   def __init__(self):
> self.__eventDict = {}
> for m in inspect.getmembers(events, self.__isValidEventClass):
>   cls = m[1]
>   self.__eventDict.update({cls.eventNum: cls})
>
>   def parseEvents(self, file):
> while not file.eof():
>   ev = file.read(1)
>   self.__eventDict[ev](file).execute()
>
> #
>
> I'm using the inspect module to find the event classes. One drawback of
> this approach is the need to keep the event classes in a module
> different from that of the factory, because the getmembers method
> expects an already parsed object or module. (The advantage is keeping
> the event number near the class declaration.) I've already had to make
> the solution generic and I found it was not straightforward to separate
> the common logic while avoiding the need to keep the factory and the
> events in two distinct modules.
>
> Is there anything better I can do? I don't have enough experience with
> Python, then I don't know whether it offers a more obvious way to
> address my problem.
>

I'd have the classes register themselves rather than trying to find
them. This removes the need to have a common base class (preserves
duck typing) and lets everything communicate via the factory module.

#in module Factory.py

EventMap = {}

#in module events.py

import Factory
class EventHandler:
Factory.EventMap[1] = EventHandler

#in module parser.py

import Factory

handler = Factory.EventMap[event]()
handler.handleEvent(data)


There's probably some way to wrap the registration up in a metaclass
so it's handled implicitly, but I prefer the explicit approach.


> Thanks in advance.
>
> --
> Romulo A. Ceccon
> 'romulo%s\x40yahoo.com.br' % 'ceccon'
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Async callback in python

2006-12-06 Thread Chris Mellon
On 12/4/06, Calvin Spealman <[EMAIL PROTECTED]> wrote:
> On 4 Dec 2006 20:18:22 -0800, Linan <[EMAIL PROTECTED]> wrote:
> > Hi,
> >
> > In javascript, code could be written like this:
> >
> > ...
> >
> > var _p=XMLHttpRequest();
> > _p.open('GET',url,true);
> > _p.send(null);
> > _p.onreadystateChange=function(){
> > if(_p.readyState==4)
> > cb(_p.responseText);
> > }
> > ...
> >
> > This basic AJAX code allows function to be called when it's invoked,
> > without blocking the main process. There is same library asyncore in
> > python. However, I can't validate it's asynchronous through code:
> > class T(asyncore.dispatcher):
> > def __init__(self,host,url):
> > asyncore.dispatcher.__init__(self)
> > self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
> > self.connect((host,80))
> > self.url='GET %s HTTP/1.0\r\n\r\n' % url
> >
> > def handle_connect(self):
> > pass
> >
> > def handle_close(self):
> > self.close()
> >
> > def handle_read(self):
> > print 'READING.'
> > print self.recv(256)
> >
> > def handle_write(self):
> > sent=self.send(self.url)
> > self.url=self.url[sent:]
> >
> > t=T('aVerySlowSite','/')
> > asyncore.loop()
> > for i in range(0,10):
> > print '%d in main process' % i
> > time.sleep(1)
> >
> > Suppose it's asynchronous, couple of '%d in main process' lines should
> > be mixed in the output of T.handle_read(), right? But I found that
> > actually main process was blocked at asyncore.loop(), until the the
> > socket was closed. My questions:
> > 1, Did I do anything wrong?
> > 2, Is it real asynchronous?
> > 3, If not, where to get the real one(s)?
> >
> > Any comment is welcome :)
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
>
> You seem to be confusing the terms "asyncronous" and "threaded".
> Although multi-threading is a way to implement asyncronous software,
> it is not the only or the best way to get those results. Usually the
> term "asyncronous" is attached to non-threaded methods, because
> "multi-threading" is usually just used for those threaded methods.
>
> Thus, solutions like asyncore are ways to allow asyncronous code
> without threading, and usually this involves a loop, as with asyncore,
> and until all the asyncronous operations running in the loop are
> complete, the loop does not end.
>
> If you wanted to have these prints interlaced in the http download,
> you might schedule them as a seperate asyncronous operation.
>
> I hope that helped.
>
> PS - Another, more complete asyncronous framework is the Twisted
> project (http://www.twistedmatrix.com/)
>

In addition to the above, you misinterpret the way the posted
JavaScript works. JavaScript uses a "run to completion" model and, in
browsers, is purely event-based. There is no "main process" to block,
and if you simulate one via a loop, the code you posted won't work.

Except in IE, because it violates the ecmascript standard and will
'call back' from the implementation to the javascript environment
without regard for the current state of that environment.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merits of Lisp vs Python

2006-12-08 Thread Chris Mellon
On 8 Dec 2006 12:23:54 -0800, Stephen Eilert <[EMAIL PROTECTED]> wrote:
>
> Alex Mizrahi escreveu:
>
>
> >
> > we should feed this text to the query-builder.
> > then we should bind ?dept to our variable departament (i'm not sure how this
> > is done in SPARQL, but there should be a way).
> > then we should iterate over results and output HTML. a python-like
> > pseudocode:
> >
> > query = BuildQuery(query_str)
> > query.bind("?dept", departament)
> > results = query.execute()
> > for each rs in results:
> > print "" + htmlesc(rs.get("?fname")) + "" +
> > htmlesc(rs.get("?lname")) + "" + rs.get("?salary") + ""
>
> I just want to add that this kind of HTML mixed with code is something
> that should be avoided, no matter what language is used.
>

results = doQuery(department="Accounting")
for row in results:
for field in ["fname","lname","salary"]:
print "%s" % htmlesc(row[field])

I hide away the binding etc in doQuery as the lisp version does. Note
that in any kind of real code most of the literals that take up the
space are likely to come from elsewhere.

Note how much more trivial it is to change the HTML output of this
version that the lisp - it's a matter of creating a format string,
which you can retrieve from just about anywhere, rather than requiring
a code refactoring. Just because you have macros doesn't mean it makes
sense to use them.


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


Re: Conditional iteration

2006-12-13 Thread Chris Mellon
On 13 Dec 2006 07:47:23 -0800, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> at <[EMAIL PROTECTED]> writes:
> > I have a lot times the following code:
> >
> > for x in [-2, -1, 0, 1, 2, 3, 4]:
> > if x > 0:
> > ... more code...
>
> Use:
>
>  for x in (x in [-2, -1, 0, 1, 2, 3, 4] if x > 0):
>   ... more code ...
> --

or filter:

from itertools import ifilter

for x in ifilter(lambda x: x > 0, [-2, -1, 0, 1, 2, 3, 4]):
...more code...



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


Re: merits of Lisp vs Python

2006-12-14 Thread Chris Mellon
On 12/14/06, Ken Tilton <[EMAIL PROTECTED]> wrote:
>
>
> Andrew Reilly wrote:
> >>  Each skill seems to have a title, a
> > list of annotations, and a list of hints (and a reverse, which I don't
> > understand).
>
> There's the problem.
>
> >  That all looks like data.
>
> No, not reverse, the part you did not understand. I do not mean what the
> code was doing, I meant that it was code.
>
> >  Couldn't you do that with a table
> > containing those fields, and key it off the defskill argument (or even the
> > title?) at startup?
>
> Not the code. In reverse.
>
> >  Then you don't have to worry about re-factoring the
> > code: there's only going to be one piece of code, driven by a table.
>
> What if it turns into an SQL lookup during refactoring?
>
> >
> > I only mentioned interpolation because it seemed likely that you might
> > want to be mutating these strings to be more specific to what your student
> > was actually doing.
>
> Interpolation does not mean what you think it means. :) That's OK, I
> figgered it out. Yes, that is what the program does, it substitutes
> terms from the student's problem to produce a hint or annotation. The
> function is called "expand". Because the text is like a macro. :)
>
> >  I didn't expect that "42" was necessarily the right
> > answer...
>
> No, but it so happens any #STR...# token is a literal bit of math
> encoded as an ascii string. That gets translated to proper math notation
> (by which I mean, what you would see in tex output). During template
> conversion. So this hint is just saying to the kid, "Dude, |-42|=42,
> |42|=42, get over it."
>
> >
> > To back out a bit, here, and get back to the meat of the matter: if one is
> > using Python, then it's because one doesn't much care about performance,
>
> I'll try again: this has nothing to do with performance.
>
> > and it's reasonable to do expansions, pattern matching and domain specific
> > language creation/use at run-time.  After all, that's how the language
> > itself works, mostly.
>
> The last example showed the macro inserting code to magically produce a
> binding inside the reverse function. It would be easier to compare and
> contrast with the Python equivalent if someone had posted such, but your
> troops have fallen back to Fort So What? and pulled up the drawbridge.
>
> Peace. Out. Ken
>

I think this specific sub-thread is a great example of what a lot of
people roll their eyes about when Lispers start talking, and it's a
great contrast to the foot stomping earlier where all the Lispers were
swearing that macros didn't complicate anything.

You start out with a fairly simple task, and use a macro instead of a
function even though you don't need to. That's "Arguments against LISP
101" right there. Then, you're (by your own indication - I find the
lisp code unreadably idiomatic) overly clever and spend several
iterations walking around in circles making your macro more clever,
rather than fixing your problem (spending too much time creating
clever genericness is a trap I'm sure many programmers have fallen in,
I've done it myself, but I have a feeling that Lispers are more
susceptible than most).

You finally have your macro doing all the cleverness you need, and
(again by your own account, I can't judge the code on any merit other
than "this looks like garbage to me") it's getting nasty and
contrived.

So you went from "look how simple and powerful this macro is", in a
trivial case that didn't even need a macro to "well, it's ugly and
nasty and idiomatic, but look how powerful this macro is!". This is
exactly the sort of thing that I (and, in my experience, many Python
programmers) strive to avoid in our work, and the readability and
clarity (more than simple character counts) of Python is a tool that
helps me achieve this goal.

I'd produce an equivalent Python version, but since you're totally
unclear in why you're adding these changes, and I can't read the lisp
well enough to see what it's doing, you're going to have to back up a
few steps if you want a Python implementation of your final solution.
I expect, however, that I wouldn't use a function at all = I'd make it
a data driven solution, because it (seems to be) a data oriented
problem.

> --
> Algebra: http://www.tilton-technology.com/LispNycAlgebra1.htm
>
> "Well, I've wrestled with reality for thirty-five
> years, Doctor, and I'm happy to state I finally
> won out over it." -- Elwood P. Dowd
>
> "I'll say I'm losing my grip, and it feels terrific."
> -- Smiling husband to scowling wife, New Yorker cartoon
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good Looking UI for a stand alone application

2006-12-18 Thread Chris Mellon
On 12/17/06, Christophe Cavalaria <[EMAIL PROTECTED]> wrote:
> Sandra-24 wrote:
>
> > On 12/16/06, The Night Blogger <[EMAIL PROTECTED]> wrote:
> >> Can someone recommend me a good API for writing a sexy looking (Rich UI
> >> like WinForms) shrink wrap application
> >
> >> My requirement is that the application needs to look as good on Windows
> >> as on the Apple Mac
> >
> > wxPython or something layered on it would be the way to go. I tried all
> > the popular toolkits (except qt) and nothing else comes close for cross
> > platform gui work. Don't let people persuade you otherwise, that caused
> > me a lot of trouble.
>
> Well, you should try qt too ;)
>
> BTW, does wxWindow/wxPython have something that allows you to switch the OK
> and Cancel button position according to the current machine GUI guidelines?
>

Yes. See wxDialog.CreateButtonSizer, which will return a sizer
(probably, on some embedded platforms it might not create actual
buttons, see docs) that has ok/cancel buttons in the standard position
for the platform, and with the correct stock graphics and text on
those platforms that have such a concept (like Gtk/GNOME).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good Looking UI for a stand alone application

2006-12-19 Thread Chris Mellon
> Ok, now here's a question for you: if crossplatform toolkits/frameworks
> are so great and automagically allow to produce superlickable and
> native-looking/feeling applications on all three major platforms, why is
> there so few of those applications on OS X ?
>
> "Because Mac users are elitists assholes" is not the good answer by the
> way :)
>

You've got a ridiculous straw man here. Nobody has ever said that they
do this, and nobody with any experience would. I don't actually think
you're interested in what is possible and what isn't, and I don't even
think that you actually evaluate the screenshots in a context where
it's possible for you to have any other opinion.

wx is the only popular toolkit of it's kind - it's a wrapper toolkit,
that uses actual native controls, not just ones designed to look like
them. For many wxPython/wxWidgets applications, there is *no
difference* between an app written directly to cocoa and a wxwidgets
app besides the API the author used. None, zero, zilch. Any "feel"
issues you claim to be present are solely because the author either
didn't know about or didn't care about a convention on the mac
platform.

The only other major cross platform toolkit with good mac support is
Qt, and I don't follow it's development closely. It may also use
native controls, at least in some cases, or it may still render
everything via the presentation manager, but regardless it's got a lot
of work and again, in most cases, it's hard if not impossible to tell
the difference between a "native" app and a qt one. I'm not a qt
expert so I won't spend too much energy defending it.

The look is easiest, of course. There's more to the look than just
that, of course, there's things like the stock behavior of controls.
wxPython gets that mostly for free, because it's using actual native
controls. There's things like the button order and layout, and wx
provides APIs to address that. Not everyone uses them, which is too
bad. There's some standard platform conventions like where your menu
items go. wx provides support for that. There's the fairly minor
issues of making sure your layout works with differently sized
controls and text, the wx layout mechanism addresses that.

Finally, there's some poorly defined "mac style" issues. wx, and no
toolkit, not even the native one, can address that. Many cross
platform apps are written on Windows with windows users in mind and
use windows assumptions, like that it's fine for a context menu to be
the only way to interact with something. This category is where almost
all complaints against cross platform apps fall, and it's ridiculous
because it's not something that a toolkit can address. You can, and
people do, write exactly the same sort of interface into mac native
applications. FinkCommander is a good example.

There's a few more caveats I haven't addressed, and there are places
where wx isn't perfect.  In wxPython, there are quite a few commonly
used controls that are custom controls hand-designed in Python, and
don't wrap native controls, so that can be a problem. It's not a
panacea, and anyone who sells it as such is wrong. But it doesn't
"suck", either. And it's a lot easier than maintaining multiple GUI
codebases, especially for platforms that don't see as much use.

Why are there so few applications? The real answer is probably that
the mac developer community is smaller than either the windows or
linux dev community, and people who develop for the mac tend not to
care about any other platform. So most of the crossover comes from the
other direction, and the mac community, being elitist assholes, makes
scathing comments about how it assumes you have 2 mouse buttons.

FYI: OS X ships with wxWidgets installed. How many applications built
into OS X are built using it? Are you sure? How would you know?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fall of Roman Empire

2006-12-20 Thread Chris Mellon
On 12/20/06, Ben Finney <[EMAIL PROTECTED]> wrote:
> "John Machin" <[EMAIL PROTECTED]> writes:
>
> > Ben Finney wrote:
> >
> > >  \  "...one of the main causes of the fall of the Roman Empire was |
> > >   `\that, lacking zero, they had no way to indicate successful |
> > > _o__)   termination of their C programs."  -- Robert Firth |
> >
> > An amusing .sig, but it doesn't address the root cause: As they had no
> > way of testing for the end of a string, in many cases successful
> > termination of their C programs would have been unlikely.
>
> Yet historically proven: the 'imperium' process they were running
> terminated many centuries ago.
>
> Or did it fork and exec a different process?
>

According to the C standard (16AD version), access past the end of an
imperial era results in undefined behavior.
-- 
http://mail.python.org/mailman/listinfo/python-list


PIL broken on win32?

2006-12-20 Thread Chris Mellon
PIL 1.1.5  and 1.1.6 both seem to be broken, in different ways, on win32.

1.1.5 will load and access images, but ImageDraw fails:
i = Image.open("good.jpg")
d = ImageDraw.Draw(i)
d.line((10,10,20,20))
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\Lib\site-packages\PIL\ImageDraw.py", line 199, in line
self.draw.draw_lines(xy, ink, width)
TypeError: function takes exactly 2 arguments (3 given)

1.1.6 is just broken in general - any access to image data fails:
i = Image.open("good.jpg")
d = i.getdata()
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\Lib\site-packages\PIL\Image.py", line 860, in getdata
self.load()
  File "C:\Python24\Lib\site-packages\PIL\ImageFile.py", line 217, in load
return Image.Image.load(self)
  File "C:\Python24\Lib\site-packages\PIL\Image.py", line 599, in load
return self.im.pixel_access(self.readonly)
AttributeError: pixel_access


These are the binary distributions for Python 2.4 off the effbot
download at http://effbot.org/downloads/#PIL

I tried with Python 2.5 quickly too - both 1.1.5 and 1.1.6 failed at
the same function that 1.1.5 for 2.4 failed at, but with a
SystemError: new style getargs format but argument is not a tuple
exception.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good Looking UI for a stand alone application

2006-12-21 Thread Chris Mellon
On 12/20/06, Vincent Delporte <[EMAIL PROTECTED]> wrote:
> On Tue, 19 Dec 2006 08:15:18 -0600, "Chris Mellon" <[EMAIL PROTECTED]>
> wrote:
> >There's a few more caveats I haven't addressed, and there are places
> >where wx isn't perfect.
>
> BTW, do you know of a good article/book on writing cross-platform GUI
> apps, with recommendations, pitfalls, etc. especially using wxWidgets?
> --
> http://mail.python.org/mailman/listinfo/python-list
>


There's a book on both wxWidgets itself, and on wxPython. Both of them
focus primarily on the wx api, rather than on the more general cross
platform problems.

The wxWidgets book is part of Bruce Perens' open source series, and
you can get the PDF from http://phptr.com/perens.

The wxPython book isn't freely available, but you can order it from
wxpython.org.

Unfortunately, neither book points out too much in the way of pitfalls
- they're mainly focussed on the API. The wxWidgets book does have a
section on some common errors with conforming to platform standards
and what wx can and cannot do to help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: some OT: how to solve this kind of problem in our program?

2006-12-26 Thread Chris Mellon
On 12/26/06, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Monday 25/12/2006 21:24, Paul McGuire wrote:
>
> >For example, for all the complexity in writing Sudoku solvers, there are
> >fewer than 3.3 million possible permutations of 9 rows of the digits 1-9,
> >and far fewer permutations that match the additional column and box
> >constraints.  Why not just compute the set of valid solutions, and compare
> >an input mask with these?
>
> Are you sure? There are 9!=362880 rows of digits 1-9; taking 9 of
> these at random gives about 10**50 possibilities. Of course just a
> few match the additional constraints. Maybe you can trivially reduce
> them (just looking for no dupes on the first column) but anyway its a
> large number... (Or I'm wrong computing the possibilities...)
>

According to Wikipedia, there are 6,670,903,752,021,072,936,960
possible classical Sudoku layouts. Ref.
http://www.research.att.com/~njas/sequences/A107739
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattr__ possible loop

2006-12-28 Thread Chris Mellon
On 28 Dec 2006 07:45:05 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Maksim Kasimov:
> > how to improve the situation depends on what do you expect to get by 
> > calling "T().method()"
>
> You are right, sorry for being cryptic. I think that's a kind of bug of
> Python (produced maybe by an infinite loop), so an improvement can be a
> traceback or some automatic breaking of that loop. Note that my problem
> comes from using Psyco that segfaults in that situation (if you have
> Psyco installed you can decomment two lines to see that). I think that
> using normal code Python+Psyco don't have to segfault, but I know this
> is tricky situation, so if no simple "solutions" can be found, then
> it's not a important thing and it can be ignored.
>

What I find most interesting is that you don't crash out because of
hitting the recursion limit.My brief testing shows something odd
going on  - when the stack depth gets to almost 1000 (the recursion
limit on my system) it knocks some stuff off the stack and the stack
limit never gets to the limit. Some sort of built in tail recursion?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: per interpreter storage for C extensions

2006-12-28 Thread Chris Mellon
On 12/28/06, Robin Becker <[EMAIL PROTECTED]> wrote:
> As part of some django usage I need to get some ReportLab C extensions into a
> state where they can be safely used with mod_python.
>
> Unfortunately we have C code that seems incompatible with mod_python and I'm
> looking for ways to improve the situation.
>
> Basically the main things that are wrong are all privately cached copies of
> python variables. This sample code
>
>
> static PyObject *_pdfmetrics_fonts = NULL;
> static PyObject *_pdfmetrics_ffar = NULL;
>
> ..
>  if(!_pdfmetrics_fonts){
>  res = PyImport_ImportModule("reportlab.pdfbase.pdfmetrics");
>  if(!res) ERROR_EXIT();
>  _o1 = _GetAttrString(res,"_fonts");
>  if(!_o1) ERROR_EXIT();
>  _o2 = _GetAttrString(res,"findFontAndRegister");
>  if(!_o2) ERROR_EXIT();
>  _pdfmetrics_fonts = _o1;
>  _pdfmetrics_ffar = _o2;
>  Py_DECREF(res); _o1 = _o2 = res = NULL;
>  }
>  if((res = PyObject_GetItem(_pdfmetrics_fonts,fontName))) return res;
> ...
>
> illustrates the general problem. If called first by interpreter A I'll get the
> values from interpreter A. When later called by interpreter B I'll be using 
> the
> wrong values and _pdfmetrics_ffar can alter the wrong interpreter's data.
>
>
> The functions themselves are fairly small, but may be called many times so
> they're worth speeding up.
>
> Is there a simple/cheap way for C code to cache these sorts of module level
> globals on a per interpreter basis? Is there even a way to tell which
> interpreter I'm being called in?
>
> Anything too costly will probably bust any speedup. Luckily I don't think we
> have too many of these cached variables so it's possible we may be able to get
> away with just dropping the caching for some and eliminating others.
> --
> Robin Becker
>

Just off the top of my head, I'd think that using thread-local storage
instead of static would work, wouldn't it? I'm not that familiar with
mod_python but I'm surely each python interpreter is in a different
thread (if not process) than the others.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattr__ possible loop

2006-12-28 Thread Chris Mellon
On 12/28/06, Chris Mellon <[EMAIL PROTECTED]> wrote:
> On 28 Dec 2006 07:45:05 -0800, [EMAIL PROTECTED]
> <[EMAIL PROTECTED]> wrote:
> > Maksim Kasimov:
> > > how to improve the situation depends on what do you expect to get by 
> > > calling "T().method()"
> >
> > You are right, sorry for being cryptic. I think that's a kind of bug of
> > Python (produced maybe by an infinite loop), so an improvement can be a
> > traceback or some automatic breaking of that loop. Note that my problem
> > comes from using Psyco that segfaults in that situation (if you have
> > Psyco installed you can decomment two lines to see that). I think that
> > using normal code Python+Psyco don't have to segfault, but I know this
> > is tricky situation, so if no simple "solutions" can be found, then
> > it's not a important thing and it can be ignored.
> >
>
> What I find most interesting is that you don't crash out because of
> hitting the recursion limit.My brief testing shows something odd
> going on  - when the stack depth gets to almost 1000 (the recursion
> limit on my system) it knocks some stuff off the stack and the stack
> limit never gets to the limit. Some sort of built in tail recursion?
>

Nothing so clever. dir() eats and ignores all exceptions, so when you
hit the recursion limit it eats the RecursionLimitExceeded exception
and continues merrily along the way. This is probably not good
behavior...

class Foo:
def __getattr__(self, attr):
raise SystemExit, "Don't call me, again, ever"

f = Foo()
f.method() #dies correctly
dir(f) #continues happily
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: db access

2006-12-28 Thread Chris Mellon
On 12/28/06, Martin P. Hellwig <[EMAIL PROTECTED]> wrote:
> king kikapu wrote:
> > Hey Martin,
> >
> > thanks for the fast reply!
> >
> > I have already seen that link and i just downloaded the pyodbc module
> > but isn't Python already containing a "built-in" odbc module so to
> > allow for db communication ??
> >
> 
> Not that I'm aware of, but it is possible to do odbc with the win32
> extensions which are commonly installed on windows machines, perhaps
> you've seen something like that?
>

Yes, but you don't want to. Use pyodbc (or adodbapi, if you're windows
only) and save yourself the trouble.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some basic newbie questions...

2006-12-28 Thread Chris Mellon
On 28 Dec 2006 08:40:02 -0800, jonathan.beckett
<[EMAIL PROTECTED]> wrote:
> Hi all,
>
> While working on support at work, I have been picking away at Python -
> because I think it could be a valuable scripting tool for building
> utilities from. I have been reading the python.org tutorials, and
> playing around with some basic code, but I have ended up with a few
> questions that probably have straightforward answers - any quick
> explanations or assistance would be fantastic...
>
>
> Question 1...
> Given the code below, why does the count method return what it does?
> How *should* you call the count method?
>   a = []
>   a.append(1)
>   print a.count
>

print a.count(). There's a "Python for VB programmers" out there
somewhere, see if you can find it. In python, functions (and methods
which are special cases of functions) are first class objects, so
you're printing the function object, not calling it.

>
> Question 2...
> What is the correct way of looping through a list object in a class via
> a method of it? (I've hit all sorts of errors picking away at this, and
> none of the tutorials I've found so far cover it very well) - apologies
> for the arbitrary class - it's the first example I thought up...
>
> class Gun:
> Shells = 10
>
> class Battleship:
> Gun1 = Gun()
> Gun2 = Gun()
> Guns = [Gun1,Gun2]
>
> def getShellsLeft(self):
> NumShells = 0
> for aGun in Guns:
> NumShells = NumShells + aGun.Shells
> return NumShells
>
> Bizmark = Battleship()
>
> print Bizmark.getShellsLeft()
>
>
> In the above code, I guess I'm just asking for the *correct* way to do
> these simple kinds of things...
>

You have the right idea but you've got your object instantiation
wrong. As I write this, I see an email from Grant Edwards that sums
things up nicely, I'll let him explain it.

I suggest working through the Python tutorial and Dive Into Python,
which will introduce you to the concepts you're getting wrong here.

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


Re: per interpreter storage for C extensions

2006-12-28 Thread Chris Mellon
On 12/28/06, Robin Becker <[EMAIL PROTECTED]> wrote:
> Robin Becker wrote:
> > Chris Mellon wrote:
> >> On 12/28/06, Robin Becker <[EMAIL PROTECTED]> wrote:
> >>> As part of some django usage I need to get some ReportLab C extensions 
> >>> into a
> >>> state where they can be safely used with mod_python.
> > .
> >> Just off the top of my head, I'd think that using thread-local storage
> >> instead of static would work, wouldn't it? I'm not that familiar with
> >> mod_python but I'm surely each python interpreter is in a different
> >> thread (if not process) than the others.
> >
> > I was thinking along those lines and if that were the case then I could use
> >
>
> ... reading further along those lines it seems there may be some hope of
> storing this stuff on the extension module (probably where it should belong) 
> as
> it seems that new interpreters share extensions, but when the extension is 
> first
>   imported a shallow copy is made of the module dict. That would seem to imply
> the  extension's module is private to each interpreter.
> --


It looks like you can figure out which interpreter you're running
under by looking at PyThreadState_Get()->interp. You can key your
cache using this pointer and you should be fine, if you want to keep
it in C.

> Robin Becker
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to serve image files without disk use?

2006-12-29 Thread Chris Mellon
On 12/28/06, Ray Schumacher <[EMAIL PROTECTED]> wrote:
> I'm trying to make a small camera server using VideoCapture.py and
> socket. I needed to construct a complete image file with headers etc
> for a browser to recognize it, but I couldn't find a combination of
> StringIO and wx image methods to avoid disk saves, without PIL.
>
> If I save a temp.jpg file to disk I can serve the image easily:
> ...
> self.cam = VideoCapture.Device(devnum=0, showVideoWindow=0)
> buff, width, height = self.cam.dev.getbuffer()
> im =  wx.EmptyImage(width, height)
> im.SetData(buff)
> im.Mirror().SaveFile('temp.jpg', wx.BITMAP_TYPE_JPEG)
> ...
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind((HOST, PORT))
> s.listen(1)
> conn, addr = s.accept()
> while 1:
>  data = conn.recv(1024)
>  if data[:3] == 'GET':
>  conn.send("HTTP/1.0 200 OK"+"\015\012")
>  conn.send("Server: RJS_video/0.0.1"+"\015\012")
>  conn.send("Content-type: image/bmp"+"\015\012")
>  conn.send("Content-Length: "+str(352*288*3+256)+"\015\012")
>  conn.send("\015\012")
>  fh = file('temp.jpg', 'rb')
>  conn.send(fh.read())
>  fh.close()
>  else: break
>
> But, how can I avoid disk writes? wx's *.SaveFile() needs a string
> file name (no objects).
> I'm going to investigate PIL's im.save(), as it appears to allow
> file-objects.
>

wx.Image.GetData() returns the raw image data as a Python string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 39, Issue 465

2006-12-29 Thread Chris Mellon
On 12/29/06, Ray Schumacher <[EMAIL PROTECTED]> wrote:
>
>  At 10:50 AM 12/29/2006, you wrote:
>
> In addition to what Chris said, is there a reason why you're reinventing
>  the wheel instead of using available components?
>  Hi Carsten,
>  The eventual goal here is towards a streaming two-way server, which
> wouldn't use the http, but something more like RTP/RTCP/H.323/ which I'm
> learning. It's also a general socket  learning exercise for me, as I haven't
> used them very much.
>  I was also using PyDShowCam before, and have switched to VideoCapture since
> I'll need to recompile PyDShowCam for py2.4.
>  I will look into the wx Chris suggested this weekend; more stuff I haven't
> used...
>
>  Thanks,
>  Ray
>
>  For anyone interested, I attached a quick wx I made last night that
> monitors a USB webcam, will create "dark" frames (a la astronomy), and serve
> up images to web browsers (thus the question). The browser/monitor would
> actually work nicely with a web page that has a JavaScript function to
> reload the image x times/second. I'll try replacing the PIL with the wx
> function(s) and benchmark if they work.
>

I just double-checked my documentation and wx.Image.GetData() is not
what you want - that's the RGB pixel data, and you want the encoded
stream.

Using pil to save directly to the output buffer is probably the most
efficient mechanism - it doesn't look like wxPython provides
SaveStream (or SaveBuffer). Those probably could be implemented (the
C++ wxImage object supports saving to streams, and SWIG can make a
python FLO look like a stream), you might want to post a feature
request.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Packaging up a Python/Twisted Matrix application...

2007-01-04 Thread Chris Mellon
On 1/4/07, Chaz Ginger <[EMAIL PROTECTED]> wrote:
> I have a rather large Python/Twisted Matrix application that will be run
> on Windows, Linux and perhaps Macs. I was wondering if there are any
> tools that can be used to create an installer that will bring in Python,
> Twisted Matrix, my application libraries and anything else I need?
>
> I have tried using ezsetup with no luck (it seems not everything can be
> installed with it). I was hoping to find something as nice (and
> complete) as Perl's CPAN but can't seem to find anything.
>
> Does anyone have any recommendations?
>
> Peace,
> Chaz.
> --

For windows, py2exe is the de facto standard and it works fine with Twisted.

There are similar scripts for the other platforms but I'm not familiar
with them, I understand py2app is the standard for OS X.

Note that OS X and pretty much every version of linux ship with
Python, you might re-think your need to distribute a binary and
instead just use a distutils install.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using External Libraries with python?

2007-01-04 Thread Chris Mellon
On 1/4/07, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
> Ognjen Bezanov schrieb:
> > I have some external C libraries I would like to use with python.
> >
> > I have been searching on the internet and found many such
> > modules/bindings for libraries (e.g. Py-Lame) but have not yet
> > come across any information of how to actually go about creating such
> > bindings, so I was wondering if anybody here could point me in the right
> > direction?
>
> There are several methods. One is to write a Python C module by hand,
> using the Python C API:
>
> http://docs.python.org/ext/ext.html
> http://docs.python.org/api/api.html
>
> Essentially, all you need is a DLL/shared-object with an init
> function.
>
> Other solutions include tools that generate extension modules
> automatically (such as SWIG or Pyrex), or using libraries on
> top of the C API (such as Boost.Python).
>
> I personally always use the C API directly.
>
> Regards,
> Martin

Don't forget calling the using the external library directly from
Python by using ctypes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb windows binaries for Python 2.5?? Yes, but from a World of Warcraft guild.

2007-01-05 Thread Chris Mellon
On 1/5/07, John Nagle <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Anyone have a binary they want to share?
> >
> > /Martin
> >
> Somebody has an untested one.  See
>
> http://sourceforge.net/forum/forum.php?thread_id=1571110&forum_id=70461
>
> You have to ask for a copy; they don't want to distribute it and
> be blamed for problems.
>
> There hasn't been a new release of MySQLdb since April 2006, and
> there's no official support for either Python 2.5 or Windows.
> Realistically, you have to run Python 2.4 or earlier if you
> need database access.  We dropped back to Python 2.4,
> with good results.
>
> John Nagle
> --

I guess this is your opportunity, as someone who thinks that MySQL
support for Python is important, to assist in maintaining and updating
those wrappers, right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PDF rendering toolkit?

2007-01-08 Thread Chris Mellon
On 1/5/07, Jorge Vargas <[EMAIL PROTECTED]> wrote:
> Hi
>
> I'm looking for a tool to take an actual .pdf file and display it in a
> window (I'm using wxwidgets at the moment)
>
> I have found several project but none seem to do what I need.
>
> http://sourceforge.net/projects/pdfplayground seems like a nice
> toolkit to edit pdf files with python code, but nothing about
> rendering.
>
> I have find out http://poppler.freedesktop.org/ but there seems to be
> no python bindings for it.
>
> there is also an example at http://www.daniweb.com/code/snippet618.html
> using wx.lib.pdfwin but that is windows only, I need at least Linux
> support better if it's platform independant as python *should* be
>
> and the reportlabs BSD packages can't do this.
> http://www.reportlab.org/devfaq.html#2.1.5
>
> anyone knows of a toolkit to do this? bonus points if's it is already
> integrated into wxpython
> --

Rendering PDF is quite hard, much harder than writing it. There are
relatively few PDF rendering solutions for any platform, and it's
non-trivial to merge one with a specific UI solution. So I'm not aware
of any cross-platform solution. Most PDF usage either embeds the Adobe
ActiveX control (on windows) or just shunts it off the user to find a
working PDF viewer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread Chris Mellon
On 1/8/07, Felipe Almeida Lessa <[EMAIL PROTECTED]> wrote:
> On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
> >
> >
> > > I just tried on my system
> > >
> > > (Python is using 2.9 MiB)
> > > >>> a = ['a' * (1 << 20) for i in xrange(300)]
> > > (Python is using 304.1 MiB)
> > > >>> del a
> > > (Python is using 2.9 MiB -- as before)
> > >
> > > And I didn't even need to tell the garbage collector to do its job. Some
> > info:
> >
> > It looks like the big difference between our two programs is that you have
> > one huge string repeated 300 times, whereas I have thousands of
> > four-character strings.  Are small strings ever collected by python?
>
> In my test there are 300 strings of 1 MiB, not a huge string repeated. 
> However:
>
> $ python
> Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02)
> [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> # Python is using 2.7 MiB
> ... a = ['1234' for i in xrange(10 << 20)]
> >>> # Python is using 42.9 MiB
> ... del a
> >>> # Python is using 2.9 MiB
>
> With 10,485,760 strings of 4 chars, it still works as expected.
>
> --
> Felipe.
> --

Have you actually ran the OPs code? It has clearly different behavior
than what you are posting, and the OPs code, to me at least, seems
much more representative of real-world code. In your second case, you
have the *same* string 10,485,760 times, in the OPs case each string
is different.

My first thought was that interned strings were causing the growth,
but that doesn't seem to be the case. Regardless, what he's posting is
clearly different, and has different behavior, than what he is
posting. If you don't see the memory leak when you run the code he
posted (the *same* code) that'd be important information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suitability for long-running text processing?

2007-01-08 Thread Chris Mellon
On 1/8/07, tsuraan <[EMAIL PROTECTED]> wrote:
>
>
> > My first thought was that interned strings were causing the growth,
> > but that doesn't seem to be the case.
>
> Interned strings, as of 2.3, are no longer immortal, right?  The intern doc
> says you have to keep a reference around to the string now, anyhow.  I
> really wish I could find that thing I read a year and a half ago about
> python never collecting small strings, but I just can't find it anymore.
> Maybe it's time for me to go source diving...
>
>

I remember something about it coming up in some of the discussions of
free lists and better behavior in this regard in 2.5, but I don't
remember the details.

Interned strings aren't supposed to be immortal, these strings
shouldn't be automatically interned anyway (and my brief testing
seemed to bear that out) and calling _Py_ReleaseInternedStrings didn't
recover any memory, so I'm pretty sure interning is not the culprit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why less emphasis on private data?

2007-01-08 Thread Chris Mellon
Private data in the C++ and Java OO worlds is so taught so much and
emphasized so often that people have started thinking of it as being
desirable for its own sake. But the primary motivation for it grew out
of the need to maintain compatible interfaces. These languages rely on
a great deal of shared information between provides and clients of
interfaces in order to work correctly - public/private interfaces are
simply a reflection of that requirement (and the fact that your
clients still need to see the stuff you declare as private is an
example of a leak in that abstraction).

Python doesn't have these problems, so the only use for private
information is to warn your clients away from access to certain names.
There's no need for compiler enforcement of that, as a convention is
just as effective.

The remaining arguments are generally outgrowths of "but my code is
SECRET", which just isn't true in general, even less true of Python,
and not really a healthy attitude anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Execute binary code

2007-01-08 Thread Chris Mellon
On 8 Jan 2007 12:45:45 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Larry Bates wrote:
>
> > What you are asking is a virus/trojan "like" program.  There's no reason
> > you shouldn't be able to write the code to TEMP directory and execute it.
> >
> > -Larry
>
>
> No, it is not about a trojan, but I guess it's pointless to try to
> convince you otherwise.
>
> It's not about being able to write the code to TEMP directory and
> execute it, it's about not wanting to do so.
>
> -Cornelius
>

Writing to a temp file will be at least 3 times as easy and twice as
reliable as any other method you come up with.


 Repost. Is there any chance at all that ML could set the
reply-to to the list instead of the sender?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Execute binary code

2007-01-08 Thread Chris Mellon
On 1/8/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Monday 8/1/2007 18:01, [EMAIL PROTECTED] wrote:
>
> >Chris Mellon wrote:
> > > Writing to a temp file will be at least 3 times as easy and twice as
> > > reliable as any other method you come up with.
> >
> >I'm not disputing that, but I want to keep a piece of code (a parser
> >for Oracle binary dumps, that I didn't wrote) out of foreign hands, as
> >much as possible. Using a TEMP directory is not "stealth" enough.
>
> This is what I would do  (untested of course!) (Mostly using the
> Win32 API so you'll have to use pywin32 or ctypes).
>
> Call CreateFile with dwShareMode=0, FILE_ATTRIBUTE_TEMPORARY,
> FILE_FLAG_NO_BUFFERING, FILE_FLAG_DELETE_ON_CLOSE.
> That means that no other process could open the file, if it fits in
> available memory probably it won't even be written to disk, and it
> will be deleted as soon as it has no more open handles. File name
> does not have to end in .exe.
> Copy the desired contents into a buffer obtained from VirtualAlloc;
> then call WriteFile; release the buffer (rounding size up to next 4KB 
> multiple)
> Then CreateProcess with CREATE_SUSPENDED, and CloseHandle on the
> file, and CloseHandle on the two handles returned on
> PROCESS_INFORMATION. At this stage, the only open handle to the
> temporary file is held by the section object inside the process.
> Then ResumeThread(hTread) -process begins running- and
> WaitForSingleObject(hProcess) -wait until finishes-.
> As soon as it finishes execution, the last handle to the file is
> closed and it is deleted.
>
> Another approach would be to go below the Windows API and use the
> native API function NtCreateProcess -officially undocumented- which
> receives a section handle (which does not have to be disk based). But
> this interfase is undocumented and known to change between Windows versions...
>
> Or search for a rootkit...
>
>
> --
> Gabriel Genellina
> Softlab SRL
>

Thats a lot of work to execute a binary image that can be trivially
recovered from the python source with 2 minutes of work (up to 15 if
you have to install Python and google for how to write to a file
first).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Execute binary code

2007-01-09 Thread Chris Mellon
On 9 Jan 2007 07:04:11 -0800, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> Jorgen Grahn wrote:
>
> > For what it's worth[1], under Unix it /is/ impossible. The only way to 
> > bring in
> > new code (short of dynamic libraries) is to call exec(2) or its variations,
> > and all need a file system object to load the code from.
>
> The x86 processor cannot tell the difference between code segments and
> data segments. If the executable code is stored in string, all you need
> is a pointer to the string holding the code. You can cast the string
> address to a function pointer (possibly through a void* if the compiler
> complains), then dereference (call) the function pointer.
>
> Trojans, viruses and JIT compilers do this all the time. Here is an
> (untested) example:
>
> static PyObject*
> call_code_in_string(PyObject *self, PyObject *args)
> {
> char *s;
> int size;
> int arg1, arg2, arg3;
> typedef int (*func_t)(int,int,int);
> func_t pfunc;
> if(!PyArg_ParseTuple(args, "s#(iii)", &s, &size, &arg1, &arg2,
> &arg3)) return NULL;
> pfunc = (func_t)((void *)s); /* if it fails, try
> memcpy(&pfunc,&s,sizeof(void*)) instead */
> return PyInt_FromLong((long)pfunc(arg1, arg2, arg3));
> }
>
> Another possibility would be to just return the string address, and
> then make the call possibly using ctypes.
>
> static PyObject*
> get_string_addr(PyObject *self, PyObject *args)
> {
> char *s;
> int size;
> if(!PyArg_ParseTuple(args, "s#", &s, &size)) return NULL;
> return PyInt_FromLong((long)((void*)s));
> }
>

This works fine if the binary data is "pure" asm, but the impresssion
the OP gave is that it's a compiled binary, which you can't just "jump
into" this way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another GUI toolkit question...

2006-02-11 Thread Chris Mellon
On 2/10/06, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> ...with a twist.
>
> I'm undertaking my first semi-substantial Python GUI application after a
> long time dabbling with the language.
>
> I'm fairly experienced with Tcl/Tk, so Tkinter seems the obvious choice
> to reduce my Python learning curve. However, my Tcl applications
> typically make use of a *lot* of extensions to the core widget set, such
> as BWidgets, tablelist, and Tile.
>
> I've found minimal Tkinter wrappers for all of these extensions, but
> they are all labelled "experimental," lightly documented at best, and
> little-used (as far as I can tell) by Python developers.
>
> So: my question is, would it be more productive for me to wrestle with
> these extensions when there doesn't seem to be much constituency for
> their use, or would it be better/faster/more efficient for me to start
> scaling the wxPython mountain?
>
> For what it's worth, my application has to run on OS X and Windows, and
> will be commercial, so this combination of requirements rules out
> PyGTK/PyQt/just about every other cross-platform GUI toolkit.
>

If you're planning on selling an application, especially to OS X
users, then Tk is absolutely out of the question. It doesn't have even
the slightest resemblence to native behavior, and lacks the polish and
flash that occasionally lets a non-native app get away with it. Given
the limits you've stated, I believe your only options are wxPython and
writting 2 guis using PyWin/PyObjC. The second option requires
knowledge of the native tool sets for the respective platforms, so if
you don't have that I can only suggest wxPython. If you're used to Tk
you will face a learning curve, and you will need to look for or write
replacements for the custom widgets you've been using.

> Advice, especially from those Tkinter devs who look beyond the core
> widget set for their apps, is appreciated!
>
> --
> Kevin Walzer
> iReveal: File Search Tool
> http://www.wordtech-software.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Yet another GUI toolkit question...

2006-02-11 Thread Chris Mellon
On 2/11/06, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> Chris Mellon wrote:
>
> >
> > If you're planning on selling an application, especially to OS X
> > users, then Tk is absolutely out of the question. It doesn't have even
> > the slightest resemblence to native behavior, and lacks the polish and
> > flash that occasionally lets a non-native app get away with it. Given
> > the limits you've stated, I believe your only options are wxPython and
> > writting 2 guis using PyWin/PyObjC. The second option requires
> > knowledge of the native tool sets for the respective platforms, so if
> > you don't have that I can only suggest wxPython. If you're used to Tk
> > you will face a learning curve, and you will need to look for or write
> > replacements for the custom widgets you've been using.
> >
>
> Do these screenshots look "non-native" to you?

Yes, actually.  But thats not the point, and a trivial dialog isn't
enough to really judge Tile anyway.

>
> http://www.wordtech-software.com/ireveal-mac.png
> http://www.wordtech-software.com/ireveal-windows.png
> http://www.wordtech-software.com/ireveal-linux.png
>
> This application was developed in Tcl/Tk.
>
> I think Tkinter is lagging behind Tk itself in terms of its advances
> with theming and native look and feel, especially on OS X and Win XP.
> Certainly a lot of Python developers don't seem well-informed about the
> work that has been done to bring Tk back into the modern age. The
> wrappers I mentioned above (some at a site that is offline but should be
> back online shortly, I'm told) are bleeding-edge in Tkinter terms but
> reflect work that started a couple of years ago in Tk. (The extension is
> called "Tile" and will be part of the Tk core when it's released at v. 8.5).
>
> That doesn't mean wxPython is out of the question. What I'm trying to
> figure out is whether I will be up and running faster with Tkinter +
> Tile (leaving me mainly to improve my proficiency with Python itself and
> translate Tk into a Python idiom) or whether I should learn wxPython,
> with its vastly different GUI paradigm, as well as Python.
>

That depends almost totally on you and your skills, doesn't it? I'm an
unabashed fan of wxPython, so naturally I lean that way, but I
wouldn't deny that is has a learning curve. It's famous "C++ like API"
has seen vast improvement in the last few releases, by the way, and is
much more pythonic than a lot of people seem to believe  - no more
from wxPython import *, for example. I certainly find it's API more
pythonic than Tkinters.

> If Tkinter + Tile + Bwidgets + Tablelist does the job, as I think it may
> (and as it does with regular Tcl/Tk), then I will probably stick with
> that. And perhaps I can then contribute some documentation somewhere on
> how to use the Tile widgets in a Tkinter application, complete with
> screen shots and working code for others to use. Such documentation is
> sorely lacking right now.
>
> The vast range of available GUI toolkits is one thing that partially
> offsets Python's many virtues as a programming language. I realize I was
> stepping into a fire swamp by even broaching the question. However, the
> application I'm envisioning (accessing web services from a desktop GUI)
> will benefit from the abundant Python libraries/wrappers that have
> already been written, which are mostly lacking (or which would require
> me to roll my own) in Tcl.
>

I can't possibly see how an available range of GUI toolkits is a
detriment to a *language*. I can see (but don't neccesarily agree)
that is detrimental to a desktop environment or whatever, but not a
language. By that standard C is the worst language to ever exist, C++
only marginally better, and stuff like Visual FoxPro the best of all.

>
>
> --
> Kevin Walzer
> iReveal: File Search Tool
> http://www.wordtech-software.com
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Legality of using Fonts

2006-02-11 Thread Chris Mellon
On 2/11/06, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Fri, 10 Feb 2006 20:24:34 -0800, Ross Ridge wrote:
>
> > Steven D'Aprano wrote:
> >> It is highly unlikely that any judge will be fooled by a mere change in
> >> format ("but Your Honour, I converted the TTF file into a bitmap").
> >
> > If that were true, almost the entire X11 bitmap font collection would
> > be illegal.  Fonts aren't subject copyright, just the hints in most
> > outline fonts, which are considered computer programs.
>
> This may come as a shock to you, but the USA is not the entire world, and
> the US government's decision to exclude typefaces from copyright
> protection is anomalous. In almost the entire rest of the world,
> typefaces (the design of a font) are able to be copyrighted, and so are
> fonts whether they are bitmapped or outline (with or without hints).
>
>
> See, for example: http://www.typeright.org/feature4.html
>
> In any case, even in the USA, hinted fonts are copyrightable, and merely
> removing the hints (say, by converting to a bitmap) is no more legal than
> whiting out the author's name from a book and claiming it as your own.
>

This is absolutely wrong. It is perfectly legal to extract the
non-copyrightable elements of a copyrighted work (the typeface itself,
in this case) and do whatever you want with it.

> Of course, like all these issues, the actual decision of a judge and jury
> in the USA is uncertain -- who knows whether they will consider a
> bitmapped version of a TTF font to be a derivative work or not? So even in
> the USA, unless you want to spend big dollars on legal fees, the best
> advice is to stick to fonts which are distributed under open licences.
>

I'd say this is a case that isn't uncertain at all. The lack of
protection for typefaces is not a loophole or unclear convention -
Congress and the copyright office explicitly refuse to extend
copyright protection to typefaces. The loophole, in fact, is the
protection of hinted fonts, which are only protected to the degree
that they are "computer programs", because they are *not* protectable
as fonts, period. Saying it is uncertain is not intellectually honest,
in my opinion.

Now, I personally feel that this is a case where Congress made a poor
decision on all counts - TTF files are a prime example of programs
that should not be copyrightable (mechanical implementation), and
typefaces should be. But that's not the state of affairs in the US.

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


Re: Python vs. Lisp -- please explain

2006-02-21 Thread Chris Mellon
On 2/20/06, Donn Cave <[EMAIL PROTECTED]> wrote:
> Quoth Steven D'Aprano <[EMAIL PROTECTED]>:
> ...
> | Nobody denies that Python code running with no optimization tricks is
> | (currently) slower than compiled C code. That's a matter of objective
> | fact. Nobody denies that Python can be easily run in interactive mode.
> | Nobody denies that *at some level* Python code has to be interpreted.
> |
> | But ALL code is interpreted at some level or another. And it is equally
> | true that at another level Python code is compiled. Why should one take
> | precedence over the other?
>
> I have no idea, what precedence?  All I'm saying is that Python matches
> what people think of as an interpreted language.  You can deny it, but
> but it's going to look like you're playing games with words, and to no
> real end, since no one could possibly be deceived for very long.  If you
> give me a Python program, you have 3 choices:  cross your fingers and
> hope that I have the required Python interpreter version, slip in a
> 25Mb Python interpreter install and hope I won't notice, or come clean
> and tell me that your program needs an interpreter and I should check to
> see that I have it.


You're correct as far as it goes, but can you provide a reasonable
definition for "interpreted" that matches the common usage? Most
people can't.

When asked to name some interpreted (or scripting) languages, they'll
name some off - perl, python, ruby, javascript, basic...

They won't say Java. Ask them why Python is interpreted and Java isn't
and you'll have a hard time getting a decent technical answer, because
Python isn't all that different from Java in that regard, especially
pre-JIT versions of Java.

Probably the most accurate definition of "interpreted" as it is used
in the wild is "one of these languages: perl, python, perl, ruby,
etc". That is, you're essentially claiming that Python is interpreted
because everyone thinks of it that way, technical correctness be
damned.

There is an obvious difference between Python and C. Nobody would deny
that. But it's a fairly hard thing to *quantify*, which is why people
make sloppy categorizations. That's not a problem as long as there
isn't prejudice associated with the categorization, which there is.

I wonder how "interpreted" people would think Python is if the
automagic compilation to .pyc was removed and you had to call
"pythonc" first.

>
> Donn Cave, [EMAIL PROTECTED]
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs. Lisp -- please explain

2006-02-21 Thread Chris Mellon
On 21 Feb 2006 08:30:04 -0800, Paul Boddie <[EMAIL PROTECTED]> wrote:
> Chris Mellon wrote:
> >
> > You're correct as far as it goes, but can you provide a reasonable
> > definition for "interpreted" that matches the common usage? Most
> > people can't.
>
> I thought Torsten's definition was good enough: if the instructions
> typically produced when preparing your programs for execution can be
> handled directly by the CPU then let's call it a "compiled language";
> otherwise, let's call it an "interpreted language". I think we all know
> about the subtleties of different levels of virtual machines, but if
> you want an arbitrary definition that lots of people feel is intuitive
> then that's the one to go for.
>
> > When asked to name some interpreted (or scripting) languages, they'll
> > name some off - perl, python, ruby, javascript, basic...
>
> Right: compiled Perl and Python instructions typically aren't executed
> directly by the hardware; Ruby visits the parse tree when executing
> programs (see [1] for some casual usage of "interpreted" and "compiled"
> terms in this context), although other virtual machines exist [2];
> JavaScript varies substantially, but I'd imagine that a lot of the
> implementations also do some kind of parse tree walking (or that the
> developers don't feel like documenting their bytecodes), although you
> can also compile JavaScript to Java class files [3]; BASIC varies too
> much for any kind of useful summary here, but I'd imagine that early
> implementations have tainted the language's "compiled" reputation
> substantially.
>
> > They won't say Java. Ask them why Python is interpreted and Java isn't
> > and you'll have a hard time getting a decent technical answer, because
> > Python isn't all that different from Java in that regard, especially
> > pre-JIT versions of Java.
>
> That's why I put Java and Python in the same category elsewhere in this
> thread. Bear in mind, though, that Java's just-in-time compilation
> features were hyped extensively, and I imagine that many or most
> implementations have some kind of native code generation support,
> either just-in-time or ahead-of-time.
>

Early Java versions did not, and many versions still don't, at least
in any meaningful way. There are ways of compiling "native" Java, but
they work more like py2exe than GCC. "Native code generation" is a
fairly imprecise term in and of itself - Psyco works almost exactly
the same way as Java JIT does,

> > Probably the most accurate definition of "interpreted" as it is used
> > in the wild is "one of these languages: perl, python, perl, ruby,
> > etc". That is, you're essentially claiming that Python is interpreted
> > because everyone thinks of it that way, technical correctness be
> > damned.
>
> Well, I think Torsten's definition was more objective and yet arrives
> at the same result. Whether we're happy with that result, I have my
> doubts. ;-)

I don't think it does, though. Firstly, as a definition it relies on
the environment the application will be running under and therefore
can't be considered to describe just a language. Secondly, by that
definition Java is an interpreted language which is at odds with the
common definition.

I've encountered a C scripting environment that works by using GCC to
compile each line as it is encountered, doing some magic to keep a
working compilation environment around.

Interpreted? Compiled?

>
> > There is an obvious difference between Python and C. Nobody would deny
> > that. But it's a fairly hard thing to *quantify*, which is why people
> > make sloppy categorizations. That's not a problem as long as there
> > isn't prejudice associated with the categorization, which there is.
>
> I refer you again to Torsten's definition.
>

Torstens definition isn't useful for quantifying a difference between
interpeted and compiled - it's a rough sort of feel-test. It's like
how much of a naked body you can expose before before it changes from
art to pornography - it's not something that is easily quantified.

> > I wonder how "interpreted" people would think Python is if the
> > automagic compilation to .pyc was removed and you had to call
> > "pythonc" first.
>
> Well, such things might have a psychological impact, but consider
> removing Python's interactive mode in order to enhance Python's
> non-interpreted reputation, and then consider Perl (an interpreted
> language according to the now-ove

Re: wxPython memory footprint? - Re: Write a GUI for a python script?

2006-03-02 Thread Chris Mellon
On 3/2/06, robert <[EMAIL PROTECTED]> wrote:
> ianaré wrote:
>
> > wxPython is another good option, especially since there is
> > boa-constructor, which is a great GUI builder, almost makes it too easy
> > to make a nice looking app in no time at all.
> >
> > http://www.wxpython.org/download.php
> >
> > http://boa-constructor.sourceforge.net/
> >
> > if you decide to give wxPython a go, make sure to download the demo, it
> > has tons of usefull code samples.
>
> What is the minimal memory footprint of a Hello World wxPython app
> meanwhile (when you cx_freeze/py2exe it) ?
>

I'm assuming you mean disk space and not memory usage. A stock
wxPython (from a standard release) wil vary from platform to platform
but is generally about 2.5 megs. This can be brought down rather a lot
if you're willing to spend a fair amount of time learning the
wxWidgets and wxPython build systems and making custom builds but it's
not generally worth the time to me (and I know the build system and
could make customized builds if I wanted to)

I have a non-trivial wxPython application and, using py2exe in "single
executable" mode (thus all the dlls and the zipfile with the .pyc
files are included in the exe) it's just over 5 megs in size.

> Can you debug & call functions interactively from e.g. Pythonwin while a
> wxPython app is running.
>

I've never tried it with PythonWin and I don't know how PythonWin
hooks into Python to manage debugging). Both pdb and the debugger in
PyDev work fine for me, however. As another responder said it's
trivial (literally < 5 lines) to add an interactive Python shell to a
wxPython application, which is invaluable for debugging and testing.

> ( When I made a test with wxPython some years ago, it had no option to
> step/share its Messageloop. Interaction was "crust"y and I didn't manage
> to get smooth debugging (on Windows).  )
>

I don't believe that wxPython exposes the low level C++ APIs that're
available to hook the wx message loop (it's an efficency issue, from
what I understand), but there are a number of other methods for
integration. The need to hook the message loop is far far less common
than the number of people who ask for it, so you'll forgive me if I'm
skeptical unless someone actually says why they want to.

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


Re: XP rich text cut-n-paste

2006-03-04 Thread Chris Mellon
On 4 Mar 2006 11:39:11 -0800, Paddy <[EMAIL PROTECTED]> wrote:
> Hi,
> Is their a colourized editor/shell that allows you to cut and paste the
> colourized text?
>
> Idle, SPE, Eclipse, and pythonwin all seem to nicely colourize both
> command line input as well as editor windows but when I cut and paste
> (in this case, into OpenOffice Writer), even the paste-special menu
> just allows the pasting of un-adorned text.
>
> i have a work-around: gvim coourizes and allows export as html, but it
> is long-winded.
>

The SciTe editor has a "Copy as RTF" function. It uses the same editor
control as SPE (but not idle, eclipse, or pythonwin), so you might ask
for it as a feature request in SPE.


> Thanks in advance, Paddy.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python memory handling

2007-05-31 Thread Chris Mellon
On 5/31/07, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
> * Chris Mellon (Thu, 31 May 2007 12:10:07 -0500)
> > > Like:
> > > import pool
> > > pool.free()
> > > pool.limit(size in megabytes)
> > >
> > > Why not letting the user choosing that, why not giving the user more
> > > flexibility ?
> > > I will try later under linux with the latest stable python
> > >
> > > Regards,
> > > FP
> > >
> >
> > The idea that memory allocated to a process but not being used is a
> > "cost" is really a fallacy, at least on modern virtual memory sytems.
> > It matters more for fully GCed languages, where the entire working set
> > needs to be scanned, but the Python GC is only for breaking refcounts
> > and doesn't need to scan the entire memory space.
> >
> > There are some corner cases where it matters, and thats why it was
> > addressed for 2.5, but in general it's not something that you need to
> > worry about.
>
> If it's swapped to disk than this is a big concern. If your Python app
> allocates 600 MB of RAM and does not use 550 MB after one minute and
> this unused memory gets into the page file then the Operating System
> has to allocate and write 550 MB onto your hard disk. Big deal.
>

It happens once, and only in page-sized increments. You'd have to have
unusual circumstances to even notice this "big deal", totally aside
from the unusual and rare conditions that would trigger it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python for EE CAD program

2007-06-04 Thread Chris Mellon
On 6/4/07, chewie54 <[EMAIL PROTECTED]> wrote:
> On Jun 4, 10:58 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > > Hello Diez,
> >
> > > I did look at PythonCad but the distribution and install methods for
> > > Windows is not user freindly. Since the public domain software,  I
> > > don't think they protect the source code either.
> >
> > The subject of code obfuscation in python has been beaten to death quite a
> > few times on this list, do a search to find anything you want to know.
> >
> > In a nutshell: forget about it. it's not worth it, difficult to accomplish
> > due to the dynamic nature of python and to be brutally honest: more or less
> > nothing you can come up with in your own code is really worth looking at
> > anyway. That's not saying that you can't code, just that more or less
> > everything one programs is trivial and only of value in the actual context
> > it was written in. So nobody is really interested in ripping stuff out.
> >
> > diez
>
>
> Your opinions are noted, thank you,  but I don't agree with you.
> There are
> portions of the code that are under review for patents and as such
> need to
> be protected.
>

For the record: This is not true. If you've already applied for the
patent, you have as much legal protection as you will ever get. Also,
since patents apply to methods and not to literal source, if you're
trying to protect something patentable you have even less protection
against analysis and disassembly than you would if you were trying to
protect the copyright on the code. If you need to make a token effort
to satisfy whatever legal hurdles are involved, shipping .pyc files
(which py2exe and all the other packagers I'm aware of do) is just as
effective as shipping executables compiled with C or C++.

> I'm investigating whether Python is the right language to use
> for a commercial CAD application. While I think Python is a great
> scripting
> language, there seems to limitations with regards to packaging and
> distributing
> programs.
>

None that don't also exist in every other language in existence. These
are fundamental issues of information theory, not language
constraints.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "GUI module" you suggest me to use?

2007-06-06 Thread Chris Mellon
On 6/6/07, Samuel <[EMAIL PROTECTED]> wrote:
> On Wed, 06 Jun 2007 00:22:40 +, Grant Edwards wrote:
>
> >> I know that WxPython work only under Windows and PyGTK work only under
> >> Linux...
> >
> > You 'know' wrong.
> >
> > wxPython works fine under Windows, Linux and OSX.
>
> wxPython emulates Gtk (though using some native widgets, it also uses
> some of its own) and in many cases it looks non-native compared to Gtk.
> If your target platform includes Unix systems, you'll have to decide
> whether inconsistencies with the look and feel of the desktop are an
> issue for you.
>

In the general case, wxWidgets wraps (not emulates) Gtk. I don't
believe that there are any common controls left which are still
emulated (maybe the list control? I'm not sure - I don't follow the
bleeding edge of wx anymore).

wxPython (as opposed to wxWidgets, the C++ core) has a sizeable
library of custom controls as part of its standard lib. Most of these
are owner-drawn for various reasons and often won't appear native
(Andrea Gavin, probably the most prolific custom control author, works
primarily on Windows).

> > PyGTK works under Linux and Windows, but doens't use native widgets
> > under Windows, so it won't look like a "normal" windows app.
>
> Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32
> installer does this by default since a couple of months.
>

That stretches the truth rather significantly. While the win32 theme
does use the windows theme apis for drawing, it still has slightly
different colors (especially window backgrounds and menus), and (more
importantly) vastly and notably different behavior. Shortcuts are
different, renderings are different, the Gtk drawing model is used
instead of the windows one (leads to quite jarring repainting
differences), different fonts, etc, etc. It looks okay in a screenshot
but is clearly non-native and foreign in use.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "GUI module" you suggest me to use?

2007-06-06 Thread Chris Mellon
On 6/6/07, Samuel <[EMAIL PROTECTED]> wrote:
> On Wed, 06 Jun 2007 14:43:35 +, Grant Edwards wrote:
>
> > On 2007-06-06, Samuel <[EMAIL PROTECTED]> wrote:
> >> On Wed, 06 Jun 2007 00:22:40 +, Grant Edwards wrote:
> >>> wxPython works fine under Windows, Linux and OSX.
> >>
> >> wxPython emulates Gtk
> >
> > What?  On some platforms (Linux), wxPython _uses_ Gtk. I don't see how
> > you could say it emulates it.
>
> That may be true in some cases, but in fact, most widgets show some sort
> of difference. Take for example the HPaned - it looks totally different
> (the slider is a lot slimmer, plus moving it makes a line appear. The
> behavior is different as well).
>

I'm not familiar with any wxPython control called HPaned. There's a
couple different types of splitter, the Gtk native one is
wxSplitterWindow. The others are owner drawn with better or worse
native appearance. Splitters are one of those things where everyone
writes their own, like web frameworks.

> Even simple widgets show differences. Try triple-clicking into entry
> boxes, it's different from Gtk.
>

Text boxes are absolutely native controls under gtk.

> >> (though using some native widgets, it also uses some of its own) and in
> >> many cases it looks non-native compared to Gtk.
> >
> > How can that be the case when wxPython is using Gtk?
>
> Obviously, it does *not* always use Gtk.

It *always* uses Gtk. Some people write or use custom controls, which
may or may not have gtk native analogs. This isn't any different than
using pygtk and writing custom widgets.

>
> >> If your target platform includes Unix systems, you'll have to decide
> >> whether inconsistencies with the look and feel of the desktop are an
> >> issue for you.
> >
> > wxPython looks completely native on Unix, because it's using a native
> > widget set (Gtk).
>
> Same as above.
>
> -Samuel
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which "GUI module" you suggest me to use?

2007-06-06 Thread Chris Mellon
On 6/6/07, Samuel <[EMAIL PROTECTED]> wrote:
> On Wed, 06 Jun 2007 09:45:48 -0500, Chris Mellon wrote:
>
> > On 6/6/07, Samuel <[EMAIL PROTECTED]> wrote:
> > In the general case, wxWidgets wraps (not emulates) Gtk. I don't believe
> > that there are any common controls left which are still emulated (maybe
> > the list control? I'm not sure - I don't follow the bleeding edge of wx
> > anymore).
>
> See my other response. Also, the fact that Gtk widgets are used does not
> necessarily mean that the behavior is the same - you can still do all
> kinds of weird stuff by hooking into the callbacks. Some of the
> differences to Gtk were probably introduced to wx in order to have more
> consistent behavior over different platforms.
>

This is true and in the specific case of triple click, wx does indeed
report them to the application differently than gtk does. This
doesn't, to my knowledge, interfere with text controls that don't try
to handle the click, but it may result in inconsistent behavior with
an app that adds triple click behavior to it's own text controls.

> > wxPython (as opposed to wxWidgets, the C++ core) has a sizeable library
> > of custom controls as part of its standard lib. Most of these are
> > owner-drawn for various reasons and often won't appear native (Andrea
> > Gavin, probably the most prolific custom control author, works primarily
> > on Windows).
>
> This affects the C++ core as well. aMule (which is written in CPP) is one
> particular complex example that exposes many of those problems when used
> on Linux.
>

the aMule team makes heavy use of their own custom written controls -
issues with it are not necessarily representative of the toolkit. The
C++ core has very few controls which are entirely custom drawn, and
those are generally controls which don't exist in the native platform.

> >> > PyGTK works under Linux and Windows, but doens't use native widgets
> >> > under Windows, so it won't look like a "normal" windows app.
> >>
> >> Gtk on Win32 can be themed to looked like Windows, AFAIK the Win32
> >> installer does this by default since a couple of months.
> >>
> >>
> > That stretches the truth rather significantly. While the win32 theme
> > does use the windows theme apis for drawing, it still has slightly
> > different colors (especially window backgrounds and menus), and (more
> > importantly) vastly and notably different behavior.
>
> Well, I have only tried Gaim on windows and could not tell the
> difference. But then, I am not a regular Windows user.
>
> > Shortcuts are
> > different, renderings are different, the Gtk drawing model is used
> > instead of the windows one (leads to quite jarring repainting
> > differences), different fonts, etc, etc. It looks okay in a screenshot
> > but is clearly non-native and foreign in use.
>
> Sounds bad. It also sounds much like what I experienced with wx on Linux.
>

I regularly use wxGTK and wxPython under linux with gnome (it's my
sole desktop at home - I only use windows at work). The differences
are orders of magnitude in severity.

One common problem is that people use incorrect (but working on
Windows) code and don't test under linux, it can cause similar issues.
The *toolkit* is very strong on all platforms. Individual apps are
often much less strong, because relatively view developers have access
and motivation to test heavily on all platforms. wx tries to make
correct code work the same on all platforms, but it can't make
incorrect code fail the same way on all platforms.

And, of course, many people simply aren't familiar with or choose not
to use the APIs that wx provides for whatever reason. Custom controls
that don't use native fonts are fairly common, for example, even
though wx provides APIs to retrieve the correct fonts and the use of
them is encouraged - people just hardcode whatever they "know" the
right font is on their native platform.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython / Dabo demo shell ?

2007-06-08 Thread Chris Mellon
On 6/8/07, stef <[EMAIL PROTECTED]> wrote:
> hello,
>
> I was impressed by the demo shell of wxPython,
> and a few days ago (finally getting Dabo to work),
> I saw Dabo uses the same demo shell.
>
> Is there any more information available about this shell,
> because it seems a very nice / good way to show
> (many) demos, in an organized way to newbies.
>
> thanks,
> Stef mientki
> --

The shell in the wxPython demo (but apparently not in the dabo demo,
as per Ed's email) is from the wx.py package. It's quite trivial to
add to your own applications, documentation is at
http://www.wxpython.org/PyManual.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editors again (it's not the same old request)

2007-06-10 Thread Chris Mellon
On 6/10/07, Eric S. Johansson <[EMAIL PROTECTED]> wrote:
> I upgraded to version 9.5 and all of my tools which enabled me to program by
> voice in Emacs are broken.  it's one of those dagnabbit a moment's of life.
>
> What I am looking for is a Windows based Python Smart editor that uses 
> specific
> rich text edit controls as specified here:
>
> http://knowledgebase.nuance.com/view.asp?tnID=5104&sQuery=4247
>
> Quoting from the article:
> """
> A window is considered standard if its window class name is one of the 
> following:
>
> Edit
>
> RichEdit
>
> RichEdit20A
>
> RichEdit20W
>
> RichEdit50W
>
> If the name is not one of those, then an edit control is still considered
> standard if its window class name and window styles are similar to those of
> standard edit controls.
>
> """
>
> There is some other stuff in there about other classes that may be able to 
> work
> in so far, they haven't yield anything useful to me.  Doesn't mean I won't 
> keep
> trying but it's more than a tad frustrating trying to root out some of these
> magic numbers.  Any help would be most appreciated.  Actually, it would be
> really nice if wxwindows  and gtk used the standard classes underneath so
> accessibility would be there semiautomatically on Windows but that's a 
> different
> conversation.
>

wx does (in large part), but most likely the problem is that the "rich
text" control used in most editors is not the win32 rich text control,
but instead Scintilla, which is designed for source editing and is
much easier to use. Very few editors, of any kind, use the native
win32 text control for source highlighting.

wx does have (some)  support for the accessibility features in win32,
you might post a feature request on the wx bug tracker to add them to
the wx platform bindings for Scintilla.

The main reason editors don't use the standard control is for syntax
highlighting and perhaps folding and margins, though, which I'm not
sure are especially valuable to you. What kind of features makes a
Python editor 'smart' for someone who's coding with a screen reader?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for ... else ?

2007-06-12 Thread Chris Mellon
On 6/12/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Tue, 12 Jun 2007 06:34:49 -0300, exhuma.twn <[EMAIL PROTECTED]> escribió:
>
> > On Jun 12, 6:57 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
> >> for number in range(10,100):
> >>  for divisor in range(2,number):
> >>  if number % divisor == 0:
> >>  break
> >>  else:
> >>  print number,
> >>
> >
> > Oh my. Would it not be an idea to rename this "else" into a "finally"?
> > As Gabriel points out, the else-block gets executed after the for loop
> > exits *normally*. In that case, is the "else" not semantically
> > misleading? I would surely misunderstand it if I saw it the first time.
>
> No - finally already has a meaning, "do this always, even if an exception
> occurred before".
> The "else" clause is fired when a condition is not met:
>
> if condition:
>do something when condition is true
> else:
>do something when condition is not true
>
>
> while condition:
>do something when condition is true
> else:
>do something when condition is not met
>
>
> for x in iterable:
>do something with x
> else:
>do something when there are no more x
>
>
> You can think the above as:
>
> while there are still values in iterable:
>do something with the next value
> else:
>do something when there are no more items
>

This is a good way of phrasing it and I hope I can remember it,
because for..else always gives me trouble. To me, "else" indicates the
negative condition and I intuitively associate it with executing the
loop early, not normal exit. Personally, I think a different keyword
(maybe "after"?) would have done a better job of clarifying this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List sequential initialization

2007-06-12 Thread Chris Mellon
On 6/12/07, HMS Surprise <[EMAIL PROTECTED]> wrote:
> Thanks for the explaination. It didn't seem natural and from the
> tutorial I read:
>
> A value can be assigned to several variables simultaneously:
>
> >>> x = y = z = 0  # Zero x, y and z
>
>
> Maybe I infer too much
>

And yet, your answer is right there.

"A value can be assigned to several variables simultaneously"

When you say want a value assigned to several variables, Python
doesn't assume that you actually mean you want 2 different values
assigned to them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Method much slower than function?

2007-06-14 Thread Chris Mellon
On 6/14/07, Peter Otten <[EMAIL PROTECTED]> wrote:
> Peter Otten wrote:
>
> > Leo Kislov wrote:
> >
> >> On Jun 13, 5:40 pm, [EMAIL PROTECTED] wrote:
> >>> Hi all,
> >>>
> >>> I am running Python 2.5 on Feisty Ubuntu. I came across some code that
> >>> is substantially slower when in a method than in a function.
> >>>
> >>> >>> cProfile.run("bar.readgenome(open('cb_foo'))")
> >>>
> >>>  20004 function calls in 10.214 CPU seconds
> >>
> >>> >>> cProfile.run("z=r.readgenome(open('cb_foo'))")
> >>>
> >>>  20004 function calls in 0.041 CPU seconds
> >>>
> >>
> >> I suspect open files are cached so the second reader
> >> picks up where the first one left: at the of the file.
> >> The second call doesn't do any text processing at all.
> >>
> >>   -- Leo
> >
> > Indeed, the effect of attribute access is much smaller than what the OP is
> > seeing:
>
> I have to take that back
>

Your tests (which I have snipped) show attribute access being about 3x
slower than local access, which is consistent with my own tests. The
OP is seeing a speed difference of 2 orders of magnitude. That's far
outside the range that attribute access should account for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with wxPython

2007-06-26 Thread Chris Mellon
On 6/26/07, Ali <[EMAIL PROTECTED]> wrote:
> Hi
>
> I'm not sure if this is the right place to post, pardon me if it's not.
> I'm having a problem with an application written with wxpython. The frame
> seems only to refresh when moving my mouse of it, though i frequently call:
> frame.Refresh(True). In fact, that line is called by another thread, right
> after having modified some of the frames attributes.
>

In general, the wxpython-users list is a better source of wxPython
answers than c.l.p.

wxPython gui elements are not threadsafe unless otherwise indicated.
Don't make calls against gui objects from other threads. This includes
Refresh().

You can make this call in a threadsafe manner using wx.CallAfter like so:
wx.CallAfter(frame.Refresh, True)


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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-06-26 Thread Chris Mellon
On 6/26/07, paul <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers schrieb:
> > Stephen R Laniel a écrit :
> >> On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote:
> >>> If you asked Java programmers why you couldn't turn *off* Java's static
> >>> type checking if you wanted to, you'd probably get a similar response.
> >> Perhaps it would help for me to explain what I'd like.
> >>
> >> Under both Perl and Python, I've found myself
> >> having/wanting to write things like so:
> >>
> >> def my_func( int_arg, str_arg ):
> >> try:
> >> int_arg = int( int_arg )
> >> str_arg = str( str_arg )
> >> except ValueError:
> >> sys.stderr.write( "Args are not of the right type\n" )
> >> sys.exit(1)
> >>
> >
> > Just a question : what will happen if you get rid of the try/except
> > block ?-)
> >
> The error will remain unnoticed and the argument might survive another
> few function calls but eventually fails deep down somewhere with:
>
> TypeError: cannot concatenate 'str' and 'list' objects
>
> then you have to examine the traceback and hope the real error is
> visible somewhere (an argument not conforming to the specification of
> the function prototype, or the lack thereof).
>

In the example given, not catching the example will provide *more*
information than the terrible exception handling performed. If you're
going to write thick boilerplate to log the values of your locals and
arguments around all your functions, I suggest that you not do that
and instead make use of the ehanced tracebacks in the cgitb module,
which will give you a stack trace with the values of the locals in
each stack frame.

The only reason to trap an exception is either to redirect the
exception (for example, I have a call in a thread which can't be
permitted to throw, so exceptions are caught and transfered elsewhere
for logging), or to correct the error that caused the exception.
Boilerplate like this is at best useless, and in the case of the
example given actively worse than simply not catching it at all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-27 Thread Chris Mellon
On 6/27/07, Andy Freeman <[EMAIL PROTECTED]> wrote:
> On Jun 26, 10:03 am, Paul Rubin  wrote:
> > > Map doesn't work on generators or iterators because they're not part
> > > of the common lisp spec, but if someone implemented them as a library,
> > > said library could easily include a map that handled them as well.
> >
> > Right, more scattered special purpose kludges instead of a powerful
> > uniform interface.
>
> Huh?  The interface could continue to be (map ...).
>
> Python's for statement relies on the fact that python is mostly object
> oriented and many of the predefined types have an iterator interface.
> Lisp lists and vectors currently aren't objects and very few of the
> predefined types have an iterator interface.
>
> It's easy enough to get around the lack of objectness and add the
> equivalent of an iterator iterface, in either language.  The fact that
> lisp folks haven't bothered suggests that this isn't a big enough
> issue.
>

Is this where I get to call Lispers Blub programmers, because they
can't see the clear benefit to a generic iteration interface?

> The difference is that lisp users can easily define python-like for
> while python folks have to wait for the implementation.
>

Yes, but Python already has it (so the wait time is 0), and the Lisp
user doesn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's "only one way to do it" philosophy isn't good?

2007-06-27 Thread Chris Mellon
On 6/27/07, Douglas Alan <[EMAIL PROTECTED]> wrote:
> Paul Rubin  writes:
>

> Gee, that's back to the future with 1975 Lisp technology.  Destructors
> are a much better model for dealing with such things (see not *all*
> good ideas come from Lisp -- a few come from C++) and I am dismayed
> that Python is deprecating their use in favor of explicit resource
> management.  Explicit resource management means needlessly verbose
> code and more opportunity for resource leaks.
>
> The C++ folks feel so strongly about this, that they refuse to provide
> "finally", and insist instead that you use destructors and RAII to do
> resource deallocation.  Personally, I think that's taking things a bit
> too far, but I'd rather it be that way than lose the usefulness of
> destructors and have to use "when" or "finally" to explicitly
> deallocate resources.
>

This totally misrepresents the case. The with statement and the
context manager is a superset of the RAII functionality. It doesn't
overload object lifetimes, rather it makes the intent (code execution
upon entrance and exit of a block) explicit. You use it in almost
exactly the same way you use RAII in C++ (creating new blocks as you
need new scopes), and it performs exactly the same function.

Nobody in their right mind has ever tried to get rid of explicit
resource management - explicit resource management is exactly what you
do every time you create an object, or you use RAII, or you open a
file. *Manual* memory management, where the tracking of references and
scopes is placed upon the programmer, is what people are trying to get
rid of and the with statement contributes to that goal, it doesn't
detract from it. Before the with statement, you could do the same
thing but you needed nested try/finally blocks and you had to
carefully keep track of the scopes, order of object creation, which
objects were created, all that. The with statement removes the manual,
error prone work from that and lets you more easily write your intent
- which is *precisely* explicit resource management.

RAII is a good technique, but don't get caught up on the
implementation details. The fact that it's implemented via stack
objects with ctors and dtors is a red herring. The significant feature
is that it's you've got explicit, predictable resource management with
(and this is the important bit) a guarantee that code will be called
in all cases of scope exit.

The with statement does exactly the same thing, but is actually
superior because

a) It doesn't tie the resource managment to object creation. This
means you can use, for example, with lock: instead of the C++ style
Locker(lock)

and

b) You can tell whether you exited with an exception, and what that
exception is, so you can take different actions based on error
conditions vs expected exit. This is a significant benefit, it allows
the application of context managers to cases where RAII is weak. For
example, controlling transactions.

> > Python object lifetimes are in fact NOT predictable because the ref
> > counting doesn't (and can't) pick up cyclic structure.
>
> Right, but that doesn't mean that 99.9% of the time, the programmer
> can't immediately tell that cycles aren't going to be an issue.
>
> I love having a *real* garbage collector, but I've also dealt with C++
> programs that are 100,000+ lines long and I wrote plenty of Python
> code before it had a real garbage collector, and I never had any
> problem with cyclic data structures causing leaks.  Cycles are really
> not all that common, and when they do occur, it's usually not very
> difficult to figure out where to add a few lines to a destructor to
> break the cycle.
>

They can occur in the most bizarre and unexpected places. To the point
where I suspect that the reality is simply that you never noticed your
cycles, not that they didn't exist.

> > And the refcounts are a performance pig in multithreaded code,
> > because of how often they have to be incremented and updated.
>
> I'm willing to pay the performance penalty to have the advantage of
> not having to use constructs like "when".
>

"with". And if you think you won't need it because python will get
"real" GC you're very confused about what GC does and how.

> Also, I'm not convinced that it has to be a huge performance hit.
> Some Lisp implementations had a 1,2,3, many (or something like that)
> reference-counter for reclaiming short-lived objects.  This bypassed
> the real GC and was considered a performance optimization.  (It was
> probably on a Lisp Machine, though, where they had special hardware to
> help.)
>
> > That's why CPython has the notorious GIL (a giant lock around the
> > whole interpreter that stops more than one interpreter thread from
> > being active at a time), because putting locks on the refcounts
> > (someone tried in the late 90's) to allow multi-cpu parallelism
> > slows the interpreter to a crawl.
>
> All due to the ref-counter?  I find this really hard to be

  1   2   3   4   5   6   >