Re: Variable-width lookbehind
OKB (not okblacke) wrote: > Paul Rubin wrote: > > >> "OKB (not okblacke)" <[EMAIL PROTECTED]> writes: >> >>> For years now Python has not supported variable-length >>> lookbehinds. >>> >> I'm not sure what that is and the perl links you gave don't work, >> but it sounds evil. >> > > The links work fine for me. . . > > You're not sure what "variable-length lookbehinds" means? > Lookbehind is something that Python regexps already have. You can do > "(?<=one)two" to match "two" only if it's preceded by "one", and you can > do "(? What you can't do is "(?<=one|three)two", because Python requires that > the lookbehind contain only strings of a fixed length. What I'm asking > about is the possibility of lifting this limitation, to allow the > lookbehinds (positive and negative) to contain general regexps. I don't > see how this is in any way evil. > If not *evil*, then how about *unreadable*. Regular expressions are powerful, but nearly unreadable as they are. Allowing them to be even more complex just gets one step closer to *absolutely unreadable*. But that's not necessarily a reason to keep it out of the language. (Well actually, keeping Python's clarity-of-code goal in mind, it might be reason enough for some to want to keep it out.) But this is an all volunteer community. Your feature is not in the language because no one has cared enough to implement it. Or if some one has implemented it, no one has found it useful enough to lobby it into the language. Are you willing to implement it and lobby for it's inclusion? If so, good, we'll look at it. If not, then perhaps you understand perfectly why it's not yet included. Welcome to the world of Open Source! Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Book: Python Power!: The Comprehensive Guide
John Salerno wrote: > Anyone know anything about this book? I've read a few intro Python books > already, but I'm always interested in reading more to reinforce the > language. No reviews on Amazon yet so I'm not sure if it's good or not. > > Thanks. A cursory glance while standing in the bookshop suggest that I should give it a closer read - there are some interesting stuffs that caught my eyes but I only have time for a quick flip then. maurice -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i return a image in mod python ?
On Nov 18, 6:46 am, Abandoned <[EMAIL PROTECTED]> wrote:
> Hi..
> I want to show the pictures with mod python directly.
>
> def showimage(req):
> some process...
> open /var/www/a.jpg and print
>
> for example if i open:
> domain.com/a.py/showimage
> It must show me image directly (no redirect or html)
>
> How can i do it ?
> I'm sorry for my bad english.
> Kind Regards
How about:
def showimage(req):
req.content_type="image/jpeg" # Change to you image type
req.sendfile("/path/to/image.jpg")
return apache.OK
HTH
BTW mod_python has its own list :)
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list
keyword parameter order
I am looking for a way to determine the order of keyword parameters passed on to a class method. In the source code the keyword parameters are ordered, an ordering that is lost by putting them into a dictionary and then accessing them by using **kw. If I had this order (either of the keyword+value pairs or just of the keywords) I could meaningfully initialise my ordereddict implemenation (which uses Key Insertion Order or KeyValue Insertion Order). I looked at traceback (which shows this info if all the keywords are on one source line), and tracing that I found that it displays the sourcecode line based on the code-object found in the frame stack. I could persue that but I find the idea of reparsing the sourcecode kind of ugly (although doable, as the keyword are never variables, and I would not have to reevaluate the variables). I am not sure if this kind of info is available internally to the interpreter (ordereddict is in C, so I would even prefer that). Has anyone done this or anything like it? I could probably compile the python interpreter to use ordereddict instead of dict and then the parser would insert the keyword parameters in specification order in the **kw ordereddict, after which iteration over parameters would be ordered. I am pretty sure though if the 10% speed overhead of the ordereddict implementation compared to dict is going to prevent people from using such an interpreter version. As an aside: I think that allowing dict to be initialised from keyword parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of use of keyword parameters prevents any real keyword parameters. E.g. with 'maxsize' that restricts the dictionary size or 'unique' that would throw an Exception if an existing key gets reassigned. Anthon -- http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
MonkeeSage wrote: > Proposal: > > When an attribute lookup fails for an object, check the top-level > (and local scope?) for a corresponding function or attribute and apply > it as the called attribute if found, drop through to the exception > otherwise. This is just syntactic sugar. > > > Example: > > a = [1,2,3] > > a.len() > # -> fails, > # -> finds len() in the top-level symbol table, > # -> applies len(a) > # -> 3 > > a.foobar() > # -> fails, > # -> no foobar() in scope, > # -> raise NameError > > > Benefits: > > - Uniform OO style. Top-levels can be hidden as attributes of data. > Most of the top-level functions / constructors can be considered as > attributes of the data; e.g., an int() representation of a string can > be considered as _part_ of the semantics of the string (i.e., one > _meaning_ of the string is an int representation); but doing it this > way saves from storing the int (etc) data as part of the actual > object. The trade-off is speed for space. > > - Ability to "add" attributes to built-in types (which is requested > all the time!!) without having to sub-class a built-in type and > initialize all instances as the sub-class. E.g., one can simply define > flub() in the top-level (local?) namespace, and then use "blah".flub() > as if the built-in str class provided flub(). > > - Backwards compatible; one can use the top-level functions when > desired. No change to existing code required. > > - Seemingly trivial to implement (though I don't know much C). On > attribute lookup failure, simply iterate the symbol table looking for > a match, otherwise raise the exception (like current implementation). > > > Drawbacks: > > - Could hide the fact that an extra (On?) lookup on the symbol table > is necessary for attribute lookup failure. (Maybe there could be a > switch/pragma to enable (or disable) the functionality?) > > - As above, attribute lookup failure requires an extra lookup on the > symbol table, when normally it would fall through directly to > exception. > > - ??? > > > Disclaimer: > > I realize that very often what seems good to me, ends up being half- > assed, backwards and generally bad. So I'd appreciate input on this > proposition. Don't take it that I think the idea is wonderful and am > trying to push it. I am just throwing it out there to see what may > become of it. It would be unoriginal of me to suggest that this violates the explicit is better than implicit maxim. But it does. Also, you have picked the perfect use case for a counter argument: py> class NoLen(object): ... pass ... py> len(NoLen) Traceback (most recent call last): File "", line 1, in : object of type 'type' has no len() So this proposal would send the interpreter through two cycles of trying to find the proper attribute before it failed. Plus, I probably haven't even raised the best arguments against it, but my feeling is that it has serious problems and is better left out of the language. But it is an interesting idea nonetheless. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword parameter order
> I am not sure if this kind of info is available internally to the > interpreter (ordereddict is in C, so I would even prefer that). Has > anyone done this or anything like it? It's not available. See ceval.c:do_call; this fills the dictionary. >From then on, information about the order of keyword arguments is lost. > I could probably compile the python interpreter to use ordereddict > instead of dict and then the parser would insert the keyword > parameters in specification order in the **kw ordereddict, after which > iteration over parameters would be ordered. If you'ld do that literally, you'll find that the keyword arguments are in reverse order. > As an aside: I think that allowing dict to be initialised from keyword > parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of > use of keyword parameters prevents any real keyword parameters. E.g. > with 'maxsize' that restricts the dictionary size or 'unique' that > would throw an Exception if an existing key gets reassigned. For your own dictionary implementation, you are not required to follow this interface - in particular if you believe it was a mistake. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Commentary on Python 411 - Web 3.0 and Nanoprogramming
SamFeltus wrote: > Here's an interesting Podcast musing on the possible future of Python > and computing, illustrated and commentated by SonomaSunshine... > > Enjoy... > > http://samfeltus.com/kudzu/Nanoprogramming_podcast.html I work right across from the Nanosystems Institute, and now this! You know, having studied a lot of microbiology in college, I can't fathom the thought of being outdone. So I'm going to start doing femtoruminating, which reduces thought to its most fundamental particle, the mor-on. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword parameter order
> I am looking for a way to determine the order of keyword parameters
> passed on to a class method.
I'm fairly certain it's not possible, as how would code like this
behave:
def my_func(**kwd):
kwd = OrderedDict(kwd) #magic happens here?
return do_something(kwd)
my_dict = {'hello':42, 'world':3.14159}
print my_func(**my_dict)
This is regularly used in lots of code. The ordering of the
contents of my_dict is already lost before the my_func() ever
gets a chance to see it. And in case one suggests trying to
sniff the source-code for the ordering, it's easy to break with
things like
my_dict = read_dict_from_file(get_filename_from_user())
where the dict and its source are completely outside the scope of
the code.
The only way around it I see is to force the user to pass in an
ordered dict explicitly:
def my_func(ordered_dict_of_kwdargs):
return do_something(ordered_dict_of_kwdargs)
my_dict = OrderedDict()
my_dict['hello'] = 42
my_dict['world'] = 3.14159
print my_func(my_dict)
-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
On Nov 18, 4:07 am, MonkeeSage <[EMAIL PROTECTED]> wrote: > Proposal: > > When an attribute lookup fails for an object, check the top-level > (and local scope?) for a corresponding function or attribute and apply > it as the called attribute if found, drop through to the exception > otherwise. This is just syntactic sugar. [...] > Benefits: [...] > - Backwards compatible; one can use the top-level functions when > desired. No change to existing code required. It changes how the following code executes: -- def foo(x): return x.foo() foo(1) -- * currently this raises AttributeError * under your proposal this code would fill the stack and raise a RuntimeError I guess. > - Seemingly trivial to implement (though I don't know much C). On > attribute lookup failure, simply iterate the symbol table looking for > a match, otherwise raise the exception (like current implementation). This is not a benefit! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: SOAPpy port reuse
Maurice LING schrieb: > Hi, > > I have a problem: > > 1. Assuming that my application is a SOAP server that uses SOAPpy, > 2. I am given port 35021 for use. > > What I normally do (simply) is: > > functionlist = [] > import SOAPpy > server = SOAPpy.SOAPServer((, 35021)) > for func in functionlist: server.registerFunction(func) > server.serve_forever() > > My question is: How can I shutdown this server and reuse port 35021 when > my functionlist changes? > > Currently, after killing the python process which runs this SOAP server, > the port (35021 in this case) cannot be re-used, as though it is still > phantom-ly bounded to some process (which should have been killed). It shouldn't be that way. Either you still have some process lying around hogging the port. Or the OS needs a while to re-enable the port for allocation. That happened to me quite a few times. Shutting down gracefully might speed up things I guess. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
On 11/16/07, Shawn Milochik <[EMAIL PROTECTED]> wrote: > I completely support Wildemar. Lazy questions like that deserve absolutely > nothing. > > I agree that cushioning the reply with a brief explanation of why that > question sucks would have helped the original poster, but he doesn't deserve > any effort from any of us until he has shown evidence of his own efforts. > Then he will find a lot of friendly help. How do you know that he hasn't investigated this? Maybe all the google examples he found suck or he still has questions. *He* should have been wordier too, but you are assuming a lot. That being said, if he doesn't reply back my assumption is that he was just a troll, trying to ellicit a response similar Wildemar's. (which is all the more the reason to *not* respond in such a way) -- http://mail.python.org/mailman/listinfo/python-list
Re: SOAPpy port reuse
Diez B. Roggisch wrote: > Maurice LING schrieb: >> Hi, >> >> I have a problem: >> >> 1. Assuming that my application is a SOAP server that uses SOAPpy, >> 2. I am given port 35021 for use. >> >> What I normally do (simply) is: >> >> functionlist = [] >> import SOAPpy >> server = SOAPpy.SOAPServer((, 35021)) >> for func in functionlist: server.registerFunction(func) >> server.serve_forever() >> >> My question is: How can I shutdown this server and reuse port 35021 >> when my functionlist changes? >> >> Currently, after killing the python process which runs this SOAP >> server, the port (35021 in this case) cannot be re-used, as though it >> is still phantom-ly bounded to some process (which should have been >> killed). > > It shouldn't be that way. Either you still have some process lying > around hogging the port. Or the OS needs a while to re-enable the port > for allocation. That happened to me quite a few times. > > Shutting down gracefully might speed up things I guess. > I am under the impression that SOAPpy.SOAPServer.serve_forever() is an "endless" loop. I had been suggested to see if there is a method of SOAPpy.SOAPServer (which I can call through a wrapper function in functionlist) that can enable me to gracefully shutdown the server. Any advice? Thanks Maurice -- http://mail.python.org/mailman/listinfo/python-list
Re: Auto locate Python's .so on Linux (for cx_Freeze's --shared-lib-name)
robert wrote: > In a makefile I want to locate the .so for a dynamically linked > Python on Linux. (for cx_Freeze's --shared-lib-name) > e.g. by running a small script with that Python. How to? > > Robert How about run python -v yourscript and filter the output? -- http://mail.python.org/mailman/listinfo/python-list
Re: Commentary on Python 411 - Web 3.0 and Nanoprogramming
"""I work right across from the Nanosystems Institute, and now this! You know, having studied a lot of microbiology in college, I can't fathom the thought of being outdone. So I'm going to start doing femtoruminating, which reduces thought to its most fundamental particle, the mor-on. """ Perhaps, but Python libraries are deficient in facilities for generating shiny, frilly flashy thingies for the web... It's Sunday in Alabama, think I'll goto the Gulf and drink beer on the beach... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: SOAPpy port reuse
> Maurice LING <[EMAIL PROTECTED]> (ML) wrote: >ML> Hi, >ML> I have a problem: >ML> 1. Assuming that my application is a SOAP server that uses SOAPpy, >ML> 2. I am given port 35021 for use. >ML> What I normally do (simply) is: >ML> functionlist = [] >ML> import SOAPpy >ML> server = SOAPpy.SOAPServer((, 35021)) >ML> for func in functionlist: server.registerFunction(func) >ML> server.serve_forever() >ML> My question is: How can I shutdown this server and reuse port 35021 when my >ML> functionlist changes? >ML> Currently, after killing the python process which runs this SOAP server, >ML> the port (35021 in this case) cannot be re-used, as though it is still >ML> phantom-ly bounded to some process (which should have been killed). This phenomenon is explained here: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html or the Unix socket FAQ (http://www.faqs.org/faqs/unix-faq/socket/) 2.7 Normally the solution is to set the SO_REUSEADDR option in the socket (the original one) before binding it: s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) However, SOAPPy does that already so it should work. -- 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
sys.arg whitespace problem
Hi, Basically I want to get sys.argv[1: ] but the problem is that actually the argument should maintain whitespace. Thus if the arguments are something something with only one space between them, or something something with three spaces between them I should be able to maintain the exact whitespace between arguments. Cheers, Bryan Rasmussen -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets: why doesn't my connect() block?
On Sat, 17 Nov 2007 21:32:50 -0800 (PST), 7stud <[EMAIL PROTECTED]> wrote: >According to "Python in a Nutshell(2nd)", p. 523: > >connect: s.connect((host, port)) >... >Blocks until the server accepts or rejects the connection attempt. > >However, my client program ends immediately after the call to >connect()--even though my server program does not call accept(): > Your platform's TCP implementation acknowledges the connection attempt before your application calls accept(). This is fairly usual. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.arg whitespace problem
bryan rasmussen schrieb: > Hi, > > Basically I want to get sys.argv[1: ] but the problem is that actually > the argument should maintain whitespace. Thus if the arguments are > something something with only one space between them, or something > something with three spaces between them I should be able to maintain > the exact whitespace between arguments. That has nothing to do with python - it's a question of your shell. Because the shell is responsible for parsing the arguments, possibly instantiating variables or even executing subcalls. The resulting argument list is then passed to the C-main of python. So to pass arguments containing whitespace to python, do python myscript.py "an argument with whitespac in it" "another one" Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: What is python?????
Cope <[EMAIL PROTECTED]> wrote in news:7ab5b781-3c6c- [EMAIL PROTECTED]: > please tell me what is python.This group is so crowded. > I see nobody has chosen to answer your question seriously. I'll give you an answer, but it is probably not to the question you are asking, either. Python is not one thing. Python is the name of a computer language, which you can determine easily through Google or Wikipedia or other means. That's what comp(uter).lang(uage).python is here for, nominally. Python is also a package of programs that implement the language and create a Python runtime environment. The most common implementation is of a virtual machine that runs Python bytecodes, though other variations run Java or .NET bytecodes. And Python is also a set of packages that provide utilities and features that allow users of the packages to do useful things on their computers without unnecessary fuss and bother. Some of these utilities come with a basic Python installation (code name: "batteries included"), while others are available elsewhere, often from the Python Package Index (codename: "cheese shop"), but from other sources as well. Some people conflate these meanings of "Python", which can lead to confusion at times. Much of the crowdedness of the group has to do with discussion related to the batteries-included features and to the other packages written to run in the Python environment. Hope that helps. -- rzed -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting name of control under mouse in Windows?
En Fri, 16 Nov 2007 16:16:25 -0300, Shane Clark <[EMAIL PROTECTED]> escribi�: > I am trying to get my python app to output the name of the control under > the mouse each time it is clicked. Currently, I am trying to do this > with a combination of pyhook and pyAA, but pyAA gives me "pyAA.Error: > -2147417843" for almost any control in Microsoft Office apps, for > example. If it matters, I am trying to retrieve the control's name based > on the mouse position coordinates. pywinauto does that. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
how to resize a window with a specific name with python-xlib
The python-xlib documentation is confusing for me..and the examples are too few :-( I need simply to resize a window (named "firefox" for example), but before I need the window's id, how can i obtain this id? thanks in advance and please excuse me for my bad english.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Which uses less memory?
En Sat, 17 Nov 2007 19:30:04 -0300, Nick Craig-Wood <[EMAIL PROTECTED]>
escribi�:
>> I'm working on an application that is very memory intensive, so we're
>> trying to reduce the memory footprint of classes wherever possible. I
>
> I'd guess that if you __slot__-ed the Domain class then you'll find
> the overhead of a type attribute is minimal (4 bytes per instance I
> think).
>
> No idea about Hessian or Stomp (never heard of them!) but classes with
> __slot__s are normal classes which would pickle or unpickle.
Actually classes with __slots__ require that you write your own
__getstate__ and __setstate__. The following implementation may be enough
in simple cases:
py> class X(object):
... __slots__ = ('foo','bar')
...
py> x = X()
py> x.foo = 123
py> dumps(x)
Traceback (most recent call last):
...
TypeError: a class that defines __slots__ without defining __getstate__
cannot b
e pickled
class X(object):
__slots__ = ('foo','bar')
def __getstate__(self):
return dict((name, getattr(self, name))
for name in self.__slots__
if hasattr(self, name))
def __setstate__(self, state):
for name,value in state.iteritems():
setattr(self, name, value)
py> x = X()
py> x.foo = 123
py> p = dumps(x)
py> x2 = loads(p)
py> type(x2)
py> x2.foo
123
py> x2.bar
Traceback (most recent call last):
File "", line 1, in
AttributeError: bar
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Looking for a event-message-qeue framework
Hi, I am looking for a kind of framework that let's me send events between systems. What I had in mind is common event bus that can be spread over multiple systems. On each system, there should be sort of an 'agent' that listens to the events on the bus and acts upon them if they are destined for the agent. The agent should also be able to send events. Some queue mechanism would also be nice. Is there something like this in Python? (I really want to avoid Java or MQ series) Eric -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets: why doesn't my connect() block?
On Nov 18, 8:18 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > On Sat, 17 Nov 2007 21:32:50 -0800 (PST), 7stud <[EMAIL PROTECTED]> wrote: > >According to "Python in a Nutshell(2nd)", p. 523: > > >connect: s.connect((host, port)) > >... > >Blocks until the server accepts or rejects the connection attempt. > > >However, my client program ends immediately after the call to > >connect()--even though my server program does not call accept(): > > Your platform's TCP implementation acknowledges the connection attempt > before your application calls accept(). This is fairly usual. > > Jean-Paul Has my platform rejected or accepted the connection? If it accepted the connection, then why do I have to call accept()? Or is "Python in Nutshell" wrong? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Design Patterns - composition vs. inheritance
On 17 Nov, 19:58, Carl Banks <[EMAIL PROTECTED]> wrote: > Google for Liskov Substitutability if you are interested. I didn't pull > this idea out of my hat. In fact I learned the term from reading a post > by GvR himself, though the idea was intuitive to me long before that. > > Carl Banks Interesting... I think I've actually had problems in the past beacause I did not understand this. -- http://mail.python.org/mailman/listinfo/python-list
Re: SOAPpy port reuse
En Sun, 18 Nov 2007 11:17:42 -0300, Maurice LING <[EMAIL PROTECTED]> escribi�: > Diez B. Roggisch wrote: >> Maurice LING schrieb: >>> My question is: How can I shutdown this server and reuse port 35021 >>> when my functionlist changes? >> >> Shutting down gracefully might speed up things I guess. >> > I am under the impression that SOAPpy.SOAPServer.serve_forever() is an > "endless" loop. I had been suggested to see if there is a method of > SOAPpy.SOAPServer (which I can call through a wrapper function in > functionlist) that can enable me to gracefully shutdown the server. serve_forever is inherited from SocketServer.BaseServer and it's just an infinite loop calling self.handle_request() over and over. You have to break out of the loop somehow and call self.server_close(). Something like this (untested): def serve_forever(self): while not self.some_flag_to_indicate_it_has_to_stop: self.handle_request() self.server_close() -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Book: Python Power!: The Comprehensive Guide
Maurice LING wrote: > John Salerno wrote: >> Anyone know anything about this book? I've read a few intro Python books >> already, but I'm always interested in reading more to reinforce the >> language. No reviews on Amazon yet so I'm not sure if it's good or not. >> >> Thanks. > > > A cursory glance while standing in the bookshop suggest that I should > give it a closer read - there are some interesting stuffs that caught my > eyes but I only have time for a quick flip then. > > maurice Thanks. My nearest Barnes & Noble doesn't usually have stuff like this, but I'll see if they do and maybe I can get a better look myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
[EMAIL PROTECTED] wrote: > On Nov 15, 2:38 pm, "SMALLp" <[EMAIL PROTECTED]> wrote: >> Could someone please paste some program in wxPython that uses inharitance. I >> would be very thankfull. > > Most examples of wxPython use inheritance. I would recommend going to > their website and downloading the demo as it has lots of code to learn > from. > > www.wxpython.org > > They also have a mostly helpful wiki here: > > http://wiki.wxpython.org/ > > Also see: > > http://zetcode.com/wxpython/ > http://showmedo.com/videos/series?name=PythonWxPythonBeginnersSeries > http://www.onlamp.com/pub/a/python/excerpts/chpt20/wxpython.html > http://www.linuxjournal.com/article/3776 > > Mike Also, the newsgroup gmane.comp.python.wxpython is excellent for help and advice -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets: why doesn't my connect() block?
On Nov 18, 10:40 am, 7stud <[EMAIL PROTECTED]> wrote: > If it accepted > the connection, then why do I have to call accept()? That should read: If my platform accepted the connection, then why does my server program have to call accept()? -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword parameter order
Martin, Thanks for pointing this out. I might have found that code eventualy but it would have taken me quite sometime. There was a request from a user to make ordereddict more of drop-in replacement for dict. That can be already be done by specifying the relax keyword parameter (or defining a subclass that does so), but it made me revisit the idea of investigating the keyword parameter order.. I will just drop this idea Thanks Anthon On Nov 18, 12:08 pm, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > > I am not sure if this kind of info is available internally to the > > interpreter (ordereddict is in C, so I would even prefer that). Has > > anyone done this or anything like it? > > It's not available. See ceval.c:do_call; this fills the dictionary. > From then on, information about the order of keyword arguments is > lost. > > > I could probably compile the python interpreter to use ordereddict > > instead of dict and then the parser would insert the keyword > > parameters in specification order in the **kw ordereddict, after which > > iteration over parameters would be ordered. > > If you'ld do that literally, you'll find that the keyword arguments are > in reverse order. > > > As an aside: I think that allowing dict to be initialised from keyword > > parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of > > use of keyword parameters prevents any real keyword parameters. E.g. > > with 'maxsize' that restricts the dictionary size or 'unique' that > > would throw an Exception if an existing key gets reassigned. > > For your own dictionary implementation, you are not required to follow > this interface - in particular if you believe it was a mistake. > > Regards, > Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword parameter order
Hi Tim,
Thanks for the comments, I obviously hadn't thought beyond the simple
case.
I am happy I wrote (and that you Martin answered) instead of trying to
program myself into a halffunctional implementation %-)
Regards
Anthon
On Nov 18, 1:40 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > I am looking for a way to determine the order of keyword parameters
> > passed on to a class method.
>
> I'm fairly certain it's not possible, as how would code like this
> behave:
>
> def my_func(**kwd):
> kwd = OrderedDict(kwd) #magic happens here?
> return do_something(kwd)
>
> my_dict = {'hello':42, 'world':3.14159}
> print my_func(**my_dict)
>
> This is regularly used in lots of code. The ordering of the
> contents of my_dict is already lost before the my_func() ever
> gets a chance to see it. And in case one suggests trying to
> sniff the source-code for the ordering, it's easy to break with
> things like
>
> my_dict = read_dict_from_file(get_filename_from_user())
>
> where the dict and its source are completely outside the scope of
> the code.
>
> The only way around it I see is to force the user to pass in an
> ordered dict explicitly:
>
> def my_func(ordered_dict_of_kwdargs):
> return do_something(ordered_dict_of_kwdargs)
> my_dict = OrderedDict()
> my_dict['hello'] = 42
> my_dict['world'] = 3.14159
> print my_func(my_dict)
>
> -tkc
--
http://mail.python.org/mailman/listinfo/python-list
Simple eval
Hi,
A while ago I asked a question on the list about a simple eval
function, capable of eval'ing simple python constructs (tuples, dicts,
lists, strings, numbers etc) in a secure manner:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/58a01273441d445f/
>From the answers I got I chose to use simplejson... However, I was
also pointed to a simple eval function by Fredrik Lundh:
http://effbot.org/zone/simple-iterator-parser.htm. His solution, using
module tokenize, was short and elegant. So I used his code as a
starting point for simple evaluation of dicts, tuples, lists, strings,
unicode strings, integers, floats, None, True, and False. I've
included the code below, together with some basic tests, and
profiling... On my computer (winXP, python 2.5), simple eval is about
5 times slower than builtin eval...
Comments, speedups, improvements in general, etc are appreciated. As
this is a contribution to the community I suggest that any
improvements are posted in this thread...
-Tor Erik
Code (tested on 2.5, but should work for versions >= 2.3):
'''
Recursive evaluation of:
tuples, lists, dicts, strings, unicode strings, ints, floats,
True, False, and None
'''
import cStringIO, tokenize, itertools
KEYWORDS = {'None': None, 'False': False, 'True': True}
def atom(next, token):
if token[1] == '(':
out = []
token = next()
while token[1] != ')':
out.append(atom(next, token))
token = next()
if token[1] == ',':
token = next()
return tuple(out)
elif token[1] == '[':
out = []
token = next()
while token[1] != ']':
out.append(atom(next, token))
token = next()
if token[1] == ',':
token = next()
return out
elif token[1] == '{':
out = {}
token = next()
while token[1] != '}':
key = atom(next, token)
next() # Skip key-value delimiter
token = next()
out[key] = atom(next, token)
token = next()
if token[1] == ',':
token = next()
return out
elif token[1].startswith('u'):
return token[1][2:-1].decode('unicode-escape')
elif token[0] is tokenize.STRING:
return token[1][1:-1].decode('string-escape')
elif token[0] is tokenize.NUMBER:
try:
return int(token[1], 0)
except ValueError:
return float(token[1])
elif token[1] in KEYWORDS:
return KEYWORDS[token[1]]
raise SyntaxError('malformed expression (%r)¨' % token[1])
def simple_eval(source):
src = cStringIO.StringIO(source).readline
src = tokenize.generate_tokens(src)
src = itertools.ifilter(lambda x: x[0] is not tokenize.NL, src)
res = atom(src.next, src.next())
if src.next()[0] is not tokenize.ENDMARKER:
raise SyntaxError("bogus data after expression")
return res
if __name__ == '__main__':
expr = (1, 2.3, u'h\xf8h\n', 'h\xc3\xa6', ['a', 1],
{'list': [], 'tuple': (), 'dict': {}}, False, True, None)
rexpr = repr(expr)
a = simple_eval(rexpr)
b = eval(rexpr)
assert a == b
import timeit
print timeit.Timer('eval(rexpr)', 'from __main__ import
rexpr').repeat(number=1000)
print timeit.Timer('simple_eval(rexpr)', 'from __main__ import
rexpr, simple_eval').repeat(number=1000)
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to resize a window with a specific name with python-xlib
my apologies..:-( the answer is in the shortest python-xlib example, profilex.py -- http://mail.python.org/mailman/listinfo/python-list
Help with sympy, please
from __future__ import division Here's what I'm trying to do, but using sympy: = from math import e n = 1 prod = 1 k = 0 while k < 1000: k += 1 term = (e**(1.0/n))/(e**(1.0/(n+1))) prod *= term n += 2 print prod, term Output: 1.99950018746 1.0025013 (the limit is 2) from sympy import * from sympy import Rational as R from sympy.numerics import * prec = 50 Float.setdps(prec) e = evalf(E) n = 1 k = 0 prod = evalf(R(1,1)) while k < 1000: k += 1 n = evalf(R(n,1)) term = (e**(1/n))/(e**(1/(n+1))) prod *= term n += 2 print prod, term === This gets: Traceback (most recent call last): File "E:\PythonWork\Untitled 5.py", line 20, in term = (e**(1/n))/(e**(1/(n+1))) TypeError: unsupported operand type(s) for /: 'int' and 'Float' Thanks, Dick Moores -- http://mail.python.org/mailman/listinfo/python-list
regular expression
I just can't seem to get it: I was having some trouble with finding the first > > """ print "The First approach - flags in finditer" rex = re.compile(r'^<(?P[a-zA-Z0-9_]*)') for i in rex.finditer(TESTTXT,re.MULTILINE): print i,i.groups() print "The Second approach - flags in pattern " rex = re.compile(r'(?m)^<(?P[a-zA-Z0-9_]*)') for i in rex.finditer(TESTTXT): print i,i.groups() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too complex ?!?!?!
On Nov 17, 3:21 pm, Tim Chase <[EMAIL PROTECTED]> wrote: > > programmer, but he claims that the install, config, and > > library models for C# have proved to be less > > problematic than Python. So both his courses (intro, > > data structs, algorithms) are taught in C#. > > A little anecdotal comparison from some of my experience with two > web apps deployed at my current company: > > One web app, written in C#/ASP.net one written in Python. > > Moved each app to new servers (C#/ASP.net on a new Windows box, > Python app on a shiny new Debian box). > > C#/ASP.net app: had to find and install the right version of the > .net libraries. That's an afternoon of my life I won't get back. > > Python app: copied my app > > C#/ASP.net app: couldn't find VS2003 (in which the app had been > written) any more so had to upgrade to VS2005. > > Python app: Continued to use the same development environment. > > C#/ASP.net app: (ASP specific) generally requires following a > particular convention. Writing a RESTful web app is next to > impossible given the reliance on the postbacks; and the server > environment doesn't make it easy to make clean URLs > > Python app: Django makes web-app development easy and > clean/RESTful (other frameworks may as well...I speak from Django > experience) and push you to Do The Right Thing (tm) > > C#/ASP.net app: had to re-partition my server containers so that > it could deploy .Net 2.0 and .Net 3.0 apps side-by-side > > Python app: I've had Python 2.3, 2.4 and 2.5 running on the same > machine without a thought > > C#/ASP.net app: libraries are often written to a particular > framework version, so if any new functionality requires the new > version the whole app needs to be migrated. > > Python app: most of the libraries I use come built in, or they > work with 2.3 or later. > > C#/ASP.net app: Installing new libraries, same as upgrading > currently-used libraries. Usually requires paying for, then > manually installing various libraries, clearing distribution > rights, etc. > > Python app: There are an abundance libraries that are just an > apt-get away in terms of difficulty, and they are Free Software > so I can install them and deploy them without additional costs. > > C#/ASP.net app: 3rd party libraries usually come as source-less > DLLs that you can't peer into > > Python app: 3rd party libraries are usually pure python which > you can modify or step into as needed > > C#/ASP.net app: really only works well on Windows > > Python app: works well on Windows, Linux, BSD, Mac OS X... > > C#/ASP.net app: really requires Visual Studio > > Python app: works well with Eclipse, Vim, Emacs, Wing IDE, > Komodo, Idle, and piles of other development environments. Heck, > I've written the occasional python program using "ed" or "cat > > x.py". > > C#/ASP.net app: files are scattered all over. You've got source > apps, you've got templates, you've got resource files, you've got > GUID files. And VS hides the complexity so when (not "if") > something breaks you get a crash course in what goes on under the > covers. > > Python app: I've got .py files (and sometimes templates for my > Django code, and could have I18N files for translations). Very > easy to track down where everything is. > > C#/ASP.net app: Code/syntax is horridly opaque, requires braces > and lots of additional overhead code to get things done. Compare > the clutter of a basic C# script with a similarly function Python > script. How much is pure syntactic overhead? > > Python app: Code/syntax is rather easy to read (once you > understand list comprehensions and the __foo__ methods) > > Yeah, I'd take Python any day...for implementation *OR* for > teaching someone how to program. > > -tkc Thank you very much for this VERY useful summary. It gives me tons of ammunition in case the latest .Net zealot walks into my office :) -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
gardsted schrieb: > I just can't seem to get it: > I was having some trouble with finding the first following with this regex: > > Should these two approaches behave similarly? > I used hours before I found the second one, > but then again, I'm not so smart...: > > kind retards > jorgen / de mente > using python 2.5.1 > --- > import re > > TESTTXT="""SAMPLES "" "" > > >MAINSEND 1 >ACT 1 > > >ACT 1 > > > > > > > """ > print "The First approach - flags in finditer" > rex = re.compile(r'^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT,re.MULTILINE): > print i,i.groups() > > print "The Second approach - flags in pattern " > rex = re.compile(r'(?m)^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT): > print i,i.groups() What the heck is that format? XML's retarded cousin living in the attic? Ok, back to the problem then... This works for me: rex = re.compile(r'^<(?P[a-zA-Z0-9_]+)',re.MULTILINE) for i in rex.finditer(TESTTXT): print i,i.groups() However, you might think of getting rid of the ^ beceause otherwise you _only_ get the first tag beginning at a line. And making the * a + in the TAGNAME might also be better. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
On Nov 18, 5:27 am, James Stroud <[EMAIL PROTECTED]> wrote: > It would be unoriginal of me to suggest that this violates the explicit > is better than implicit maxim. But it does. That's what I meant about hiding the complexity of an attribute failure. Though, sometimes implicit is acceptable (e.g., promotion of int to float by __add__ when RHS is a float). Perhaps not here though. > Also, you have picked the perfect use case for a counter argument: > > py> class NoLen(object): > ... pass > ... > py> len(NoLen) > > Traceback (most recent call last): >File "", line 1, in > : object of type 'type' has no len() > > So this proposal would send the interpreter through two cycles of trying > to find the proper attribute before it failed. Ah. Good point. Hadn't thought of that. On Nov 18, 6:42 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > It changes how the following code executes: > > -- > def foo(x): return x.foo() > foo(1) > -- > > * currently this raises AttributeError > * under your proposal this code would fill the stack and raise a > RuntimeError I guess. I think it would be easy enough to detect and avoid cyclic references like that (it's done in other instances in the language). An exception could be thrown in such a case. But maybe it would be more difficult than I imagine, leading to even further complexity (bad). I think that, given that it hides a complex operation (which could easily lead to abuse by the "unwashed masses"), and that in many cases multiple lookups in the symbol table would be necessary before termination (as in James' example above), as well as having to deal with cases such as you mention, perhaps it's not such a good idea. Off the cuff, it seemed like a nice feature (and still does, if it could be implemented without the drawbacks). But such is life. :) Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Auto locate Python's .so on Linux (for cx_Freeze's --shared-lib-name)
James Stroud wrote:
> robert wrote:
>> In a makefile I want to locate the .so for a dynamically linked Python
>> on Linux. (for cx_Freeze's --shared-lib-name)
>> e.g. by running a small script with that Python. How to?
>>
>> Robert
>
> def findaso(aso):
> import os
> for apath in os.sys.path:
> if not apath.startswith(os.path.sep):
> apath = os.path.join(os.path.curdir, apath)
> try:
> files = os.listdir(apath)
> except OSError:
> pass
> if aso in files:
> return apath
>
>
> py> def findaso(aso):
> ... import os
> ... for apath in os.sys.path:
> ... if not apath.startswith(os.path.sep):
> ... apath = os.path.join(os.path.curdir, apath)
> ... try:
> ... files = os.listdir(apath)
> ... except OSError:
> ... pass
> ... if aso in files:
> ... return apath
> ...
> py> findaso('_tkinter.so')
> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload'
>
>
> James
>
I'd need to know already the name and oon this installation it is
for example /usr/lib/libpython2.4.so.1.0
/usr/lib is not in sys.path
Robert
--
http://mail.python.org/mailman/listinfo/python-list
Re: Auto locate Python's .so on Linux (for cx_Freeze's --shared-lib-name)
Neal Becker wrote: > robert wrote: > >> In a makefile I want to locate the .so for a dynamically linked >> Python on Linux. (for cx_Freeze's --shared-lib-name) >> e.g. by running a small script with that Python. How to? >> >> Robert > > How about run python -v yourscript and filter the output? > for examples here python -v delivers many other python module paths, but not Python's .so. For example /usr/lib/libpython2.4.so.1.0 Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too complex ?!?!?!
Paddy wrote: > On Nov 17, 1:46 pm, Brian <[EMAIL PROTECTED]> wrote: >> Had a unsettling conversation with a CS instructor that >> teaches at local high schools and the community >> college. This person is a long-term Linux/C/Python >> programmer, but he claims that the install, config, and >> library models for C# have proved to be less >> problematic than Python. He has a point. Many Python enthusiasts are in denial about this, but, face it, the binary library situation isn't in good shape. Try running something that needs, say, MySQL and OpenSSL on a shared hosting server and see how far you get. Or try to install the same set of modules on both Linux and Windows. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: What is python?????
Damn! I joined this group because I thought it was a pie-a-thon. All that practice has now gone to waste/waist. -- http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
Ps. Just for kicks, here is a simple ruby 1.8 mock-up of the proposal
(sorry for using ruby, but I don't know enough C to start hacking the
CPython backend; I think that a higher-level example is conceptually
clearer anyhow). Reference cycles are not detected in the example.
#!/usr/bin/ruby
class Object
def method_missing(fun, *args)
begin
TOPLEVEL_BINDING.method(fun).call(self, *args)
rescue
raise(NoMethodError,
%{undefined method `#{fun.to_s}' for "#{self}":String},
[])
end
end
end
def myfun(s1, s2)
s1 + s2
end
puts "foo".myfun("bar")
# -> foobar
puts 1.myfun(2)
# -> 3
puts "foo".nofun("baz")
# -> ./attr_fail.rb:10: undefined method `nofun' for "foo":String
(NoMethodError)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Troubleshooting garbage collection issues
On Nov 17, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > Hi folks - wondering if anyone has any pointers on troubleshooting > garbage collection. My colleagues and I are running into an > interesting problem: > > Intermittently, we get into a situation where the garbage collection > code is running in an infinite loop. The data structures within the > garbage collector have been corrupted, but it is unclear how or why. > The problem is extremely difficult to reproduce consistently as it is > unpredictable. > > The infinite loop itself occurs in gcmodule.c, update_refs. After > hitting this in the debugger a couple of times, it appears that that > one of the nodes in the second or third generation list contains a > pointer to the first generation head node. The first generation was > cleared shortly before the call into this function, so it contains a > prev and next which point to itself. Once this loop hits that node, > it spins infinitely. > > Chances are another module we're depending on has done something > hinkey with GC. The challenge is tracking that down. If anyone has > seen something like this before and has either pointers to specific GC > usage issues that can create this behavior or some additional thoughts > on tricks to track it down to the offending module, they would be most > appreciated. > > You can assume we've done some of the "usual" things - hacking up > gcmodule to spit information when the condition occurs, various > headstands and gymnastics in an attempt to identify reliable steps to > reproduce - the challenge is the layers of indirection that we think > are likely present between the manifestation of the problem and the > module that produced it. Does "usual things" also include compiling with --with-pydebug? You could also try the various memory debuggers. A refcounting error is the first thing that comes to mind, although I can't see off hand how this specific problem would come about. Are you using threading at all? Do you see any pattern to the types that have the bogus pointers? -- Adam Olsen, aka Rhamphoryncus -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
Ups - got it - there are no flags in finditer;-) So rtfm, once again, jorgen! gardsted wrote: > I just can't seem to get it: > I was having some trouble with finding the first following with this regex: > > Should these two approaches behave similarly? > I used hours before I found the second one, > but then again, I'm not so smart...: > > kind retards > jorgen / de mente > using python 2.5.1 > --- > import re > > TESTTXT="""SAMPLES "" "" > > >MAINSEND 1 >ACT 1 > > >ACT 1 > > > > > > > """ > print "The First approach - flags in finditer" > rex = re.compile(r'^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT,re.MULTILINE): > print i,i.groups() > > print "The Second approach - flags in pattern " > rex = re.compile(r'(?m)^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT): > print i,i.groups() -- http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
On 19 Nov., 00:02, MonkeeSage <[EMAIL PROTECTED]> wrote: > Ps. Just for kicks, here is a simple ruby 1.8 mock-up of the proposal > (sorry for using ruby, but I don't know enough C to start hacking the > CPython backend; I think that a higher-level example is conceptually > clearer anyhow). No need to excuse. I think Ruby provides a nice context for discussing the semantics of top level "open classes". But I think those are entirely different than your contextual bindings. Note I find your proposal somewhat confusing since I expect that an attribute is "owned" by an object and is not an arbitrary contextual property. Regarding open classes in Python, what about "extension classes"? class +object: def len(self): return self.__len__() This either adds the len method to the namespace of object or it creates a new namespace which is associated with the namespace of object s.t. each object can lookup attributes in this namespace when default lookup fails. I'm not entirely sure about scope. I think the lifetime of an extension class shall be determined by the lifetime of the extended class and not by the scope in which the extension class is defined. What do you think? Kay PS. you can use EasyExtend when you want to provide a language extension without hacking the CPython runtime. EE was made for such kinds of experiments. -- http://mail.python.org/mailman/listinfo/python-list
RE: Getting name of control under mouse in Windows?
> To: [email protected] > From: [EMAIL PROTECTED] > Subject: Re: Getting name of control under mouse in Windows? > Date: Sun, 18 Nov 2007 13:32:54 -0300 > > En Fri, 16 Nov 2007 16:16:25 -0300, Shane Clark > escribi�: > >> I am trying to get my python app to output the name of the control under >> the mouse each time it is clicked. Currently, I am trying to do this >> with a combination of pyhook and pyAA, but pyAA gives me "pyAA.Error: >> -2147417843" for almost any control in Microsoft Office apps, for >> example. If it matters, I am trying to retrieve the control's name based >> on the mouse position coordinates. > > pywinauto does that. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list Thanks for the response. Pywinauto is more or less incompatible with Office apps so far as I can tell. According to what I have read, this is because Office does not use standard Windows controls. For more info: http://forums.openqa.org/message.jspa?messageID=28199 Shane _ You keep typing, we keep giving. Download Messenger and join the i’m Initiative now. http://im.live.com/messenger/im/home/?source=TAGLM -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
At 03:42 PM 11/18/2007, Dennis Lee Bieber wrote: >On Sun, 18 Nov 2007 13:02:01 -0800, Dick Moores <[EMAIL PROTECTED]> >declaimed the following in comp.lang.python: > > > > > This gets: > > Traceback (most recent call last): > >File "E:\PythonWork\Untitled 5.py", line 20, in > > term = (e**(1/n))/(e**(1/(n+1))) > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > > Seems self-explanatory... try using 1.0 rather than 1 term = (e**(1.0/n))/(e**(1.0/(n+1))) TypeError: unsupported operand type(s) for /: 'float' and 'Float' Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
On Nov 19, 2007 1:05 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > At 03:42 PM 11/18/2007, Dennis Lee Bieber wrote: > >On Sun, 18 Nov 2007 13:02:01 -0800, Dick Moores <[EMAIL PROTECTED]> > >declaimed the following in comp.lang.python: > > > > > > > > This gets: > > > Traceback (most recent call last): > > >File "E:\PythonWork\Untitled 5.py", line 20, in > > > term = (e**(1/n))/(e**(1/(n+1))) > > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > > > > Seems self-explanatory... try using 1.0 rather than 1 > > term = (e**(1.0/n))/(e**(1.0/(n+1))) > TypeError: unsupported operand type(s) for /: 'float' and 'Float' Hi Dick, I recognize you from python-list, where you had a question about mpmath. Your code still won't work if you convert the numbers to Floats because the Float type in sympy.numerics does not implement ** for fractional numbers. You could use the exp function in sympy.numerics.functions instead to compute e**x. Basically, sympy.numerics is an old version of mpmath. The sympy.numerics module is not very well integrated in SymPy, slower than mpmath, and has a couple bugs that have subsequently been fixed in mpmath. In sympycore (http://code.google.com/p/sympycore/), we're using the latest version of mpmath and integrating it directly into the symbolic engine; it will be much more robust and user-friendly. It will hopefully not be long until we merge the improvements we've done in the sympycore project with the main SymPy branch. Fredrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Log Search code is not working
This might be a perfect application for nucular. http://nucular.sourceforge.net If you need help using it I can help a bit by email (not on the list). If you want to build your own solution, what you have might be fixable, but you need to take out the lowest level loops by using dictionaries and the dictionary.has_key(...) method instead of looping over lists. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=long+necked On Nov 18, 7:12 pm, "martin" <[EMAIL PROTECTED]> wrote: > Hello, > > I need some help with my job assignment and the code that is not working. I > am to search all log files and print out how many "name" > used "fields" in all the logs? I have a list of about 50 names and 50 fields > and now i need search and count. > > How to search regardless of the case? > > This what I wrote it does not work or it just ran so slow that I had to stop > it. > > Oh and I have about 100 web logs to search. > > import os > ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
At 04:26 PM 11/18/2007, Fredrik Johansson wrote: >On Nov 19, 2007 1:05 AM, Dick Moores <[EMAIL PROTECTED]> wrote: >Hi Dick, I recognize you from python-list, where you had a question >about mpmath. > >Your code still won't work if you convert the numbers to Floats >because the Float type in sympy.numerics does not implement ** for >fractional numbers. You could use the exp function in >sympy.numerics.functions instead to compute e**x. Thanks, Fredrik, but I get the same error using either exp or power: from __future__ import division from sympy import * from sympy import Rational as R from sympy.numerics import * from sympy.numerics.functions import power, exp prec = 50 Float.setdps(prec) e = evalf(E) n = 1 m = n + 1 k = 0 n = evalf(R(n,1)) m = evalf(R(m,1)) prod = evalf(R(1,1)) prec = 50 Float.setdps(prec) e = evalf(E) n = 1 k = 0 prod = evalf(R(1,1)) while k < 1000: k += 1 n = evalf(R(n,1)) term = (exp(1/n))/(exp(1/(n+1))) prod *= term n += 2 print prod, term = term = (exp(1/n))/(exp(1/(n+1))) TypeError: unsupported operand type(s) for /: 'int' and 'Float' And also if I use sympy.numerics.functions.power in that line, as term = power(e,(1/n))/power(e,(1/(n+1))) I get: term = power(e,(1/n))/power(e,(1/(n+1))) TypeError: unsupported operand type(s) for /: 'int' and 'Float' Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets: why doesn't my connect() block?
7stud wrote: > If my platform accepted the connection, then why does my server > program have to call accept()? By making the listen() call, you've indicated your willingness to accept connections. The accept() call just gives you a file descriptor for the accepted connection (it's perhaps a little misnamed in that regard). -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: A proposal for attribute lookup failures
On Nov 18, 5:59 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote: > No need to excuse. I think Ruby provides a nice context for discussing > the semantics of top level "open classes". But I think those are > entirely different than your contextual bindings. Note I find your > proposal somewhat confusing since I expect that an attribute is > "owned" by an object and is not an arbitrary contextual property. I obviously like ruby as well as python, I just didn't want to turn the discussion into a "I can do this in ruby, can you do that in python" thread, so my apology was more along those lines that an apology for using ruby at all. :) As far as "ownership" of an object, that's what object abstraction is all about is it not? Multiple instances can "own" a method via polymorphic substitution, without a strict interface definition. My proposal simply adds a new scope within which to look for "ownership". Of course, there are problems with that, as noted above. > Regarding open classes in Python, what about "extension classes"? > > class +object: >def len(self): >return self.__len__() > > This either adds the len method to the namespace of object or it > creates a new namespace which is associated with the namespace of > object s.t. each object can lookup attributes in this namespace when > default lookup fails. I'm not entirely sure about scope. I think the > lifetime of an extension class shall be determined by the lifetime of > the extended class and not by the scope in which the extension class > is defined. What do you think? Sounds like a interesting approach! Worth looking into, imo. > PS. you can use EasyExtend when you want to provide a language > extension without hacking the CPython runtime. EE was made for such > kinds of experiments. Hadn't seen that before, thanks for the reference. :) Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
At 04:26 PM 11/18/2007, Fredrik Johansson wrote: >Basically, sympy.numerics is an old version of mpmath. The >sympy.numerics module is not very well integrated in SymPy, slower >than mpmath, and has a couple bugs that have subsequently been fixed >in mpmath. In sympycore (http://code.google.com/p/sympycore/), we're >using the latest version of mpmath and integrating it directly into >the symbolic engine; it will be much more robust and user-friendly. It >will hopefully not be long until we merge the improvements we've done >in the sympycore project with the main SymPy branch. > >Fredrik OK, I tried mpmath again, and to my surprise, it went well! === #!/usr/bin/env python #coding=utf-8 from mpmath import * mpf.dps = 50 n = 1 k = 0 prod = mpf(1) while k < 10: k += 1 term = exp(1.0/n)/exp(1.0/(n+1)) prod *= term n += 2 print prod, term == Output: 1.95187499635016028080844735182389158683797 1.00250001250004074790133889386806610626172 Thanks, Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
On Nov 19, 2007 2:03 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > At 04:26 PM 11/18/2007, Fredrik Johansson wrote: > >On Nov 19, 2007 1:05 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > >Hi Dick, I recognize you from python-list, where you had a question > >about mpmath. > > > >Your code still won't work if you convert the numbers to Floats > >because the Float type in sympy.numerics does not implement ** for > >fractional numbers. You could use the exp function in > >sympy.numerics.functions instead to compute e**x. > > Thanks, Fredrik, but I get the same error using either exp or power: > > from __future__ import division > from sympy import * > from sympy import Rational as R > from sympy.numerics import * > from sympy.numerics.functions import power, exp > > prec = 50 > Float.setdps(prec) > e = evalf(E) > n = 1 > m = n + 1 > k = 0 > n = evalf(R(n,1)) > m = evalf(R(m,1)) > prod = evalf(R(1,1)) > prec = 50 > Float.setdps(prec) > e = evalf(E) > n = 1 > k = 0 > prod = evalf(R(1,1)) > while k < 1000: > k += 1 > n = evalf(R(n,1)) > term = (exp(1/n))/(exp(1/(n+1))) > prod *= term > n += 2 > print prod, term > = > term = (exp(1/n))/(exp(1/(n+1))) > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > And also if I use sympy.numerics.functions.power in that line, as > term = power(e,(1/n))/power(e,(1/(n+1))) > > I get: > > term = power(e,(1/n))/power(e,(1/(n+1))) > TypeError: unsupported operand type(s) for /: 'int' and 'Float' Try not using "from __future__ import division". Also, n = evalf(R(n,1)) won't work, because the arguments to Rational must be ints. Fredrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
On Nov 19, 2007 2:09 AM, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Sun, 18 Nov 2007 16:05:15 -0800, Dick Moores <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > TypeError: unsupported operand type(s) for /: 'float' and 'Float' > > > > > What restrictive system can't even coerce a Python float to their > own internal data type? > > Does that library have any functions for type conversion? Float(1) > (or Float(1.0) ) perhaps? Coercion works fine; the problem is that Float implements __div__ but not __truediv__. It works if you don't import division from __future__. If you do that, even Float / Float division ceases to work. That is definitely a bug, but not as bad a bug as not being able to coerce floats at all ;-) Fredrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple eval
Tor Erik Sønvisen wrote:
> Comments, speedups, improvements in general, etc are appreciated.
You're doing a lot of repeated indexing of token[0]
and token[1] in your elif branches. You might gain some
speed by fetching these into locals before entering the
elif chain.
Also you could try ordering the branches so that the
most frequent cases come first. Probably strings and
numbers first, then the various kinds of bracket.
This would also give you a chance to avoid pulling out
token[1] until you need it.
token[1].startswith('u'): It's probably faster to
use an index to get the first character, if you know
that the string is not empty.
Importing the names from tokenize that you use repeatedly
should save some time, too.
Putting all these together, it would look something
like
from tokenize import STRING, NUMBER
def atom(next, token):
token0 = token[0]
if token0 == STRING
...
elif token0 == NUMBER:
...
elif token0[0] == 'u':
...
else:
token1 = token[1]
if token1 in KEYWORDS:
...
elif token1 == '(':
...
elif token1 == '[':
...
elif token1 == '{':
...
If you were willing to indulge in some default-argument abuse, you
could also do
def atom(next, token, STRING = tokenize.STRING, NUMBER = tokenize.NUMBER):
...
A more disciplined way would be to wrap it in a closure:
def make_atom():
from tokenize import STRING, NUMBER
def atom(next, token):
...
return atom
atom = make_atom()
--
Greg
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
On Nov 19, 2007 2:23 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > OK, I tried mpmath again, and to my surprise, it went well! > > === > #!/usr/bin/env python > #coding=utf-8 > from mpmath import * > mpf.dps = 50 > n = 1 > k = 0 > prod = mpf(1) > while k < 10: > k += 1 > term = exp(1.0/n)/exp(1.0/(n+1)) > prod *= term > n += 2 > print prod, term > == > Output: > 1.95187499635016028080844735182389158683797 > 1.00250001250004074790133889386806610626172 You're getting slightly wrong results, though, because 1.0/n and 1.0/(n+1) just performs regular float division with ~16-digit precision when n is a Python int. You should convert either 1.0 or n to an mpf before dividing. Fredrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
At 05:24 PM 11/18/2007, Fredrik Johansson wrote: >On Nov 19, 2007 2:03 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > > At 04:26 PM 11/18/2007, Fredrik Johansson wrote: > > >On Nov 19, 2007 1:05 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > > >Hi Dick, I recognize you from python-list, where you had a question > > >about mpmath. > > > > > >Your code still won't work if you convert the numbers to Floats > > >because the Float type in sympy.numerics does not implement ** for > > >fractional numbers. You could use the exp function in > > >sympy.numerics.functions instead to compute e**x. > > > > Thanks, Fredrik, but I get the same error using either exp or power: > > > > from __future__ import division > > from sympy import * > > from sympy import Rational as R > > from sympy.numerics import * > > from sympy.numerics.functions import power, exp > > > > prec = 50 > > Float.setdps(prec) > > e = evalf(E) > > n = 1 > > m = n + 1 > > k = 0 > > n = evalf(R(n,1)) > > m = evalf(R(m,1)) > > prod = evalf(R(1,1)) > > prec = 50 > > Float.setdps(prec) > > e = evalf(E) > > n = 1 > > k = 0 > > prod = evalf(R(1,1)) > > while k < 1000: > > k += 1 > > n = evalf(R(n,1)) > > term = (exp(1/n))/(exp(1/(n+1))) > > prod *= term > > n += 2 > > print prod, term > > = > > term = (exp(1/n))/(exp(1/(n+1))) > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > > > And also if I use sympy.numerics.functions.power in that line, as > > term = power(e,(1/n))/power(e,(1/(n+1))) > > > > I get: > > > > term = power(e,(1/n))/power(e,(1/(n+1))) > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > >Try not using "from __future__ import division". Didn't help. >Also, > > n = evalf(R(n,1)) > >won't work, because the arguments to Rational must be ints. But both n and 1 are ints, aren't they? Anyway, you've by now seen my new success with mpmath. I'll abandon syspy for the time being. Dick -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with sympy, please
At 05:33 PM 11/18/2007, Fredrik Johansson wrote: >On Nov 19, 2007 2:23 AM, Dick Moores <[EMAIL PROTECTED]> wrote: > > OK, I tried mpmath again, and to my surprise, it went well! > > > > === > > #!/usr/bin/env python > > #coding=utf-8 > > from mpmath import * > > mpf.dps = 50 > > n = 1 > > k = 0 > > prod = mpf(1) > > while k < 10: > > k += 1 > > term = exp(1.0/n)/exp(1.0/(n+1)) > > prod *= term > > n += 2 > > print prod, term > > == > > Output: > > 1.95187499635016028080844735182389158683797 > > 1.00250001250004074790133889386806610626172 > >You're getting slightly wrong results, though, because 1.0/n and >1.0/(n+1) just performs regular float division with ~16-digit >precision when n is a Python int. You should convert either 1.0 or n >to an mpf before dividing. Ah, yes. That was my original mistake with using mpmath. How's this?: = #!/usr/bin/env python #coding=utf-8 import psyco psyco.full() from mpmath import * mpf.dps = 50 n = mpf(1) k = 0 prod = mpf(1) while k < 10: k += 1 term = exp(1.0/n)/exp(1.0/(n+1)) prod *= term n += 2 print prod, term === Output: 1.95187499635415917971337956346129920295869 1.00250001250009375062500416669401059407666 Dick -- http://mail.python.org/mailman/listinfo/python-list
embed ipython in wxPython app
Hi All, I'm evaluting IPython to see if I can it use like Tcl and Tk. If I start wish8.4, I get a command line interpreter in xterm, then I can source tcl progams that draw tk graphics on a canvas in another window. Is there a way to embed IPython in a wxPython app to do that? When I do as shown in the example below the GUI window does not show until I exit IPython. Thanks in advance for any help with this, import wx from IPython.Shell import IPShellEmbed class MyFrame(wx.Frame): def __init__(self,parent=None, id=-1, title=' '): wx.Frame.__init__(self,parent,id,title,size=(200,140)) top = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) lb = wx.StaticText(top,-1,'Animals(in pairs; min,pair, max,dozen)') sizer.Add(lb) top.SetSizer(sizer) self.Layout() class MyApp(wx.App): def OnInit(self): frame = MyFrame(title="wxWidgets") frame.Show(True) self.SetTopWindow(frame) return True def main(): ipshell = IPShellEmbed() ipshell() app = MyApp() app.MainLoop() if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too complex ?!?!?!
Brian wrote: > Had a unsettling conversation with a CS instructor that > teaches at local high schools and the community > college. This person is a long-term Linux/C/Python > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. > > I am a low-end (3-year) journeyman Pythonista, and I > was attracted to the language because of its > simplicity. And I have come to enjoy the richness of > available libraries. > > Many of the good people of this NG may be 'too close' > to answer, but has Python, as a general devel platform, > lost its simplicity ? Is library install too complex > and unreliable ? Will my dog go to heaven ? I'm a complete noob about most of this, but it sounds like his problem may have more to do with what needs to be done on a Linux machine, than anything specifically pertaining to Python. How can you call installing Python (or any third-party modules) on Windows 'hard'? Maybe his students just have a harder type figuring out how to install things in Linux? I don't know... -- http://mail.python.org/mailman/listinfo/python-list
Learning Python : >>> import math doesn't work ?
Have carefully installed Python 2.5.1 under XP in dir E:\python25 . ran set path = %path% ; E:\python25 Python interactive mode works fine for simple arithmetic . Then tried >>> import math >>> x = sqrt(100) Get errorName error : name 'sqrt' is not defined Same thing with sin(x) . I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs or include directories . The Tutorial does not clear this up . Please help.Thanks Dave [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Troubleshooting garbage collection issues
(Dave) wrote: 8<- description of horrible problem -- Faced with this, I would: 1 - identify the modules that import gc to separate the sheep from the goats. 2 - do my best to change gc importing goats back to sheep. 3 - amongst the remaining goats, identify the ones that also use threads, (supergoats) and take a long hard look at them. 4 - hope I get lucky. 5 - If no luck, I would change the most complex of the supergoats to use more processes and messaging, to make sheep out of a supergoat, or failing that, a goat and some sheep. 6 - Repeat from 2 until luck strikes. Now the trouble with a simple minded algorithm such as the above is that a sheep could be at the bottom of the trouble if it uses threads. So a module is only a lamb if it uses neither threads nor makes calls into gc... HTH - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple eval
On Nov 18, 8:24 pm, greg <[EMAIL PROTECTED]> wrote:
> Tor Erik Sønvisen wrote:
> > Comments, speedups, improvements in general, etc are appreciated.
>
> You're doing a lot of repeated indexing of token[0]
> and token[1] in your elif branches. You might gain some
> speed by fetching these into locals before entering the
> elif chain.
>
> Also you could try ordering the branches so that the
> most frequent cases come first. Probably strings and
> numbers first, then the various kinds of bracket.
> This would also give you a chance to avoid pulling out
> token[1] until you need it.
>
> token[1].startswith('u'): It's probably faster to
> use an index to get the first character, if you know
> that the string is not empty.
I tried several of these micro optimizations but there was very little
improvement; eval() remains practically 5 times faster. The major
bottleneck is generate_tokens(); replacing simple_eval() with the
following is still 3 times slower than eval():
def simple_eval(source):
for _ in generate_tokens(StringIO(source).readline): pass
That's not very surprising since generate_tokens() is quite general
and yields more information than necessary. Clearly if performance is
critical you should write your own simple_generate_tokens(), possibly
as a cut down version of the generic one.
Leaving performance aside, below is a slightly more compact version.
The almost identical code for handling lists and tuples is factored
out in _iter_sequence(). The 'token' parameter here is the actual
token, not the 5-tuple yielded by generate_tokens(). Finally this
version handles negative and long numbers (which the original didn't):
from string import digits
from cStringIO import StringIO
from tokenize import generate_tokens, NL
_consts = {'None': None, 'False': False, 'True': True}
def simple_eval(source):
itertokens = generate_tokens(StringIO(source).readline)
next = (token[1] for token in itertokens
if token[0] is not NL).next
res = atom(next, next())
if next():
raise SyntaxError("bogus data after expression")
return res
def atom(next, token):
def _iter_sequence(end):
token = next()
while token != end:
yield atom(next, token)
token = next()
if token == ',':
token = next()
firstchar = token[0]
if token in _consts:
return _consts[token]
elif token[-1] == 'L':
return long(token)
elif firstchar in digits:
return float(token) if '.' in token else int(token)
elif firstchar in '"\'':
return token[1:-1].decode('string-escape')
elif firstchar == 'u':
return token[2:-1].decode('unicode-escape')
elif token == '-':
return -atom(next, next())
elif token == '(':
return tuple(_iter_sequence(')'))
elif token == '[':
return list(_iter_sequence(']'))
elif token == '{':
out = {}
token = next()
while token != '}':
key = atom(next, token)
next() # Skip key-value delimiter (':')
token = next()
out[key] = atom(next, token)
token = next()
if token == ',':
token = next()
return out
raise SyntaxError('malformed expression (%r)' % token)
Regards,
George
--
http://mail.python.org/mailman/listinfo/python-list
Re: What is python?????
On Nov 19, 4:42 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 18 Nov 2007 14:37:08 -0800 (PST), Zentrader
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > Damn! I joined this group because I thought it was a pie-a-thon. All
> > that practice has now gone to waste/waist.
>
> No... We respect the memory of the great dragon of Delphi, slain by
> Apollo...
>
> {Pity the BDFL is not named Apollo, so that statement could have
> multiple meanings}
> --
> WulfraedDennis Lee Bieber KD6MOG
> [EMAIL PROTECTED][EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff: [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/
how the Pythons think this network? its swallowing the wholeworld.
Discover How AGLOCO Can Be The Hugest Online Opportunity In History.
within 10 months over 1 mn joined the network. everything available on
its viewbar. But it can be download only onXP and Vista for security.
Cope
www.agloco.com/r/BBCD6361
www.agloco-burma.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: which Python ? asks beginner
"Donn Ingle" wrote: > > plans are afoot > You know, I've always wanted ask; if plans are afoot, what are hands? > > :D > > Sorry, it's late. The answer, seeing as it's late, is that whisky is at hand. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: What is python?????
On Nov 18, 8:41 pm, rzed <[EMAIL PROTECTED]> wrote: > Cope <[EMAIL PROTECTED]> wrote in news:7ab5b781-3c6c- > [EMAIL PROTECTED]: > > > please tell me what is python.This group is so crowded. > > I see nobody has chosen to answer your question seriously. I'll > give you an answer, but it is probably not to the question you are > asking, either. > > Python is not one thing. > > Python is the name of a computer language, which you can determine > easily through Google or Wikipedia or other means. That's what > comp(uter).lang(uage).python is here for, nominally. > > Python is also a package of programs that implement the language > and create a Python runtime environment. The most common > implementation is of a virtual machine that runs Python bytecodes, > though other variations run Java or .NET bytecodes. > > And Python is also a set of packages that provide utilities and > features that allow users of the packages to do useful things on > their computers without unnecessary fuss and bother. Some of these > utilities come with a basic Python installation (code name: > "batteries included"), while others are available elsewhere, often > from the Python Package Index (codename: "cheese shop"), but from > other sources as well. > > Some people conflate these meanings of "Python", which can lead to > confusion at times. Much of the crowdedness of the group has to do > with discussion related to the batteries-included features and to > the other packages written to run in the Python environment. > > Hope that helps. > > -- > rzed thanks Cope -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python : >>> import math doesn't work ?
On Nov 18, 8:48 pm, [EMAIL PROTECTED] wrote: > Have carefully installed Python 2.5.1 under XP in dir E:\python25 . > ran set path = %path% ; E:\python25 > Python interactive mode works fine for simple arithmetic . > Then tried >>> import math > >>> x = sqrt(100) >Get errorName error : name 'sqrt' is not defined > Same thing with sin(x) . > I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs > or include directories . > The Tutorial does not clear this up . > Please help.Thanks Dave [EMAIL PROTECTED] Hi, I believe that should be: x = math.sqrt(100) 'import math' makes available the functions in the math module, but they are still inside the math namespace, so still require 'math.' If you will be using sqrt a lot, you can create a copy of the function in the local namespace using sqrt = math.sqrt x = sqrt(100) [In principle, you can give it any name you want, but of course it is sensible to use a name that makes sense. E.g. if you were a Spanish speaker, you could say instead raiz = math.sqrt x = raiz(100) ] For more details about how 'import'ing works, check out the Python tutorial. Hope that helps. Best wishes, David. -- http://mail.python.org/mailman/listinfo/python-list
Re: which Python ? asks beginner
>> You know, I've always wanted ask; if plans are afoot, what are hands? > The answer, seeing as it's late, is that whisky is at hand. Ha. Brilliant answer! It also explains decorators :D /d -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets: why doesn't my connect() block?
On Nov 18, 3:08 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > > ...listen() gets > the initial connect() packet. accept() then is used to transfer the > connection onto a /new/ work socket (freeing the listen socket to catch > more connections) > Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python : >>> import math doesn't work ?
On Nov 19, 10:48 am, [EMAIL PROTECTED] wrote: > Have carefully installed Python 2.5.1 under XP in dir E:\python25 . > ran set path = %path% ; E:\python25 > Python interactive mode works fine for simple arithmetic . > Then tried >>> import math > >>> x = sqrt(100) >Get errorName error : name 'sqrt' is not defined > Same thing with sin(x) . > I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs > or include directories . > The Tutorial does not clear this up . > Please help.Thanks Dave [EMAIL PROTECTED] use it like: x = math.sqrt (100) and math.sin(x) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python : >>> import math doesn't work ?
On Nov 19, 3:46 pm, windspy <[EMAIL PROTECTED]> wrote: > use it like: x = math.sqrt (100) and math.sin(x) alternatively import like this: from math import sqrt, sin ... and use it like you have. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
On Nov 17, 12:41 am, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote: > It is true that I could have been way more polite. I don't see how. You said "please" read it. You didn't make fun of the poor spelling and said nothing rude. I can't agree that the response "reeks of arrogance." I've seen the same thing said far more agressively. You have to teach students as you find them. Clearly the querent first needs to be taught how to ask questions. If (s)he took the time to read the link you supplied (s)he will be rewarded by getting better responses not only on this group but on usenet groups generally (and probably IRL as well). -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple eval
As I see it, just as a matter of common sense, there will be no way to match the performance of the backend eval() with any interpreted code. At best, performance-wise, a preprocessor for the built-in eval() would be in order, filtering out the "unsafe" cases and passing the rest through. But what do I know, I could be dead wrong. :) Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expression
On Nov 18, 3:54 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > What the heck is that format? XML's retarded cousin living in the attic? ROFL...for some reason that makes me think of wierd Ed Edison from maniac mansion, heh ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting name of control under mouse in Windows?
En Sun, 18 Nov 2007 21:10:18 -0300, Shane Clark <[EMAIL PROTECTED]> escribió: >> From: [EMAIL PROTECTED] >> >> En Fri, 16 Nov 2007 16:16:25 -0300, Shane Clark >> escribió: >> >>> I am trying to get my python app to output the name of the control >>> under >>> the mouse each time it is clicked. Currently, I am trying to do this >>> with a combination of pyhook and pyAA, but pyAA gives me "pyAA.Error: >>> -2147417843" for almost any control in Microsoft Office apps, for >>> example. If it matters, I am trying to retrieve the control's name >>> based >>> on the mouse position coordinates. >> >> pywinauto does that. >> > Thanks for the response. Pywinauto is more or less incompatible with > Office apps so far as I can tell. According to what I have read, this is > because Office does not use standard Windows controls. For more info: > http://forums.openqa.org/message.jspa?messageID=28199 Ouch. In that case I think you won't gain much by knowing the control name anyway... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie Q: sequence membership
On Nov 17, 3:40 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
>
> You can write your own membership test based on identity ('is'):
>
Thank you for the practical (usable) advice and explanation of the
'==' operator.
On Nov 17, 4:35 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> And that can be done by reading the fine manual, specifically
>
This is true. I was being lazy by posting but have been pleasantly
surprised by the detailed responses. For the most, Python's beautiful
syntax has thus far required minimal thought of me. Programs feel more
like pseudo code than code and I may have gotten carried away.
On Nov 17, 4:35 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> Worse: Consider z = ['A1', 'Z9']. It's highly likely that when x ==
> 'A1', "x is_in z" is True -- because an unguaranteed implementation-
> dependent caper caches or "interns" some values, so that x and z[0]
> are the same object. Try explaining that to the novices!!
>
I am not a programmer so I feel odd commenting about language design
decisions. When my Prof. introduced python the first question that
popped into mind was that since "x=9; y=9; print x is y and x == y"
prints "True" is there a way to change the value of 9? He said that
was silly but after class showed me that statements "True = []" work
but suggested it was harmless and not quite a bug.
So if I am permitted to think of integers as immutable objects with
predefined labels (i.e. the integers used in the text of the program
code) that cannot de or re referenced then what a similar treatment of
characters will look like seams to be an arbitary (a design) decition.
In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer
to the same object. If one follows the convention used with integers
(9 and 9 refer to the same object) then 'ab' and 'ab' would be the
same. An equally reasonable assumption would be that 'ab' and 'ab' are
two different sequences and so not equal (I do not see the problem
here).
Actually this is what you said is left up to the implementation. '=='
seams to add a lot of power but I am not sure where or how (except as
a shortcut in the very special case of strings). Pardon the babble.
On Nov 17, 4:35 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> Do you have a use case for that?
>
I have a list of lists and want to see if another list is a member of
it. The content of the lists and the way they are related to each
other changes from program to program.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python too complex ?!?!?!
On Nov 17, 7:46 am, Brian <[EMAIL PROTECTED]> wrote: > Had a unsettling conversation with a CS instructor that > teaches at local high schools and the community > college. This person is a long-term Linux/C/Python > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. > > I am a low-end (3-year) journeyman Pythonista, and I > was attracted to the language because of its > simplicity. And I have come to enjoy the richness of > available libraries. > > Many of the good people of this NG may be 'too close' > to answer, but has Python, as a general devel platform, > lost its simplicity ? Is library install too complex > and unreliable ? Will my dog go to heaven ? I started out with some javascript and ruby background, and I "mastered" (i.e., could do everything I wanted to do in) python in a few months (including playing with the GTK bindings). I only have a GED, so I'm not the smartest programmer in the world or anything. But even so, the learning curve for python, for me, was very gradual. Nothing to too complex to swallow a spoonful at a time. After several years of using python (a very short time in the long-run, mind you), I think that the basic concepts are as simple as ever, and it remains a prime candidate for a CS 101 course. On the other hand, C# and .NET seems like a lot of baggage to bring to the table. First off, you have to introduce the CLR and how it relates to C#, then you have to deal with all the public, private, etc, syntaxis for constructors/destructors. I don't see how anyone could claim that C# is simpler to teach than python. I mean, (non-PC statement follows), it's easier to teach retarded, blind children to recite the lord's prayer backwards, in sign language, than it is to get a working .net environment set up for actual use w/o installing the latest visual studio. And not everyone had five-million dollars (or a corporate license) to get the latest and greatest VS. Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: python application dll
En Sat, 17 Nov 2007 12:04:49 -0300, <[EMAIL PROTECTED]> escribi�: > Is there a way to create a .dll from a python program which includes > the python runtime? > > I'm building a Windows application (C# VisualStudio2005) and I'd like > to utilize some of the functionality available in a Python module. For > my users who install my Windows application, I'd prefer that they not > have to install the entirety of Python on their machines. I think that linking Python directly with C# isn't easy; Python + C++ OTOH is a lot easier. Another approach is to have a Python *application* (.exe) running; you may communicate the two with virtually any available IPC mechanism. You can use py2exe to generate the .exe -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie Q: sequence membership
On Nov 19, 12:32 am, saccade <[EMAIL PROTECTED]> wrote: > I am not a programmer so I feel odd commenting about language design > decisions. When my Prof. introduced python the first question that > popped into mind was that since "x=9; y=9; print x is y and x == y" > prints "True" is there a way to change the value of 9? He said that > was silly but after class showed me that statements "True = []" work > but suggested it was harmless and not quite a bug. > > So if I am permitted to think of integers as immutable objects with > predefined labels (i.e. the integers used in the text of the program > code) that cannot de or re referenced then what a similar treatment of > characters will look like seams to be an arbitary (a design) decition. > > In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer > to the same object. If one follows the convention used with integers > (9 and 9 refer to the same object) then 'ab' and 'ab' would be the > same. An equally reasonable assumption would be that 'ab' and 'ab' are > two different sequences and so not equal (I do not see the problem > here). The problem is with side-effets. With "pure" code, your reasoning would be sound; but given that side-effects may alter the execution path, [EMAIL PROTECTED] and [EMAIL PROTECTED] may _not_ refer to the same object. This observation, is, of course, highly superfluous. ;) Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
