ANN: Chicago Python Users Group, Thurs March 9
Come to this months Chicago Python User Group Meeting and find out what happens when you cross a Chipmunk with a Python. This is sure to be our best meeting yet. Confirm your attendance: mtobis aat gmail doot com with ChiPy March in your subject line. On Topics - Someone will fake a mild dutch accent and channel BDFL's state of the universe talk from PyCon, revealing upcoming new features of Python 2.5 and beyond. We also will talk about: * doctest -- looks like interactive shell but embedded into doc strings * itertools *Module of the Month* * Maybe SCons -- finally get rid of those darn make files! Off topics -- * hosting our FR Python class * start planning for the Code Sprint Hackathon on March 18th http:// chipy.org/ChipyChipySprint * bring your tee shirt ideas. The best idea wins: a genuine pat on the back. * something unexpected is also not planned Location At the historic Monadnock Building, which in the 1890s was the tallest building in the world. That's 53 W Jackson Blvd, room 826. Here's a map: http://maps.google.com/maps?q=53+W+Jackson+Blvd,+Chicago,+IL It's right on the blue line, and two blocks from the red line, and walking distance to all of the Metra termini. Cheap parking is a few blocks away at State and Harrison, more expensive parking is immediately adjacent on Federal between Jackson and Van Buren. Take the Eisenhower all the way in until it turns into Congress, and you'll be right in the neighborhood. Turn right on State or left on Federal if you are looking for the cheap or the convenient recommended parking lots respectively. ***NOTE: PLEASE EMAIL mtobis aat gmail doot com with ChiPy March in your subject line to confirm your attendance. About ChiPy --- ChiPy is a group of Chicago Python Programmers, wannabes, and n00bs, who meet monthly at various locations around Chicagoland. We welcome all levels to attend. ChiPy website: http://chipy.org ChiPy Mailing List: http://mail.python.org/mailman/listinfo/chicago Python website: http://python.org Forward this on. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: asynchat - operation could not complete w/ blocking
Fredrik Lundh wrote: Andreas R. wrote: I'm using Python's asynchat module for networking. When calling the sendall() method of asynchat, I sometimes get the error message the operation could not complete without blocking. what sendall method ? to get proper output buffering with asynchat, use push (or push_with_producer). The problem I was having with push, is that is does not always send complete packages. The solution to this was to use sendall() instead, but sendall() gives blocking error messages. - Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading binary from a file...
Steve Holden a écrit : KraftDiner wrote: Hi! In python I'm able to read in binary data from a file. data = file.read() # Reads in an entire file. Note that you should open the file in binary mode to be platform-agnostic and as portable as possible. (Just in case you aren't). However the data is 16bits per sample and python is storing the data in a string. How do I convert that 8bit data into a list of 16 bit integers? Note: I want generic python lists or tupels not numpy or numeric etc etc... You really want the struct module here. If all data are same 16 bits integer values, you can also see the array module (and the fromfile() method - see docs). A+ Laurent. -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat - operation could not complete w/ blocking
Andreas R. wrote: The problem I was having with push, is that is does not always send complete packages. The solution to this was to use sendall() instead, but sendall() gives blocking error messages. The purpose of asynchat's push methods is to queue outgoing data and send it when possible. When you're complaining that it does not always send complete packages, that strongly implies to me that you're misunderstanding how socket transmissions work. With TCP you're guaranteed that data will show up in the same order you sent it. You're not at all guaranteed that it will show up in the same chunks, or that you will get it all at the same time. The only time you'd want to do use something like sendall is when you really _do_ want to block until you make sure all the data is sent. So if you're wondering why it blocks, that suggests a deep misunderstanding in how TCP works. If you want to use asynchat to transmit data, all you need to do is set things up so that push handles them. Once that's the case, the data will be transmitted when the socket is writable such that it doesn't block. In other words, all you want to do is call push/push_with_producer and leave it at that. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis Eppur, si muove! [But still it moves!] -- Galileo Galilei -- http://mail.python.org/mailman/listinfo/python-list
Re: sending a text message via webpage button
http://wwwsearch.sourceforge.net/ClientForm/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python FTP Question
Have you seen Python's ftplib? http://effbot.org/librarybook/ftplib.htm http://docs.python.org/lib/module-ftplib.html -- http://mail.python.org/mailman/listinfo/python-list
cgi problem
I'm trying to write a simple cgi that reads a post from the user's browser, does some stuff with the form data, and redirects the browser back to the originating url, i.e. I want the cgi to send a 302 redirect. There's no obvious way in the cgi module to set the response code to anything but 200. I.e. the run_cgi method automatically sends the 200 response without giving any way to suppress it (like nph-whatever in Apache). Is that a missing feature that I should add, or am I trying to do something dumb? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Send email notification
Ernesto a écrit : Is there a special module for mail ? I'd like to send an email [to 'n' unique email addresses] from a python script. If you want all adressee to be the only one visible in to: field, you must send n emails. For such a purpose, see iMailer module here: http://nojhan.free.fr/article.php3?id_article=22 Else, see other posts. A+ Laurent. -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat - operation could not complete w/ blocking
Dennis Lee Bieber wrote: On Wed, 08 Mar 2006 08:57:53 +0100, Andreas R. [EMAIL PROTECTED] declaimed the following in comp.lang.python: The problem I was having with push, is that is does not always send complete packages. The solution to this was to use sendall() instead, but sendall() gives blocking error messages. Somehow, the above seems logical... push probably doesn't send complete packages because doing so would require blocking; instead it sends what won't block, presuming you (the programmer) will code whatever is needed to handle partial sends and put the rest out on a later push. sendall may be sending everything, but it does so by blocking until the other end acknowledges enough packets have been received to ensure that no data is lost. Yes, this is how I understood sendall. But why does it sometimes report the error: (10035, 'The socket operation could not complete without blocking') - Andreas -- http://mail.python.org/mailman/listinfo/python-list
class variables for subclasses tuple
Hello, I have got a problem that i can't readily solve. I want the following: I want to create a supertuple that behaves both as a tuple and as a class. It should do the following: Point=superTuple(x,y,z) # this is a class factory p=Point(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] I already found a recipe to do that (recipe 6.7 in the Python cookbook). I reproduce the code hereunder: def superTuple(*attribute_names): create and return a subclass of `tuple', with named attributes # make the subclass with appropriate _ _new_ _ and _ _repr_ _ specials typename='Supertuple' nargs = len(attribute_names) class supertup(tuple): _ _slots_ _ = ( ) # save memory, we don't need per-instance dict def _ _new_ _(cls, *args): if len(args) != nargs: raise TypeError, '%s takes exactly %d arguments (%d given)' % ( typename, nargs, len(args)) return tuple._ _new_ _(cls, args) def _ _repr_ _(self): return '%s(%s)' % (typename, ', '.join(map(repr, self))) # add a few key touches to our new subclass of `tuple' for index, attr_name in enumerate(attribute_names): setattr(supertup, attr_name, property(itemgetter(index))) supertup._ _name_ _ = typename return supertup Now my problem is: i would like to extend this supertuple with class variables so that i can obtain the following: assert Point.x==0 assert Point.y==1 assert Point.z==2 while still having: assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] This is not the case unfortunately: Point.x=0 leads to having p.x==0 It seems not possible to have class variables and instance variable having the same name and yet different values. Alain -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
projecktzero wrote: I think the new site is great. I really don't understand all the nit picking that's going on from the armchair web designers. It's a nice site. It is not ugly, and its easy to navigate. *much* better than the old site, -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
[EMAIL PROTECTED] wrote: Point.x=0 leads to having p.x==0 It seems not possible to have class variables and instance variable having the same name and yet different values. A quick check: class T(tuple): ... class __metaclass__(type): ... x = property(lambda cls: 0) ... x = property(lambda self: self[0]) ... t = T(abc) t.x 'a' T.x 0 So possible it is. Come back if you're stuck generalizing the above. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Comparing: http://www.python.org/ http://www.perl.org/ http://www.java.org/ http://www.ruby-lang.org/en/ http://java.sun.com/ http://www.php.net/ It is pretty easy to see that http://www.python.org/ is both prettier than the rest, and has a far better structure. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Simple questions on use of objects (probably faq)
Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. I tried with the simple example below and ran into several questions: 1: Why can't I do: def __init__(self,self.x): and avoid the self.x=x 2: Is it a good idea to insert instances in a list or is there a simpler way to do something with all instances of a given type? 3: Why canøt I say and get the maximum of instance attributes and a list of them? y_max=max(y[].x) and ys=[y[].x] 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] The code that runs: class Foo: def __init__(self,x): self.x=x y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=[] y_max=0.0 y_min=0.0 for s in y: ys.extend([s.x]) y_max=max(s.x,y_max) y_min=min(s.x,y_min) yz=[] for i in range(len(ys)-1): yz.append(ys[i+1]-ys[i]) What I hoped I could do: class Foo: def __init__(self,self.x): continue y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=([y[].x]) y_max=max(y[].x) y_min=min(y[].x) yz=[y[:-1].x-y[1:].x] -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
Peter Otten wrote: [EMAIL PROTECTED] wrote: Point.x=0 leads to having p.x==0 It seems not possible to have class variables and instance variable having the same name and yet different values. A quick check: class T(tuple): ... class __metaclass__(type): ... x = property(lambda cls: 0) ... x = property(lambda self: self[0]) ... t = T(abc) t.x 'a' T.x 0 So possible it is. Come back if you're stuck generalizing the above. Peter Thanks for your magic answer. But i am not so good at magic ;-) If i want to generalize to a arbitrary number of variables, i got syntax errors. Within a class, you can only method/class definitions and assignments. It is therefore difficult to do something like: for idx, attr_name in enumerate(attribute_names): setattr(__metaclass__,attr_name, property(lambda cls:idx) for idx, attr_name in enumerate(attribute_names): setattr(T,attr_name, property(lambda self:self[idx]) Alain -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
As an supplement to my previous post, please find hereunder a snippet for my unsuccessful attempt (commented out snippet does not work): def superTuple(*attribute_names): nargs = len(attribute_names) class T(tuple): def __new__(cls, *args): return tuple.__new__(cls, args) class __metaclass__(type): x=property(lambda self:0) y=property(lambda self:1) z=property(lambda self:2) x=property(lambda self:self[0]) y=property(lambda self:self[1]) z=property(lambda self:self[2]) #for idx, attr_name in enumerate(attribute_names): # print 'attr name',attr_name, idx # setattr(T.__metaclass__,attr_name, property(lambda cls:idx)) #for idx, attr_name in enumerate(attribute_names): # print 'attr name',attr_name # setattr(T,attr_name, property(lambda self:self[idx])) return T if __name__ == '__main__': Point=superTuple('x','y','z') p=Point(4,7,9) assert p.x==p[0] assert p.y==p[1] assert p.z==p[2] assert Point.x==0 assert Point.y==1 assert Point.z==2 Alain -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning different languages
Rich == Rich [EMAIL PROTECTED] writes: Rich Hi, Rich (this is a probably a bit OT here, but comp.lang seems Rich rather desolated, so I'm not sure I would get an answer Rich there. And right now I'm in the middle of learning Python Rich anyway so...) Rich Anyway, my question is: what experience you people have with Rich working with different languages at the same time? I think it's akin to speaking multiple human languages. I find, in the web context, that multiple languages help to understand where stuff happens. If it's JavaScript, it's happening in the browser. If it's (other scripting language), it's on the web server. If it's SQL, it's on the database server. I realize that there are other configuration possibilities, e.g. JavaScript on the web server. R, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: linux clipboard?
Rene == Rene Pijlman [EMAIL PROTECTED] writes: Rene [EMAIL PROTECTED]: how can i copy text to the linux clipboard? Rene Linux is an operating system. It doesn't have a Rene clipboard. The clipboard is provided by desktop frameworks, Rene such as KDE or Gnome. Rene -- René Pijlman Actually, Linux is the kernel, and the full system is GNU/Linux, as RMS would hasten to point out. Isn't the clipboard a basic X component? However, for basic text, don't overlook the humble shell facilities like | , , , and R, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
[EMAIL PROTECTED] wrote: Peter Otten wrote: [EMAIL PROTECTED] wrote: Point.x=0 leads to having p.x==0 It seems not possible to have class variables and instance variable having the same name and yet different values. A quick check: class T(tuple): ... class __metaclass__(type): ... x = property(lambda cls: 0) ... x = property(lambda self: self[0]) ... t = T(abc) t.x 'a' T.x 0 So possible it is. Come back if you're stuck generalizing the above. Peter Thanks for your magic answer. But i am not so good at magic ;-) Once I grokked that a class is just an instance of its metaclass all magic magically vanished :-) If i want to generalize to a arbitrary number of variables, i got syntax errors. Within a class, you can only method/class definitions and assignments. It is therefore difficult to do something like: for idx, attr_name in enumerate(attribute_names): setattr(__metaclass__,attr_name, property(lambda cls:idx) for idx, attr_name in enumerate(attribute_names): setattr(T,attr_name, property(lambda self:self[idx]) Alain I'm not getting syntax errors: names = xyz class T(tuple): ... class __metaclass__(type): ... pass ... for index, name in enumerate(names): ... setattr(__metaclass__, name, property(lambda cls, index=index: index)) ... del index ... del name ... for index, name in enumerate(names): ... setattr(T, name, property(lambda self, index=index: self[index])) ... Traceback (most recent call last): File stdin, line 2, in ? AttributeError: can't set attribute However, the read-only property of the metaclass prevents setting the class attribute. A workaround is to set the class properties /before/ the metaclass properties. Here is a no-frills implementation, mostly untested: from operator import itemgetter def constgetter(value): def get(self): return value return get def make_tuple(*names): class TupleType(type): pass class T(tuple): __metaclass__ = TupleType def __new__(cls, *args): if len(names) != len(args): raise TypeError return tuple.__new__(cls, args) for index, name in enumerate(names): setattr(T, name, property(itemgetter(index))) for index, name in enumerate(names): setattr(TupleType, name, property(constgetter(index))) return T Peter -- http://mail.python.org/mailman/listinfo/python-list
RAD tutorials and tools for GUI development with Python?
Hey guys, I would really like to code a few more widely useable apps, but coding the GUI just seems so boring and unnecessarily complex. Maybe I was spoilt by Borland's Delphi/Kylix. But is there any way to do as little coding of the GUI as possible, and worry about the logic? The best I've seen is using one tool with a modification to output python code, which then has to be regenerated after any change to the GUI, which to me, kinda defeats the rapid in RAD. Thanks, advice would be much apperciated. If it helps to know, I am currently more interested in Python/Gtk (but not because I particularly like the look of Gtk) Arthur.-- As a boy I jumped through Windows, as a man I play with Penguins. -- http://mail.python.org/mailman/listinfo/python-list
Re: generators shared among threads
Paul Rubin wrote: Hmm (untested, like above): class Synchronized: def __init__(self, generator): self.gen = generator self.lock = threading.Lock() def next(self): self.lock.acquire() try: yield self.gen.next() finally: self.lock.release() synchronized_counter = Synchronized(itertools.count()) That isn't a general solution but can be convenient (if I didn't mess it up). Maybe there's a more general recipe somewhere. This code is not allowed in Python 2.4. From PEP 255: Restriction: A yield statement is not allowed in the try clause of a try/finally construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed; that's too much a violation of finally's purpose to bear. Even if this was allowed, ISTM the semantics might be the same as your previous attempt - I would expect the finally to be executed after the yield returns, meaning the lock would be held during the yield. Python 2.5 will allow this (see PEP 342) but from the examples it seems the finally won't execute until the yield returns. Kent -- http://mail.python.org/mailman/listinfo/python-list
mail.python.org disruption
[ Mailed to python-dev and python-list, as that should cover most of the users ;P ]There was a slight disruption on mail.python.org this morning. For about three and a half hours, it was rejecting most of its mail with the message: Client host [] blocked using singlehop.dsbl.org; Your mail has been rejected because the server you are sending to is misconfigured.The error means mail.python.org was using singlehop.dsbl.org as a DNSBL list, but that list doesn't exist, so it rejects all mail. Someone (not me :) added that blacklist at 08:15 local time (07:15 GMT) and I fixed it at 11:46 (10:46 GMT). Blame lingering PyCon-jetlag for me not catching it earlier, sorry. About 7759 mails were bounced, although a decent portion of them will have been actual spam (of which python.org gets massive amounts.) If you sent legitimate mail in that period, and got a bounce back with a message like the one above, it's safe to re-send it now.Sorry for the inconvenience. -- Thomas Wouters [EMAIL PROTECTED]Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Hi, 3: Why canøt I say and get the maximum of instance attributes and a list of them? y_max=max(y[].x) and ys=[y[].x] y_max = max([e.x for e in y]) See List comprehensions in python docs: http://docs.python.org/tut/node7.html#SECTION00714 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] yz = [e.x for e in y] yz.reverse() -- | Matt Hammond | RD Engineer, BBC Research Development, Tadworth, Surrey, UK. | http://kamaelia.sf.net/ | http://www.bbc.co.uk/rd/ -- http://mail.python.org/mailman/listinfo/python-list
Re: cgi problem
Paul Rubin wrote: I'm trying to write a simple cgi that reads a post from the user's browser, does some stuff with the form data, and redirects the browser back to the originating url, i.e. I want the cgi to send a 302 redirect. There's no obvious way in the cgi module to set the response code to anything but 200. I.e. the run_cgi method automatically sends the 200 response without giving any way to suppress it (like nph-whatever in Apache). Is that a missing feature that I should add, or am I trying to do something dumb? Set the Location: header to the new URL. http://hoohoo.ncsa.uiuc.edu/cgi/out.html http://www.algonet.se/~ug/html+pycgi/redirect.html Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: Any advantage in LISPs having simpler grammars than Python?
Grant Edwards [EMAIL PROTECTED] writes: Yes. Grammars like LISP's make it easy for programs to generate and read code. Grammars like Python's make it easy for humans to generate and read code. The above statement sounds too generalized to me. IMHO it's more of a matter of preference, your mindset and what you're accustomed to. br, S -- [EMAIL PROTECTED] -- Today is the car of the cdr of your life. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
On Wed, 08 Mar 2006 11:04:41 +0100, Brian Elmegaard wrote: Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. I tried with the simple example below and ran into several questions: 1: Why can't I do: def __init__(self,self.x): and avoid the self.x=x Okay, let's look at an example: class Parrot: def __init__(self, self.x): pass Now we create a new instance of Parrot: p = Parrot(beautiful plumage) What happens is that Python creates a Parrot instance, and calls the __init__ method with two arguments: the instance itself, called self, and the string beautiful plumage called self.x. Except, this won't work. You can't define a method or function definition like this: def f(x.y): # won't work This is a syntax error, and it would require significant changes to Python to make it work -- changes which are of dubious benefit. Okay, so what about an alternative: class Parrot: def __init__(self, x): # Python automatically calls self.x = x, # so you don't have to. pass Why doesn't Python do this? The answer is simple. What if you don't want x to be an attribute of the instance? What if you want to use x some other way? class Parrot: def __init__(self, x): y = x.strip() print All parrots have %s. % y self.y = y.upper()[0] p = Parrot(beautiful plumage) All parrots have beautiful plumage. p.y 'B' p.x Traceback (most recent call last): File stdin, line 1, in ? AttributeError: Parrot instance has no attribute 'x' As a general rule, Python never guesses what you want. It is better to be explicit than implicit. If you want an attribute self.x, you have to assign to it, Python won't guess that just because you pass an argument x to __init__ that it should be turned into an attribute. 2: Is it a good idea to insert instances in a list or is there a simpler way to do something with all instances of a given type? If you want to do something with a number of instances, you need to keep track of them somehow. You can do that by assigning each instance to its own name: p1 = Parrot(sharp beaks) p2 = Parrot(long tail feathers) p3 = Parrot(an appetite for nuts) Or in a list: parrots = [Parrot(sharp beaks), Parrot(long tail feathers)] or a dictionary: parrots = {1: Parrot(sharp beaks), 2: Parrot(long tail feathers)} or any other way you like. 3: Why canøt I say and get the maximum of instance attributes and a list of them? y_max=max(y[].x) and ys=[y[].x] If doesn't make sense to talk about getting the maximum of instance attributes. What if some attributes are numbers and some are not? How does Python know which attributes you care about? Of course you can, if you program your class to do it. class Spam: def __init__(self, x, y, z): self.x = x self.y = y + 1 self.z = 1 - z self.args = (x, y, z) # save a copy of the arguments def lister(self): # no need to report self.args return [self.x, self.y. self.z] obj = Spam(2, 3, 4) obj.lister() [2, 4, -3] Now you can do anything you want with it: max(obj.lister()) 4 min(obj.lister()) -3 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] Probably. If I work out what you are trying to do, I'll answer. The code that runs: class Foo: def __init__(self,x): self.x=x y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) Okay, you have a list of Foo instances. ys=[] y_max=0.0 y_min=0.0 for s in y: ys.extend([s.x]) You don't need to create a new, single item list and call the extend method. Do this instead: ys.append(s.x) y_max=max(s.x,y_max) y_min=min(s.x,y_min) Unless you actually want to see the maximum and minimum as they change, this is wasteful. Just call the function at the end, after collecting all the values: y_max = max(ys) y_min = min(ys) yz=[] for i in range(len(ys)-1): yz.append(ys[i+1]-ys[i]) I think you are creating a list of first differences, yes? Your code should work, and is perfectly fine. Here is another way: # use a list comprehension: yz = [ys[i+1] - ys[i] for i in range(len(ys) - 1)] And another: for index, value in enumerate(ys[:-1]): yz.append(ys[index+1] - value) By the way, don't be shy about using more meaningful names for variables. ys and yz are terribly similar, and is a bug waiting to happen. What I hoped I could do: class Foo: def __init__(self,self.x): continue You can't use continue in there, it isn't a null-op. Perhaps you wanted pass? y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=([y[].x]) y_max=max(y[].x) y_min=min(y[].x) yz=[y[:-1].x-y[1:].x] How about, before trying to
Re: Simple questions on use of objects (probably faq)
On Wed, 08 Mar 2006 11:00:09 +, Matt Hammond wrote: 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] yz = [e.x for e in y] yz.reverse() I don't think that's what the O.P. actually wants. He seems to have misused slicing syntax as some sort of weird replacement for a for loop. Of course, I could be wrong. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
[exec cmd for cmd in cmds]
Hello all, p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] for item in lst: ... exec item ... p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] [exec item for item in lst] File stdin, line 1 [exec item for item in lst] ^ SyntaxError: invalid syntax is this prohibited for some reasons or is this just happens to be disallowed? this is one more cool way p = z%i = complex(1-1e-%i, 1-1e-%i); c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)]) exec c and one more :) p = z%i = complex(1-1e-%i, 1-1e-%i); c = .join([ p % (i,i,i) for i in range(20,30) ]) exec c Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: [exec cmd for cmd in cmds]
Schüle Daniel wrote: Hello all, p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] for item in lst: ... exec item ... p = z%i = complex(1-1e-%i, 1-1e-%i) lst = [p % (i,i,i) for i in range(10, 30)] [exec item for item in lst] File stdin, line 1 [exec item for item in lst] ^ SyntaxError: invalid syntax is this prohibited for some reasons or is this just happens to be disallowed? exec is a statement. And statements aren' allowed in the _expression_ of a list-comprehension. this is one more cool way p = z%i = complex(1-1e-%i, 1-1e-%i); c = reduce(lambda x,y: x+y, [p % (i,i,i) for i in range(20,30)]) exec c and one more :) p = z%i = complex(1-1e-%i, 1-1e-%i); c = .join([ p % (i,i,i) for i in range(20,30) ]) exec c If you think so :) Ususally people go for dictionaries in such cases. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Matt Hammond [EMAIL PROTECTED] writes: See List comprehensions in python docs: Great, thanks for the hint. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
On Wed, 08 Mar 2006 11:29:29 -, Steven D'Aprano [EMAIL PROTECTED] wrote: On Wed, 08 Mar 2006 11:00:09 +, Matt Hammond wrote: 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] yz = [e.x for e in y] yz.reverse() I don't think that's what the O.P. actually wants. He seems to have misused slicing syntax as some sort of weird replacement for a for loop. Of course, I could be wrong. Hmmm, rereading, I think you're right ... and I think I'm confused too :-) Attempt #2: yz = [ (y1.x - y2.x) for (y1,y2) in zip(y[:-1], y[1:]) ] Frankly, a for loop with an index would probably be easier to read :) Matt -- | Matt Hammond | RD Engineer, BBC Research Development, Tadworth, Surrey, UK. | http://kamaelia.sf.net/ | http://www.bbc.co.uk/rd/ -- http://mail.python.org/mailman/listinfo/python-list
Re: generators shared among threads
In article [EMAIL PROTECTED], Kent Johnson [EMAIL PROTECTED] wrote: Paul Rubin wrote: Hmm (untested, like above): class Synchronized: def __init__(self, generator): self.gen = generator self.lock = threading.Lock() def next(self): self.lock.acquire() try: yield self.gen.next() finally: self.lock.release() synchronized_counter = Synchronized(itertools.count()) That isn't a general solution but can be convenient (if I didn't mess it up). Maybe there's a more general recipe somewhere. This code is not allowed in Python 2.4. From PEP 255: [ snip ] The code also doesn't make sense: .next() should *return* a value, not yield one. Substituting return for yield might just work for the code above. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: generators shared among threads
[EMAIL PROTECTED] (Alex Martelli) writes: Now, x=ReentrantIterator(itertools.count()) should have all the properties we want, I think. The locking is thanks of Queue.Queue and its sweet implementation of the Template Method design pattern. That is very cool, and generally useful enough that maybe it should be dropped into itertools. I see that Queue.get's implementation is quite intricate (it uses three separate locks to handle some additional cases like timeouts and non-blocking gets) but I'm not up to trying to grok it right now. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: [exec cmd for cmd in cmds]
[...] If you think so :) Ususally people go for dictionaries in such cases. you are right, I didn't think about dictionaries p = complex(1-1e-%i, 1-1e-%i) d={} [d.update({i:eval(p % (i,i))}) for i in range(20,30)] [None, None, None, None, None, None, None, None, None, None] so now the work is complete :) Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Brian Elmegaard wrote: Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. What I hoped I could do: class Foo: def __init__(self,self.x): continue y=[] y.append(Foo(10.0)) y.append(Foo(110.0)) y.append(Foo(60.0)) ys=([y[].x]) y_max=max(y[].x) y_min=min(y[].x) yz=[y[:-1].x-y[1:].x] It is hard to tell what you are trying to do here. But here is a shot at parts of the code. class Foo: def __init__(self, x): self.x = x y = [Foo(10.0), Foo(110.0), Foo(60.0)] x_values = [o.x for o in y] y_max = max(x_values) y_min = min(x_values) Otherwise you could try and describe with words what you are getting at. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Brian Elmegaard wrote: Matt Hammond [EMAIL PROTECTED] writes: y_max = max([e.x for e in y]) Would there be a way to refer back to the e with maximum x, or how could I find other attributes of it? In that case a common idiom is to decorate decorated = [(obj.x, obj) for obj in objects] max_decorated = max(decorated) max_obj = max_decorated[-1] Or to run through it old style max_obj = objects[0] for obj in objects: if obj.x max_obj.x: max_obj = obj Readbility is about the same I think. Testing should tell you which is faster in your case. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Steven D'Aprano [EMAIL PROTECTED] writes: Thanks for the answers. They are very useful. self.args = (x, y, z) # save a copy of the arguments As always python makes it easy. max(obj.lister()) 4 Actually I wanted to get the maximum of attributes of several instances. List comprehension is the answer. method. Do this instead: ys.append(s.x) I always get confused by extend and append. this is wasteful. Just call the function at the end, after collecting all the values: Easier indeed. for index, value in enumerate(ys[:-1]): yz.append(ys[index+1] - value) I will need to study enumerate a bit. By the way, don't be shy about using more meaningful names for variables. ys and yz are terribly similar, and is a bug waiting to happen. I know, and in the real code I use better names. You can't use continue in there, it isn't a null-op. Perhaps you wanted pass? Yes. yz=[y[:-1].x-y[1:].x] How about, before trying to invent short cuts, you actually learn some of the Python syntax? The [x:y] syntax already has a meaning to Python, just not what you want. Perhaps it is not the same, but quite close. In matlab .* is element-by-element multiplication. I was thinking about a .- operator. wouldn't that make sense here? Also, while everything in Python is an object, you don't *have* to use object oriented techniques. In the real problem the class is: class Stream: def __init__(self,T_start,T_end,Q_dot): self.T_start=T_start self.T_end=T_end self.Q_dot=Q_dot self.mcp=abs(Q_dot/(T_start-T_end)) if T_startT_end: self.type='hot' else: self.type='cold' and I thought it would make sense to store this a objects. Otherwise I would need to store each stream as a list is refer their indexes. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat - operation could not complete w/ blocking
(possible duplicate; reposted due to mail server problems) Andreas R. `wrote: what sendall method ? to get proper output buffering with asynchat, use Search for sendall here: http://svn.gna.org/viewcvs/openrts/trunk/openrts/client/networksend.py?rev=67view=markup That's what I was told to use here: http://groups.google.no/group/comp.lang.python/browse_thread/thread/e8615b50ea990a5f/0a30540bd8ec9db5 That's not correct? nope. asyncore uses it's own send implementation, and asynchat implements proper buffering on top of asyncore's send via the push methods. the reason that you could call sendall appears to be that asyncore gives you access to *all* socket object attributes via dynamic inheritance, and nobody thought of filtering out the sendall method (which is a rather recent addition to the socket layer). this should probably be fixed. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Matt Hammond [EMAIL PROTECTED] writes: Hmmm, rereading, I think you're right ... and I think I'm confused too :-) You both are. Attempt #2: yz = [ (y1.x - y2.x) for (y1,y2) in zip(y[:-1], y[1:]) ] Frankly, a for loop with an index would probably be easier to read :) Me too, would that be what I already had? -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
wxPython GenericDirCtrl events
I can't get these to work, and I can't work out what I'm doing wrong. I added the following lines to the GenericDirCtrl.py demo in the wxython demos folder: at the end TestPanel.__init__ I added: self.Bind(wx.EVT_TREE_SEL_CHANGED, self.test, dir1) and also added a test def to the class: def test(self, evt): print Hit When I run it I never get a hit. How should I be doing this? Iain --- source: --- import wx #-- class TestPanel(wx.Panel): def __init__(self, parent, log): wx.Panel.__init__(self, parent, -1) self.log = log txt1 = wx.StaticText(self, -1, style=0) dir1 = wx.GenericDirCtrl(self, -1, size=(200,225), style=0) txt2 = wx.StaticText(self, -1, wx.DIRCTRL_DIR_ONLY) dir2 = wx.GenericDirCtrl(self, -1, size=(200,225), style=wx.DIRCTRL_DIR_ONLY) txt3 = wx.StaticText(self, -1, wx.DIRCTRL_SHOW_FILTERS) dir3 = wx.GenericDirCtrl(self, -1, size=(200,225), style=wx.DIRCTRL_SHOW_FILTERS, filter=All files (*.*)|*.*|Python files (*.py)|*.py) sz = wx.FlexGridSizer(cols=3, hgap=5, vgap=5) sz.Add((35, 35)) # some space above sz.Add((35, 35)) sz.Add((35, 35)) sz.Add(txt1) sz.Add(txt2) sz.Add(txt3) sz.Add(dir1, 0, wx.EXPAND) sz.Add(dir2, 0, wx.EXPAND) sz.Add(dir3, 0, wx.EXPAND) sz.Add((35,35)) # some space below sz.AddGrowableRow(2) sz.AddGrowableCol(0) sz.AddGrowableCol(1) sz.AddGrowableCol(2) self.SetSizer(sz) self.SetAutoLayout(True) self.Bind(wx.EVT_TREE_SEL_CHANGED, self.test, dir1) def test(self, evt): print Hit #-- def runTest(frame, nb, log): win = TestPanel(nb, log) return win #-- overview = \ This control can be used to place a directory listing (with optional files) on an arbitrary window. The control contains a TreeCtrl window representing the directory hierarchy, and optionally, a Choice window containing a list of filters. The filters work in the same manner as in FileDialog. if __name__ == '__main__': import sys,os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat - operation could not complete w/ blocking
Andreas R. wrote: I'm using Python's asynchat module for networking. When calling the sendall() method of asynchat, I sometimes get the error message the operation could not complete without blocking. what sendall method ? to get proper output buffering with asynchat, use push (or push_with_producer). The problem I was having with push, is that is does not always send complete packages. that sounds like a bug on the receiving side. the network layer is free to split things up however it likes, and it's up to your code to put things together again properly. The solution to this was to use sendall() instead, but sendall() gives blocking error messages. sendall is blocking per definition (and it doesn't send complete packages either; it just loops until it has managed to hand everything over to the net- work layer). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning different languages
Rich said : Hi, (this is a probably a bit OT here, but comp.lang seems rather desolated, so I'm not sure I would get an answer there. And right now I'm in the middle of learning Python anyway so...) Anyway, my question is: what experience you people have with working with different languages at the same time? I am an undergraduate now , majoring in software engineering .I have learn three lanaguages , c/c++ , java , sql . And now I am taking a part-time job in a software corporation which engage in enterprise mail system development . I must use php to maintain their web sever page , while I am using perl script to process the mail message. Meantime , I am very interested in python too .I can't say I am good at any one of these, but I must use all of these at a time . Actually I did myself many years ago, on my Commodore machines, where I programmed a lot in both basic, assembler and machine code, and don't recall I had any problems with handling these parallel. But then, they are very different languages, so it's not easy to get their syntax etc. mixed up with each other. Yes , I feel that too . I often use break statement in perl script only be warned an syntax error ! I'm more thinking about Python, PHP, C++, Perl, Euphoria, which are languages I'm thinking of learning now. They look much more like each other than basic and MC, at places some even share the exact same syntax it seems, so your brain might get confused with what language you're actually working with? How is your experience with handling these paralell?. And what would you recommend - take one (or perhaps two) at a time, and then continue with the next? Or is it OK to go ahead with them all, at once? I think when anybody learn a new language , the most important thing is not the syntax of that language but the builtin functions and the libraries the language provide ! My experience is : Learning a language is relatively easy , but being good at a language is a far more difficult thing! Regards! -- http://mail.python.org/mailman/listinfo/python-list
wxPython cross platform taskbar
Hi All Does anyone have any peice of wxPython code thats cross platform and allows an app to be minimised in the system tray. I am hoping for windows/kde/gnome/darwin if possible. I have been playing about and have a couple of systems that nearly get there but not quite. I would llike to create an app that does this in the way limewire/skype etc. do it Hope you can help David Heres sample code that nearly gets there I think - it appears to work on ubuntu/gnome import wx ICON_STATE = 0 BLINK_STATE = 0 ID_ICON_TIMER = wx.NewId() class TaskBarApp(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size = (1, 1), style=wx.FRAME_NO_TASKBAR|wx.NO_FULL_REPAINT_ON_RESIZE) self.tbicon = wx.TaskBarIcon() icon = wx.Icon('yellow.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, '') #wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarLeftDClick) #wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarRightClick) self.tbicon.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarLeftDClick) self.tbicon.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.OnTaskBarRightClick) self.Bind(wx.EVT_TIMER, self.BlinkIcon, id=ID_ICON_TIMER) self.Show(True) def OnTaskBarLeftDClick(self, evt): global ICON_STATE try: self.icontimer.Stop() except: pass if ICON_STATE == 1: icon = wx.Icon('yellow.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Yellow') ICON_STATE = 0 else: self.SetIconTimer() ICON_STATE = 1 def OnTaskBarRightClick(self, evt): try: self.icontimer.Stop() except: pass self.tbicon.Destroy() self.Close(True) wx.GetApp().ProcessIdle() #def OnTaskBarRightClick(self, evt): #self.Close(True) #wx.GetApp().ProcessIdle() def SetIconTimer(self): self.icontimer = wx.Timer(self, ID_ICON_TIMER) wx.EVT_TIMER(self, ID_ICON_TIMER, self.BlinkIcon) self.icontimer.Start(1000) def BlinkIcon(self, evt): global BLINK_STATE if BLINK_STATE == 0: icon = wx.Icon('red.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Red') BLINK_STATE = 1 else: icon = wx.Icon('black.ico', wx.BITMAP_TYPE_ICO) self.tbicon.SetIcon(icon, 'Black') BLINK_STATE = 0 class MyApp(wx.App): def OnInit(self): frame = TaskBarApp(None, -1, ' ') frame.Center(wx.BOTH) frame.Show(False) return True def main(): app = MyApp(0) app.MainLoop() if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython GenericDirCtrl events
On 8 Mar 2006 04:25:38 -0800, Iain King [EMAIL PROTECTED] wrote: at the end TestPanel.__init__ I added: self.Bind(wx.EVT_TREE_SEL_CHANGED, self.test, dir1) {...] Try this instead: t = dir1.GetTreeCtrl() t.Bind(wx.EVT_TREE_SEL_CHANGED, self.test) -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Kay Schluehr wrote: The new website is to blah. It's so light colored across the whole thing that it kind of just melts away in my mind. Maybe giving a little color in the menu bar on the right would help. My experience is that white is a bad background color when over used. I agree. The text is too loud and the colors are too low. Otherwise Fredrik Lundh reminded me that there are no good PL language home pages out there at all. This shouldn't excuse a mediocre design but it softened my annoyance a little. unfortunately, I don't think but the others are no better is an acceptable goal for the Python universe I live in... after all, what's the fun with that? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: os.execve(pth,args,env) and os.chroot(pth) = problems
Thanks for the reply Donn, It seems logical enough to me that finding #!/usr/bin/env python in the script file with the chroot I have used, is the problem. Once again thank you for the help. Regards, Gavin -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
The first two links on the News and Announcements are dead -- they get you a 404 File Not Found. I've opened a critical ticket on this in the bug tracker. I see there's another ticket open already on a similar issue. My recommendation would be that if these can't be resolved in very short order. to revert to the old site until these are fixed. -- http://mail.python.org/mailman/listinfo/python-list
Re: asynchat - operation could not complete w/ blocking
Andreas R. wrote: sendall may be sending everything, but it does so by blocking until the other end acknowledges enough packets have been received to ensure that no data is lost. Yes, this is how I understood sendall. But why does it sometimes report the error: (10035, 'The socket operation could not complete without blocking') in this context, that error message means I cannot buffer more data right now, please come back later. sendall (which is designed for blocking sockets) treats that as an error, while asyncore's send and push methods do the right thing (i.e. waits until the socket layer signals that it's ready to handle more data). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Brian Elmegaard wrote: Hi, I am struggling to understand how to really appreciate object orientation. I guess these are FAQ's but I have not been able to find the answers. Maybe my problem is that my style and understanding are influenced by matlab and fortran. I tried with the simple example below and ran into several questions: 1: Why can't I do: def __init__(self,self.x): and avoid the self.x=x Before you assign a value to it, self.x does not exists. 2: Is it a good idea to insert instances in a list or is there a simpler way to do something with all instances of a given type? Depends on your program. But there are at least ways to make this a bit more transparent, see below. 3: Why canøt I say and get the maximum of instance attributes and a list of them? y_max=max(y[].x) and y_max = max([s.x for s in y]) ys=[y[].x] ys = [s.x for s in y] 4: Can I avoid the dummy counter i in the for loop and do something like: yz=[y[:-1].x-y[1:].x] based on the other snippet you posted: yz=[] for i in range(len(ys)-1): yz.append(ys[i+1]-ys[i]) yz = [next - current for next, current in zip(ys[1:], ys[0:-1])] I'm not sure this is exactly what you want, but this should get you started anyway. Now how you could do it the OO way (QD, not really tested): class Foo(object): _instances = [] def __init__(self, x): self.x = x # no, you won't avoid it self._add_instance(self) @classmethod def _add_instance(cls, instance): cls._instances.append(instance) @classmethod def get_instances(cls): return cls._instances[:] @classmethod def get_values(cls): return [i.x for i in cls.get_instances()] @classmethod def max(cls): return max(cls.get_values()) @classmethod def min(cls): return min(cls.get_values()) @classmethod def strange_computation(cls): values = cls.get_values() return [next - current \ for next, current in zip(values[1:], values[:-1])] for value in [10.0, 110.0, 60.0]: Foo(value) Foo.get_values() Foo.max() Foo.min() Foo.strange_computation() HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython GenericDirCtrl events
Franz Steinhaeusler wrote: On 8 Mar 2006 04:25:38 -0800, Iain King [EMAIL PROTECTED] wrote: at the end TestPanel.__init__ I added: self.Bind(wx.EVT_TREE_SEL_CHANGED, self.test, dir1) {...] Try this instead: t = dir1.GetTreeCtrl() t.Bind(wx.EVT_TREE_SEL_CHANGED, self.test) -- Franz Steinhaeusler Perfect. Thanks! Iain -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
Thank you Peter, this does the job. In passing, I have another question: where can I read up more on metaclasses? Alain -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning different languages
Rich wrote: Anyway, my question is: what experience you people have with working with different languages at the same time? I typically use Python, C++ and SQL. When there's been lots of Python and little C++, I tend to forget to terminate C++ statements with semicolon... Otherwise I seem to keep them apart. In general, I think Python made me a better C++ programmer. You certainly can't apply all Python ideas in C++ or vice versa. The languages have different strengths and weaknesses, and an idiom which is good in one language might be bad in the other. Still, it was with Python I learned OOP properly, and since Python doesn't get in the way as much, using Python has made it easier to develop as a systems designer and architect. SQL is certainly different enough from the other to prevent any confusion. Concerning more similar languages, such as Python, PHP and Perl, I don't really see the point of mastering several languages that are so similar. To be honest, learning Python made me never want to touch Perl again, and learning PHP felt very much like going backwards, so I didn't get beyond a very superficial understanding. I feel so much more productive with Python, and it can handle all the things PHP or Perl handles well enough. There are certainly cases were PHP would be more convenient, and a big existing base of Perl code, but I've managed to get by well with Python anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
Matt Hammond [EMAIL PROTECTED] writes: y_max = max([e.x for e in y]) Would there be a way to refer back to the e with maximum x, or how could I find other attributes of it? -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
PyCon2006 - will the content be available for download?
Anyone know if (and when) the talks from PyCon2006 will be available for download. I am particularly interested in the tutorials (as they did not have them at PyCono2005). Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon2006 - will the content be available for download?
abcd wrote: Anyone know if (and when) the talks from PyCon2006 will be available for download. I am particularly interested in the tutorials (as they did not have them at PyCono2005). Thanks. http://www.python.org/community/pycon/ leads to http://us.pycon.org/AudioVideoRecording/HomePage -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple questions on use of objects (probably faq)
bruno at modulix [EMAIL PROTECTED] writes: Now how you could do it the OO way (QD, not really tested): Something goes wrong in my 2.3 when I change the syntax to _add_instance=classmethod(_add_instance). If I understand this correctly the class is keeping track of the instances of itself. The class is extendible and has all the needed methods. This means that any global lists can be avoided. Interesting. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html http://www.rugbyklubben-speed.dk -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables for subclasses tuple
[EMAIL PROTECTED] wrote: In passing, I have another question: where can I read up more on metaclasses? Well, in Python in a Nutshell Alex Martelli manages to pack the practical information that lets you work with metaclasses into just four pages, including a two-page example. You may have seen posts by Alex on c.l.py that are longer... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Roy Smith wrote: The first two links on the News and Announcements are dead -- they get you a 404 File Not Found. I've opened a critical ticket on this in the bug tracker. I see there's another ticket open already on a similar issue. My recommendation would be that if these can't be resolved in very short order. to revert to the old site until these are fixed. fixed -- http://mail.python.org/mailman/listinfo/python-list
Re: RAD tutorials and tools for GUI development with Python?
On 3/8/06, Arthur Pemberton [EMAIL PROTECTED] wrote: Hey guys, I would really like to code a few more widely useable apps, but coding the GUI just seems so boring and unnecessarily complex. Maybe I was spoilt by Borland's Delphi/Kylix. But is there any way to do as little coding of the GUI as possible, and worry about the logic? The best I've seen is using one tool with a modification to output python code, which then has to be regenerated after any change to the GUI, which to me, kinda defeats the rapid in RAD. Thanks, advice would be much apperciated. If it helps to know, I am currently more interested in Python/Gtk (but not because I particularly like the look of Gtk) I would recommend that you take a look at Dabo (http://dabodev.com). They are in the process of developing exactly the sort of GUI design tools you are looking for. They're not 100% of the way there yet, as the project is basically two guys who do this in their free time (and apparently never sleep!). On the Documentation page of their site is a list of screencasts where you can see the GUI design tools in action. -- # p.d. -- http://mail.python.org/mailman/listinfo/python-list
Re: ODBC module and strange date reference ...
[EMAIL PROTECTED] wrote: I'm all for using for the latest version of Python. I'm just now learning about Python classes, and it seems like there were some significant changes at 2.2. I don't remember exactly what appeared when, but nothing you learn with 2.1 will stop working in 2.2 (I think--at least nothing broke for me, and I haven't heard of any problems in this regard). On Windows, you might have problems crossing the 2.2 - 2.3 gap if you use non-ASCII characters in the source code. That's the only upgrade problem I ever had from 1.4.2 to 2.4.2... -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
It's actually something that has been being considered for Python 3.0 for a long time. I will never understand why we can't just leave a good language alone, and instead keep trying to make it everything for all people. If I want strong typing, I'll use Java or C++. And don't tell me to just not use it, because the more that's added to the core language, the harder it becomes to inherit code, the ease of which being something that Python is supposed to stand for. Mike Soulier -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
It's also important to note that while Guido did spend a lot of time thinking about optional type markups (and this caused a LOT of hand wringing in the Python community, the general consensus in the end was that there was no real benefit from it. (I got the impression that a lot of the push was from Java/C++ people that didn't really understand what dynamic languages are about, and wanted to make Python more like Java/C++. Just my impression though). It's very comforting to hear this. Perl has already added optional type-checking, and personally, I just shook my head and asked why?. I came to the Python community because I was sick of Perl, and not happy with Java, so I find myself resistent to attempts to make Python more like either, as I'd like to leave those worlds behind. The only compelling thing about Perl was the CPAN, and the cheeseshop is looking better every day. The major compelling thing about Java for me is ease of distribution, and Python is getting better in that respect as well. Mike Soulier -- http://mail.python.org/mailman/listinfo/python-list
recycling internationalized garbage
Hi folks, Please help me with international string issues: I put together an AJAX discography search engine http://www.xfeedme.com/discs/discography.html using data from the FreeDB music database http://www.freedb.org/ Unfortunately FreeDB has a lot of junk in it, including randomly mixed character encodings for international strings. As an expediency I decided to just delete all characters that weren't ascii, so I could get the thing running. Now I look through the log files and notice that a certain category of user immediatly homes in on this and finds it amusing to see how badly I've mangled the strings :(. I presume they chuckle and make disparaging remarks about united states of ascii and then leave never to return. Question: what is a good strategy for taking an 8bit string of unknown encoding and recovering the largest amount of reasonable information from it (translated to utf8 if needed)? The string might be in any of the myriad encodings that predate unicode. Has anyone done this in Python already? The output must be clean utf8 suitable for arbitrary xml parsers. Thanks, -- Aaron Watters === As someone once remarked to Schubert take me to your leider (sorry about that). -- Tom Lehrer -- http://mail.python.org/mailman/listinfo/python-list
Having to print before method invocation?
I have an object (written as part C extension, part pure Python) called foo that I've been using without much fuss for a few months now. However, in my latest project (a rather large one involving multi-threading, pygtk, etc.), I'm seeing some really strange behavior with a particular instance of my foo object. About midway through my program, any attempt to use the instance fails; however, if I add print statements before trying to invoke methods on it, the foo object instance works fine. I thought it might have something to do w/ reference counting, but calling sys.getrefcount() shows sane values both before and after the method call. I know it's almost pointless to ask this question w/out showing any code, but does anyone have any general ideas about what might make something invalid unless you print it to stdout before using it? -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Hear hear! I like it. It's not perfect but is much better than the old one in all ways. A huge improvement. Thanks to the website team. -- http://mail.python.org/mailman/listinfo/python-list
Re: recycling internationalized garbage
[EMAIL PROTECTED] wrote: Question: what is a good strategy for taking an 8bit string of unknown encoding and recovering the largest amount of reasonable information from it (translated to utf8 if needed)? The string might be in any of the myriad encodings that predate unicode. Has anyone done this in Python already? The output must be clean utf8 suitable for arbitrary xml parsers. some alternatives: braindead bruteforce: try to do strict decoding as utf-8. if you succeed, you have an utf-8 string. if not, assume iso-8859-1. slightly smarter bruteforce: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163743 more advanced (but possibly not good enough for very short texts): http://chardet.feedparser.org/ /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
Really what we're talking about here is weak typing in the form of optional type hinting performed on a function by function basis. As an option, what it would do is allow an author to semantically 'hint' to the interpreter that a function is expecting a certain type, and perform any implicit conversion if the passed type is not what was expected, thus translating to a semantically expected result. It is my feeling that this doesn't represent a sea-change in the way Python does things, and it's certainly *not* the way things are done in Java or C++, as both of those languages are strongly typed, wherein you can't even pass a parameter if it isn't of the expected type, or a subclass thereof. The fact is, that with a system such as this, you could just 'not use it', and none would be the wiser, as it's an authorship extension rather than a calling extension. What I was suggesting is that nothing change other than function/method prototypes, and that everything, everwhere, at all times continues to be represented as scalars. -- http://mail.python.org/mailman/listinfo/python-list
Re: linux clipboard?
On 2006-03-08, Chris Smith [EMAIL PROTECTED] wrote: how can i copy text to the linux clipboard? Rene Linux is an operating system. It doesn't have a Rene clipboard. The clipboard is provided by desktop frameworks, Rene such as KDE or Gnome. Rene -- René Pijlman Actually, Linux is the kernel, and the full system is GNU/Linux, as RMS would hasten to point out. Isn't the clipboard a basic X component? What you're calling the clipboard is several basic X components. More accurately there is no such thing in X as the clipboard. The selection mechanism in X is rather complicated and can only partially be made to resemble a clipboard in the traditional MacOS sense of the word. Some desktop environments have implimented something more akin to the MacOS clipboard, but AFAICT that's another layer on top of the basic selection mechanisms provided by X -- Grant Edwards grante Yow! NOT fucking!! Also at not a PACKAGE of LOOSE-LEAF visi.comPAPER!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Send email notification
On 2006-03-08, Steve Holden [EMAIL PROTECTED] wrote: Hang around here long and you'll see a bunch of people waiting on replies to questions Google could have given them far quicker. If we weren't paid thousands of dollars a week to answer questions on this list we'd probably get snarky more often. That reminds me: I haven't seen last weeks check yet. I trust it will arrive soon... -- Grant Edwards grante Yow! I feel like I am at sharing a CORN-DOG with visi.comNIKITA KHRUSCHEV... -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic Python FTP Question
On Wed, 08 Mar 2006 00:09:34 -0800, Ravi Teja wrote: Have you seen Python's ftplib? http://effbot.org/librarybook/ftplib.htm http://docs.python.org/lib/module-ftplib.html No I hadn't. Thanks for the references; it looks like that method will do anything I need to do with ftp. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyserial again
On 2006-03-08, luca72 [EMAIL PROTECTED] wrote: Belive me for a person of my age and my background ( i'm a physics, but at my time no computer was allowed) all that for you is simple, Believe me, it wasn't simple for us. We had to guess what you were doing wrong since you wouldn't show us your code. Something that could have taken a single post and response turned into an ordeal that lasted for days. -- Grant Edwards grante Yow! Didn't I buy a 1951 at Packard from you last March visi.comin Cairo? -- http://mail.python.org/mailman/listinfo/python-list
Re: Having to print before method invocation?
Jeremy L. Moles wrote: I have an object (written as part C extension, part pure Python) called foo that I've been using without much fuss for a few months now. However, in my latest project (a rather large one involving multi-threading, pygtk, etc.), I'm seeing some really strange behavior with a particular instance of my foo object. About midway through my program, any attempt to use the instance fails; however, if I add print statements before trying to invoke methods on it, the foo object instance works fine. fails in what way? if you get a spurious exception, it's very likely that your C extension sets the exception state (either directly or because some API function it uses fails), but forgets to report this back to Python. e.g. if you have a C function that does something like PyErr_SetString(PyExc_AttributeError, blah blah): Py_INCREF(Py_None); return Py_None; instead of PyErr_SetString(PyExc_AttributeError, blah blah): return NULL; the interpreter won't raise the exception immediately (since it expected you to return NULL if something went wrong), but the exception may still be raised at a later time, if you run interpreter code that does something like do something if (PyErr_Occurred()) ... /* this will catch your error even if something succeeds */ ... *or* it may be masked, by code that does PyErr_Clear(); do something the actual exception might give you additional clues (e.g. if you get a KeyError, look for unchecked dictionary accesses in your code, etc). hope this helps! /F -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
I don't necessarily like it, but I think the true test is whether a pointy haired manager type can be convinced that python can be taken seriously as a welcome addition to the programming arsenal. I think the site re-design will aid in that area more so than the previous one. I'm not feeling the new logo though. But it's better than what I can produce in an svg editor/-- Thomas G. Willis--- http://i-see-sound.comhttp://tomwillis.sonicdiscord.comAmerica, still more rights than North Korea -- http://mail.python.org/mailman/listinfo/python-list
Re: Having to print before method invocation?
Hey Fredrik, thanks for responding. :) Your posts are always helpful and informative! On Wed, 2006-03-08 at 15:41 +0100, Fredrik Lundh wrote: Jeremy L. Moles wrote: I have an object (written as part C extension, part pure Python) called foo that I've been using without much fuss for a few months now. However, in my latest project (a rather large one involving multi-threading, pygtk, etc.), I'm seeing some really strange behavior with a particular instance of my foo object. About midway through my program, any attempt to use the instance fails; however, if I add print statements before trying to invoke methods on it, the foo object instance works fine. fails in what way? Unfortunately, very silently. There aren't any exceptions thrown or anything. The be more specific, the C part of the object is a wrapper around some socket Send/Recv functions (that interface w/ wpa_supplicant). The problem I'm getting is that unless I add that print statement, wpaobject.Recv() returns , whereas with the print statement it returns what it should (a large string representing the response from wpa_supplicant). More strange is that this is the first time I've had to do this. Up until this point, every unittest and app has succeeded without such trickery. if you get a spurious exception, it's very likely that your C extension sets the exception state (either directly or because some API function it uses fails), but forgets to report this back to Python. e.g. if you have a C function that does something like PyErr_SetString(PyExc_AttributeError, blah blah): Py_INCREF(Py_None); return Py_None; instead of PyErr_SetString(PyExc_AttributeError, blah blah): return NULL; the interpreter won't raise the exception immediately (since it expected you to return NULL if something went wrong), but the exception may still be raised at a later time, if you run interpreter code that does something like do something if (PyErr_Occurred()) ... /* this will catch your error even if something succeeds */ ... *or* it may be masked, by code that does PyErr_Clear(); do something the actual exception might give you additional clues (e.g. if you get a KeyError, look for unchecked dictionary accesses in your code, etc). hope this helps! /F -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
I like it personally. Nice clean look and feel, and the logo is much better than the old cheesy green python. Has a more professional feel to it, which can be important if you want to use the language outside of your free time... -- http://mail.python.org/mailman/listinfo/python-list
Re: recycling internationalized garbage
Fredrik Lundh [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Question: what is a good strategy for taking an 8bit string of unknown encoding and recovering the largest amount of reasonable information from it (translated to utf8 if needed)? The string might be in any of the myriad encodings that predate unicode. Has anyone done this in Python already? The output must be clean utf8 suitable for arbitrary xml parsers. some alternatives: braindead bruteforce: try to do strict decoding as utf-8. if you succeed, you have an utf-8 string. if not, assume iso-8859-1. that was a mistake I made once. Do not use iso8859-1 as python codec, instead create your own codec called e.g. iso8859-1-ncc like this (just a sketch): decoding_map = codecs.make_identity_dict(range(32, 128)+range(128+32, 256)) decoding_map.update({}) encoding_map = codecs.make_encoding_map(decoding_map) and then use : def try_encoding(s, encodings): try to guess the encoding of string s, testing encodings given in second parameter for enc in encodings: try: test = unicode(s, enc) return enc except UnicodeDecodeError, r: pass return None guessed_unicode_text = try_encodings(text, ['utf-8', 'iso8859-1-ncc', 'cp1252', 'macroman']) it seems to work surprisingly well, if you know approximately the language(s) the text is expected to be in (e.g. replace cp1252 with cp1250, iso8859-1-ncc with iso8859-2-ncc for central european languages) -- --- | Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk | --- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-list
Re: [exec cmd for cmd in cmds]
Schüle Daniel wrote: you are right, I didn't think about dictionaries p = complex(1-1e-%i, 1-1e-%i) d={} [d.update({i:eval(p % (i,i))}) for i in range(20,30)] [None, None, None, None, None, None, None, None, None, None] so now the work is complete :) Regards Really, isn't this clearer?: d = {} for i in range(20, 30): v = 1. - 10. ** -i d[i] = complex(v, v) If you must repair the mess above, try: p = complex(1-1e-%i, 1-1e-%i) d = dict([(i, eval(p % (i, i))) for i in range(20, 30)]) Strive to be clear first, terse second given the first is still achieved. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
why no block comments in Python?
I'm still tyring to figure out what Pythonic means, and I have a feeling the answer to my question may fall into that category. Are block comments somehow unpythonic? -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading binary from a file...
KraftDiner wrote: [...] In python I'm able to read in binary data from a file. [...] However the data is 16bits per sample and python is storing the data in a string. How do I convert that 8bit data into a list of 16 bit integers? On the vast majority of systems, files hold sequences of eight-bit integers. How you convert from those to your 16-bit type depends on how the the writer of the file converted the 16-bit integer type to a sequence 8-bit integers. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Interfacing with the command line
I know its possible to acsess Python via the command line, but can I do the opposite and acsess the command line via Python? For example, can I write a script that will enter $ firefox on the command line, opening Firefox for me? Thanks in advance, -- /usr/bin/byte -- http://mail.python.org/mailman/listinfo/python-list
Re: why no block comments in Python?
John Salerno wrote: I'm still tyring to figure out what Pythonic means, and I have a feeling the answer to my question may fall into that category. Are block comments somehow unpythonic? only in the sense that python don't have them. but they're pretty pointless, if you have a modern editor. (and if you don't, you can quickly comment out regions by putting them inside a triple-quoted string.) /F -- http://mail.python.org/mailman/listinfo/python-list
Extending embedded Python: Adding single methods
Hallöchen! I'd like to script C++ funtions by an embedded Python interpreter. So far, my C++ main() function contains: Py_Initialize(); Py_InitModule(pp3, PythonMethods); PyRun_SimpleString(from pp3 import *); PyRun_AnyFile(stdin, NULL); Py_Finalize(); PythonMethods is the vector of type PyMethodDef that contains the function descriptors: static PyMethodDef PythonMethods[] = { {toll, py_toll, METH_VARARGS, }, {NULL, NULL, 0, NULL} }; Then I say toll() in the input script which calls py_toll() in the C++ source. It works. However, is there a way to avoid this dummy pp3 module and add the C++ functions directy to the main namespace in the Python script? Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetusICQ 264-296-646 -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
Tom Bradford wrote: Really what we're talking about here is weak typing in the form of optional type hinting performed on a function by function basis Not what most of the world calls weak typing. It is my feeling that this doesn't represent a sea-change in the way Python does things, and it's certainly *not* the way things are done in Java or C++, as both of those languages are strongly typed, wherein you can't even pass a parameter if it isn't of the expected type, or a subclass thereof. But I would call both of those languages weakly typed (and Python strongly typed). Any _correct_ type system must have contra-variant typing on results and co-variant typing on values. Java's type system breaks because it has decided to have arrays (which are both in and out, therefore pinned as to type) obey the subtype relationship of the elements of that array. So: array of truck-driver is a subtype of: array of driver and a procedure: procedure stores(driver[] arr, driver gus) arr[1] = gus Will type check as type-correct when passed a taxi-cab driver. I suspect such problems can be found in C++ as well, but I never hunted very hard. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: cgi problem
Am Wed, 08 Mar 2006 00:19:55 -0800 schrieb Paul Rubin: I'm trying to write a simple cgi that reads a post from the user's browser, does some stuff with the form data, and redirects the browser back to the originating url, i.e. I want the cgi to send a 302 redirect. Hi, I have this setup for a small script (for bigger things I use quixote) def cgi_main(): stdout=sys.stdout sys.stdout=sys.stderr # print soll zu Apache-Log try: html=cgi_html() except ReturnThis, r: stdout.write(str(r)) return stdout.write(Content-Type: text/html\n\n%s % html) CGI-Script *very* small ... # Python Imports import os import sys import cgitb cgitb.enable() import foo if __name__==__main__: foo.cgi_main() file foo: def cgi_main(): stdout=sys.stdout sys.stdout=sys.stderr # print should go to Apache-Log try: html=cgi_html() except ReturnThis, r: stdout.write(str(r)) return stdout.write(Content-Type: text/html\n\n%s % html) class ReturnThis(Exception): pass class Redirect(ReturnThis): def __init__(self, destination): if os.environ.get(HTTPS)==on: http=https://; else: http=http://; url=%s%s%s%s % (http, os.environ[SERVER_NAME], os.environ[SCRIPT_NAME], destination) header=Status: 302 Moved Temporarily\nLocation: %s\n\n % ( url) ReturnThis.__init__(self, header) Now you can 'raise Redirect(mylocation)' anywhere in your code. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
On Mar 8, 2006, at 7:20 AM, Tom Bradford wrote: Really what we're talking about here is weak typing in the form of optional type hinting performed on a function by function basis. As an option, what it would do is allow an author to semantically 'hint' to the interpreter that a function is expecting a certain type, and perform any implicit conversion if the passed type is not what was expected, thus translating to a semantically expected result. So how would that system deal with this? class A(object): def foo(self): print bar class B(object): def foo(self): print bar def typedfunction(x : A): x.foo() b = B() typedfunction(b) #Your system would probably consider this an error This is an example of why type checking/hinting is no good, as it would break duck typing. In terms of their definitions, A and B have nothing in common (ie. B is not a subclass of A), yet I should be able to use instances of either one, whenever the method 'foo' is expected. Type hinting would completely break that. This again is why I point you in the direction of PEP 246. The fact is, that with a system such as this, you could just 'not use it', and none would be the wiser, as it's an authorship extension rather than a calling extension. What I was suggesting is that nothing change other than function/method prototypes, and that everything, everwhere, at all times continues to be represented as scalars. The problem is when someone decides to use this option, and releases a library with it. Now everyone who wants to use this library is forced to use this type hinting. It would create a divide in available Python code. (Of course, adaption would result in the same issue, but I *think* more people would be willing to use adaption, as it doesn't break duck typing). Jay P. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyCon2006 - will the content be available for download?
Max M wrote: http://us.pycon.org/AudioVideoRecording/HomePage Thanks, after going to the URL, I clicked talks and got to http://us.pycon.org/talks ...this page lets u pick which talks you want to access. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
No one of the complainers and negativists do claim that they could do it much better. Indeed, I do not have to be able to write a particular program to notice it has bugs. On the other hand, (since I think the design, while not brilliant, is good) fixing the logo is something that can be achieved without too much fuss. But I think at times it might be usefull to consult professional aid. In the case of the logo design, I am not sure I agree. I think the twisted logo http://saph.twistedmatrix.com/blog/archives/twisted.png and the PyCon logo http://mirrors.ccs.neu.edu/Python/pub/old-www/pics/pycon-logo.gif were probably not designed by professional designers but rather by people who appreciate Python, and yet do have more appeal to the community and the outside world alike. If we are going to use a snake motif, we should use snakes that look like snakes. I suspect the current shy-tadpoles design was outsourced. (At one point NBC abandoned their very recognizable peacock for a totally vapid geometric design, for which they paid many thousands of dollars. (Including a huge settlement with a Nebraska TV station whose logo they had essentially copied) Eventually they reverted to a somewhat stylized peacock, which was a much better idea.) See http://en.wikipedia.org/wiki/National_Broadcasting_Company_logos It's also interesting in passing to notice that another one of NBC's non-peacock logos was called the snake, for reasons that will escape anyone who has not seen it animated. In any case, I will probably take a little more time to make the case that the shy tadpoles logo is a mistake. Finally, I disagree that the current logo is better than the neutral but consistently used php logo or the very clever java coffee mug logo, and notably the Ruby on Rails logo, which is first rate. mt -- http://mail.python.org/mailman/listinfo/python-list
Re: Interfacing with the command line
http://effbot.org/librarybook/os.htm scroll down about half a page to example 8. is that what you're looking for? PV -- http://mail.python.org/mailman/listinfo/python-list
Re: Interfacing with the command line
Exactly what I want. Thanks a mill! -- /usr/bin/byte -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
On 8 Mar 2006 07:47:15 -0800, Michael Tobis [EMAIL PROTECTED] wrote: No one of the complainers and negativists do claim that they could do it much better. Indeed, I do not have to be able to write a particular program to notice it has bugs. On the other hand, (since I think the design, while not brilliant, is good) fixing the logo is something that can be achieved without too much fuss. [snip] While I don't dislike the logo, there has been a lot of grumbling about it. Dislike has been due to aesthetic reasons, or the resemblance to a cross, or general it's not as good as x. So I gave it another close look, and I wondered if this would improve it: Retain the stylized blue snake. Remove the yellow snake, but keep its body that's in line horizontally with the blue snake's, and color it blue. Result: one snake with a horizontal tail that curls up slightly at the right edge. Or, again remove the yellow snake, but have the blue snake's tail go down, and lengthen the head to be flush with the left edge of the logo. Result: a stylized snake that resembles the letter P. (maybe too corny) Both ideas lose the symmetry, but retain the simplicity, of the current logo. And hopefully will look like a snake instead of tadpoles (??) Or, we just grow to like the logo as is and get back to programming ;) Rob -- http://mail.python.org/mailman/listinfo/python-list
Testing
This is a test -- http://mail.python.org/mailman/listinfo/python-list
help with loops
Paul, I will check out difflib thanks. Scott -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
On 3/8/06, Robert Boyd [EMAIL PROTECTED] wrote: On 8 Mar 2006 07:47:15 -0800, Michael Tobis [EMAIL PROTECTED] wrote: No one of the complainers and negativists do claim that they could do it much better. Indeed, I do not have to be able to write a particular program to notice it has bugs. On the other hand, (since I think the design, while not brilliant, is good) fixing the logo is something that can be achieved without too much fuss. [snip]While I don't dislike the logo, there has been a lot of grumblingabout it. Dislike has been due to aesthetic reasons, or theresemblance to a cross, or general it's not as good as x. So I gave it another close look, and I wondered if this would improve it:Retain the stylized blue snake. Remove the yellow snake, but keep itsbody that's in line horizontally with the blue snake's, and color it blue. Result: one snake with a horizontal tail that curls up slightlyat the right edge.snipWhen I first saw it I thought twisted than I thought is that a cross? then I thought maybe it's a messed up yin/yang. I thought the yin/yang idea might be interesting, and maybe would work but the overall shape needs to be more circular to convey that idea better.But I'm no graphic designer -- Thomas G. Willis---http://i-see-sound.comhttp://tomwillis.sonicdiscord.com America, still more rights than North Korea -- http://mail.python.org/mailman/listinfo/python-list
Re: Extending embedded Python: Adding single methods
Torsten Bronger wrote: Hallöchen! I'd like to script C++ funtions by an embedded Python interpreter. So far, my C++ main() function contains: Py_Initialize(); Py_InitModule(pp3, PythonMethods); PyRun_SimpleString(from pp3 import *); PyRun_AnyFile(stdin, NULL); Py_Finalize(); PythonMethods is the vector of type PyMethodDef that contains the function descriptors: static PyMethodDef PythonMethods[] = { {toll, py_toll, METH_VARARGS, }, {NULL, NULL, 0, NULL} }; Then I say toll() in the input script which calls py_toll() in the C++ source. It works. However, is there a way to avoid this dummy pp3 module and add the C++ functions directy to the main namespace in the Python script? Yes. You can import __builtin__, and add methods to it. This is a snippet from the bdist_wininst code, which embeds Python: http://svn.python.org/view/python/trunk/PC/bdist_wininst/install.c?rev=38414view=markup PyMethodDef meth[] = { {create_shortcut, CreateShortcut, METH_VARARGS, NULL}, {get_special_folder_path, GetSpecialFolderPath, METH_VARARGS, NULL}, {get_root_hkey, (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, {file_created, FileCreated, METH_VARARGS, NULL}, {directory_created, DirectoryCreated, METH_VARARGS, NULL}, {message_box, PyMessageBox, METH_VARARGS, NULL}, }; ... mod = PyImport_ImportModule(__builtin__); if (mod) { int i; for (i = 0; i DIM(meth); ++i) { PyObject_SetAttrString(mod, meth[i].ml_name, PyCFunction_New(meth[i], NULL)); } } ... Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
Michael Tobis wrote: No one of the complainers and negativists do claim that they could do it much better. Indeed, I do not have to be able to write a particular program to notice it has bugs. just wait until you mention that rottened egg you found yesterday, and all the chickens in the world start calling you names... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
This type of hinting would only break type ducking in-so-much as a function that leveraged that hinting would be looking specifically for an instance of a particular type, which would be absolutely no different than a developer performing the type check manually and throwing it out if the type were invalid. It would otherwise just be a lot of tedious and repetitive work for the developer. The fact is, as valuable as type ducking is, it has drawbacks in its ambiguousness, that are especially harmful to large systems that are being developed with many hands in the pot. And no, people who use a library that leverages this type of hinting are most certainly no more effected by it than they would be by the methods performing the check manually. As the feature is optional, if you want to allow a method that allows for type ducking, you would write it in exactly the same way you write it now, and nobody would be harmed in the process. -- http://mail.python.org/mailman/listinfo/python-list
Re: generators shared among threads
[EMAIL PROTECTED] wrote: Paul wrote: def f(): lock = threading.Lock() i = 0 while True: lock.acquire() yield i i += 1 lock.release() but it's easy to make mistakes when implementing things like that (I'm not even totally confident that the above is correct). The main problem with this is that the yield leaves the lock locked. If any other thread wants to read the generator it will block. I don't think so. The second thread will start right after the yeild, and release the lock before acquiring it. Here's a demo: import threading import time def start_daemon(closure): t = threading.Thread(target=closure) t.setDaemon(True) t.start() def f(): lock = threading.Lock() i = 0 while True: lock.acquire() yield i i += 1 lock.release() fgen = f() def count3(): for _ in range(3): print '---', fgen.next() time.sleep(10) start_daemon(count3) time.sleep(1.0) print +++, fgen.next() -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Bidirectional communication over unix socket (named pipe)
Hi, I feel like I should apologize in advance because I must be missing something fairly basic and fundamental here. I don't have a book on Python network programming (yet) and I haven't been able to find an answer on the net so far. I am trying to create a pair of programs, one (the client) will be short-lived (fairly) and the second (server) will act as a cache for the client. Both will run on the same machine, so I think a simple file socket is the easiest and most reliable method. The problem I have is that the client can send to the server, but the server can't send back to the client because it gets this error: socket.error: (107, 'Transport endpoint is not connected') This is despite the client waiting on a socket.recv() statement. Is the client really not connected, or is the server unaware of the connection? And how do I fix this? I was able to get this working by switching to AF_INET, but that is not what I want. Unix sockets are bidirectional, correct? I have never programmed one, but I know that programs like clamav use a socket to receive an email to scan and return the result. Any help would be greatly appreciated! Jeff *** server.py *** #!/usr/bin/python import socket import os, os.path import time if os.path.exists(/tmp/mysock): os.remove(/tmp/mysock) server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) server.bind(/tmp/mysock) while True: datagram = server.recv(1024) if not datagram: break print datagram # the preceeding works, and I see the TEST TEST TEST statement the client sent time.sleep(2) # it dies on the next statement. server.send(Thank you\n) server.close() if os.path.exists(/tmp/mysock): os.remove(/tmp/mysock) *** client.py: *** #!/usr/bin/python import socket client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) client.connect(/tmp/mysock) TX = TEST TEST TEST TX_sent = client.send(TX) if TX_sent len(TX): print TX incomplete while True: print Waiting... datagram = client.recv(1024) # the client sits here forever, I see the waiting appear but it doesn't advance beyond # the recv statement. if not datagram: break print Received: ,datagram client.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
Tom Bradford wrote: This type of hinting would only break type ducking in-so-much as a function that leveraged that hinting would be looking specifically for an instance of a particular type, which would be absolutely no different than a developer performing the type check manually and throwing it out if the type were invalid. It would otherwise just be a lot of tedious and repetitive work for the developer. The thing with duck-typing is that exactly this kind of type-checking is _not_ what the developer is supposed to do. Doing so breaks duck-typing anyway, regardless of syntactic sugaring or not. Adding such a feature would immediately start people creating code that for example requires a list where an iterable would suffice - and thus eating from the usability of python in general. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Type Hinting vs Type Checking and Preconditions
On Mar 8, 2006, at 8:43 AM, Tom Bradford wrote: This type of hinting would only break type ducking in-so-much as a function that leveraged that hinting would be looking specifically for an instance of a particular type, which would be absolutely no different than a developer performing the type check manually and throwing it out if the type were invalid. It would otherwise just be a lot of tedious and repetitive work for the developer. Wow, I *really* hope that you're not writing functions that check the types of the incoming arguments. It's generally accepted that using isinstance() and type() in your code are evil things to do. There are very few places where it's appropriate to use them. If you're using them a lot, then I suspect you're relatively new to Python, and are programming with a Java/C++ mindset. We'll have to do what we can to get you out of that :) Jay P. -- http://mail.python.org/mailman/listinfo/python-list