Re: Mixing Decimal and float
On Wed, 02 Jun 2010 05:17:11 -0700, B.V. wrote: But trying to be open to other languages, the server implements also an XMLRPC interface (and also a JSONRPC-like interface). That's the key point: Decimal is python specific. So in an application, you can't rely on the value received from a client, because depending on the protocol, the type of the value is different. So the idea was to create a class that can behave like a Decimal or a float depending on the context, and set xmlrpclib.Unmarshaller.dispatch[double] to a function that return a Float instance. Looking at the Tryton docs, it seems that it already supports field types that can't be directly represented in XMLRPC or JSON, like BigInteger or Selection. How are these serialized over the non-python RPC mechanisms? Could you not do the same for Decimals? A contributor filed an issue on the bug tracker (https:// bugs.tryton.org/roundup/issue1575) and because he's a nice guy (ok it's a friend of mine), he made a patch proposal (http:// codereview.appspot.com/1387041). The end of the story is in the comments of the proposal. But we also need to do: isinstance(Float('1'), float) == True isinstance(Float('1'), Decimal) == True Can you explain why you need this? It's a requirement of the project leader. Should isinstance(Float('1.1'), float) and isinstance(Float('1.1'), Decimal) also both be true, or would only one of those be true? (And by the way, what value would Float('1.1') have? float('1.1') and Decimal('1.1') are different values.) I think they both should be True, for '1', '1.1', '0', '0.1', ... For the value, I would say that it depends of the definition of the field (fields.Float or fields.Numeric). I don't think your approach can succeed; I'd suggest just subclassing 'object' and abandoning the 'isinstance' requirements. Or perhaps creating a subclass of Decimal that interacts nicely with floats. You might also want to investigate the numbers ABC, though that's new in Python 2.6. First, Float implementation was a subclass of Decimal that works with floats, and solves many (maybe all) problems. But as you may read in the comments of the patch proposal, it seems to be not enough. B. -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a class at run-time
On Fri, 26 Mar 2010 08:54:11 -0700, Michel wrote: I want to add a method to a class such that it can be invoked on specifics instances. You solution works (as well as Patrick's one), thanks ! I still have a question though. If I print the type of the self object I get when my method is called, I get class 'test.TestClass'. I guess this is because the method is defined as a class method. This is ok in my case, but just out of curiosity, what should I do to change this method to an instance method? It already is an instance method. When you create a TestClass instance, the type of that instance is TestClass (the type of TestClass itself is type). -- http://mail.python.org/mailman/listinfo/python-list
Re: Create a class at run-time
On Thu, 25 Mar 2010 15:00:35 -0700, Michel wrote: I'm trying to dynamically create a class. What I need is to define a class, add methods to it and later instantiate this class. Methods need to be bound to the instance though, and that's my problem. Here is what I have so far: I'm not entirely sure what you mean by binding methods to the instance. Do you mean you need to dynamically add methods to a specific instance? Or that you need to add methods to a class, such that they can be invoked on specific instances? For the latter, just do: TestClass.test_foo = test_foo For the former, try: tc = TestClass() tc.test_foo = types.MethodType(test_foo, tc) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure virtual functions in Python?
On Sat, 20 Feb 2010 08:12:01 -0800, lallous wrote: How can I do something similar to pure virtual functions in C++ ? From what you want, it seems like you want cb() to not be called if it isn't implemented in the derived class; this isn't really what pure virtual functions in C++ do - pure virtual functions enforce, at compile time, that the derived class implements the method. If you have a situation when you want to either call a derived class's version of cb(), or do nothing, can you not just have an implementation of cb() in the base class that does nothing, i.e. class C1(object): def cb(self, param1, param2): pass -- http://mail.python.org/mailman/listinfo/python-list
Re: Modifying Class Object
On Thu, 11 Feb 2010 07:37:35 +0100, Alf P. Steinbach wrote: * Steven D'Aprano: s = [1] t = s # Binds the name t to the object bound to the name s. t[0] = 2 # Changes the object bound to the name t print(s) # Checks the object via the original name. Notice that your version describes what happens according to some implementation, below the level of the Python virtual machine. Consider just the assert( t is not s ) t = s Does this change anything at all in the computer's memory? If it doesn't, then it has no effect whatsoever. But since it does have an effect, a memory change has been effected. I don't think your disagreeing with Steven here - by talking about the computers memory, it's clear that you are talking about the details of an implementation of python, not the semantics of python itself. Unless, of course, you are under the misapprehension that the computer's memory is relevant to the python language, rather than the particular implementation. Python itself has nothing to do with computers or memory; these are mere implementation details. -- http://mail.python.org/mailman/listinfo/python-list
Re: umlauts
On Sat, 17 Oct 2009 18:54:10 +0200, Diez B. Roggisch wrote: This is wierd. I looked at the site in FireFox - and it was displayed correctly, including umlauts. Bringing up the info-dialog claims the page is UTF-8, the XML itself says so as well (implicit, through the missing declaration of an encoding) - but it clearly is *not* utf-8. The headers correctly identify it as ISO-8859-1, which overrides the implicit specification of UTF-8. I'm not sure why Firefox is reporting it as UTF-8 (it does that for me, too); I can see the umlauts, so it's clearly processing it as ISO-8859-1. -- http://mail.python.org/mailman/listinfo/python-list
Re: using python interpreters per thread in C++ program
On Mon, 07 Sep 2009 19:22:17 -0700, ganesh wrote: My application is a TCP server having multiple client connectons. C++ PTHREADS are for each connected socket and the message received on the socket is evaluated by python functions. If I use only one process level Do you have to use threads? If you use a process per connection, rather than a thread, each process will have its own GIL. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is feedparser deprecated?
On Fri, 07 Aug 2009 12:57:11 -0700, alex23 wrote: John Nagle na...@animats.com wrote: Feedparser hasn't been updated since 2007. Does this mean Feedparser is dead? Wouldn't you be better served asking this on the feedparser bug tracker? http://code.google.com/p/feedparser/issues/list But if the project _is_ dead, one would be unlikely to get a response on the bug tracker; as seems, in fact, to have happened already: http://code.google.com/p/feedparser/issues/detail?id=160start=100 I take it that the lack of response to this issue means the answer is yes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Confessions of a Python fanboy
On Thu, 30 Jul 2009 17:57:48 -0400, Luis Zarrabeitia wrote: As I understood the question, it was was wrong in 'for var in container' in comparison with ruby's container.each? What's the (semantic) difference between for localVar in container: block and container.each{|localVar| block} I don't think each is a particularly compelling example of Ruby's blocks - as you say, it's easily replaceable with a Python for-loop. The advantage of Ruby's syntax is that it allows you to define further functions that are sort-of like new control structures. So you have things like: File.open('myfile', 'r') do |file| while line = file.gets puts line end end Which is like a python's: with open('myfile', 'r) as f: for line in f: print f However, with Ruby, this kind of scoping construct can be added without adding new syntax. Another interesting example is the Sinatra web framework, which allows you to write a web app with something like: get '/' do Index page end post '/:name' do Posted to + params[:name] end Which looks something like a DSL for web apps, but is accomplished solely with normal ruby functions. More: http://www.sinatrarb.com/intro.html Ruby blocks are, fundamentally, syntactic sugar, but they are kind of neat. -- http://mail.python.org/mailman/listinfo/python-list
Re: comments? storing a function in an object
On Mon, 20 Jul 2009 21:53:59 -0400, Esmail wrote: In general I would agree with you, but in my specific case I want so store some additional meta-data with each function, such as the valid range for input values, where the max or minimum are located, the name/source for the function etc. I am creating list of functions for use in testing optimization code, so it seems best to store this data along with the function I am going to optimize in order to verify the results for a given range (for instance). You can set attributes on functions, so if your class is just storing this data, rather than altering the behavior of the function, you may be able to just use a function: def f(x, y): x * y return x * y f.arguments_max = [1000, 255] A function also already knows how many arguments it takes, which you can access as f.func_code.co_argcount -- http://mail.python.org/mailman/listinfo/python-list
Re: tough-to-explain Python
On Fri, 10 Jul 2009 16:27:12 -0400, Terry Reedy wrote: a bug, bug a limitation due to using limited-range numbers. If one uses residue classes instead of integers, and makes no adjustment, I consider it wrong to blame Bentley. But it was Bentley himself who used the C int type, so it hardly seems unreasonable to blame him. -- http://mail.python.org/mailman/listinfo/python-list
Re: Observer implementations
On Mon, 15 Jun 2009 15:29:34 +0200, Tobias Weber wrote: Despite the confusion all those are useable, but I ran into the problem that I can't register a @classmethod because weakref doesn't like them. What do you mean by weakref not liking class methods? This seems to work OK on python 2.6 class C(object): @classmethod def cm(cls): return Class method of + str(cls) cm = C.cm print cm() # Outputs: # Class method of class '__main__.C' w = weakref.ref(cm) print w # Outputs: # weakref at 0x1a362b8; to 'instancemethod' at 0x7ff1cc9ebb40 (cm) print w() # Outputs: # bound method type.cm of class '__main__.C' print w()() # Outputs: # Class method of class '__main__.C' del cm print w # Outputs: # weakref at 0x1a362b8; dead -- http://mail.python.org/mailman/listinfo/python-list
Re: Lexical scope: converting Perl to Python
On Fri, 12 Jun 2009 22:02:53 -0700, Andrew Savige wrote: Notice that this code uses Perl's lexical scope to hide the %private_hash variable, but not the public_fn() function. You might try: def public_fn(param): private_hash = publicfn.private_hash return private_hash[param] public_fn.private_hash = {'A':42, 'B':69} (You don't have to assign public_fn.private_hash to a local variable, but you might want to, to avoid extra typing, if you refer to private_hash more than a couple of times in the function). -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping methods of built-in dict
On Thu, 21 May 2009 02:31:29 +, Steven D'Aprano wrote: So the problem isn't directly with getmembers, but with the predicate functions you have passed to it (inspect.isfunction and inspect.method). Try inspect.ismethoddescriptor instead. Or perhaps callable ? callable({}.get) and callable(dict.get) are both true, although I don't know if that's guaranteed (I'm wondering if methods could be implemented with an object such that method_object.__get__ returned a callable, but where method_object itself wasn't callable). -- http://mail.python.org/mailman/listinfo/python-list
Re: JSON and Firefox sessionstore.js
On Thu, 23 Apr 2009 02:16:07 +, Steven D'Aprano wrote: I'm leaning towards this being a bug in the json module. Unless somebody can point me at a credible source that sessionstore.js isn't JSON, I will report this as a bug. I'm just another random guy on the internet, but I'm pretty sure sessionstore.js isn't strictly correct JSON - nothing in the spec at http://www.json.org/ suggests that JSON data can start with an open parenthesis, or that member names can be unquoted strings, but sessionstore.js has both of these features. It might well be useful for the json module to accept these slightly non-conforming files, though. For something with at least a vague air of credibility to it, somebody who appears to be a Mozilla developer comments on their bug tracker, that sessionstore.js isn't pure JSON (though he only identifies the parantheses, which are much easier to fix, as being a problem): https://bugzilla.mozilla.org/show_bug.cgi?id=407110#c2 -- http://mail.python.org/mailman/listinfo/python-list
Re: file.read() doesn't read the whole file
On Fri, 20 Mar 2009 07:03:35 -0700, Sreejith K wrote: I'm using the above codes in a pthon-fuse's file class's read function. The offset and length are 0 and 4096 respectively for my test inputs. When I open a file and read the 4096 bytes from offset, only a few lines are printed, not the whole file. Actually the file is only a few bytes. But when I tried reading from the Interactive mode of python it gave the whole file. Your example doesn't show what you are doing with data after you've read it. Presumably you're outputting it somehow, which is where you see that it doesn't contain the whole file. But are you sure the problem is in the reading, and not in the outputting? Could you show the section of the code where you output data? -- http://mail.python.org/mailman/listinfo/python-list
Re: REDIRECT
On Wed, 18 Mar 2009 21:30:59 -0700, gaeasiankom wrote: What actually I'm try to do is : I'm having a Login page which developed in HTML. When I click on the Login button I want the page to validate (at datastore of google app) using python and redirect to other HTML page. As what I understand, Python is the only language that supported by the GoogleApps. The webapp framework that comes with the Google Apps SDK has a function for redirecting: http://code.google.com/appengine/docs/python/tools/webapp/redirects.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the best way to translate an idiom
On Sun, 14 Dec 2008 21:08:33 -0800, James Stroud wrote: Yes. I think it was the British who decided that the apostrophe rule for it would be reversed from normal usage relative to just about every other noun. I'm not sure the purpose--maybe it was to give compulsive proofreaders a raison d'etre. It's because it is a pronoun; you don't put an apostrophe in his, either. -- http://mail.python.org/mailman/listinfo/python-list
Re: Text parsing via regex
On Mon, 08 Dec 2008 13:42:00 -0500, r0g wrote: Robocop wrote: However i'm having several problems. I know that playskool regular expression i wrote above will only parse every 50 characters, and will blindly cut words in half if the parsed string doesn't end with a whitespace. I'm relatively new to regexes and i don't know how to have it take that into account, or even what type of logic i would need to fill in the extra whitespaces to make the string the proper length when avoiding cutting words up. So that's problem #1. Regexps may not be the solution here. You could consider the textwrap module ( http://docs.python.org/library/textwrap.html ), although that will only split your text into strings up to 50 characters long, rather than padding with whitespace to exactly 50 characters. If you really need the strings to be exactly 50 characters long (and, are you sure you do?), try: # Split the input up into separate words words = input_string.split() groups = [] current_string = '' current_length = 0 for word in words: if current_length + len(word) +1 = 50: # If adding a space followed by the current word # wouldn't take us over 50 chars, add the word. current_string += ' ' + word current_length += len(word)+1 else: # Pad the string with spaces, and add it to our # list of string current_string += ' ' * (50 - current_length) groups.append(current_string) current_string = word current_length = len(word) Problem #2 is that because the string is of arbitrary length, i never know how many parsed strings i'll have, and thus do not immediately know how many variables need to be created to accompany them. It's easy enough with each pass of the function to find how many i will have by doing: mag = len(string) upper_lim = mag/50 + 1 But i'm not sure how to declare and set them to my parsed strings. Whenever you find yourself thinking I don't know how many variables I need, the answer is almost always that you need one variable, which is a list. In the code above, the 50-char-long strings will all get put in the list called groups. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 06 Dec 2008 16:34:56 -0800, Erik Max Francis wrote: `$` as a shortcut for self, on the other hand, gives absolutely no mnemonic indication what it stands for, and users would be simply left guessing. However, $ is sometimes used as an alternative way of writing S̸ (I've attempted to write here S followed by U+0338 COMBINING LONG SOLIDUS OVERLAY, in order to produce an S with a stroke through it). This is the symbol of the barred subject in Lacanian psychoanalysis, which is the Lacanian symbol for the concept of the self (see http://nosubject.com/Bar ). So, if we want Python to the programming language of choice for Lacanian psychoanalysts, perhaps we should adopt the symbol $ (or even, with Python 3's support for unicode identifiers, S followed by U+0388) instead of self. -- http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
On Thu, 17 Jul 2008 15:08:17 -0700, castironpi wrote: The Python disassembly is baffling though. y= 3 dis.dis('x=y+1') You can't disassemble strings of python source (well, you can, but, as you've seen, the results are not meaningful). You need to compile the source first: code = compile('y=x+1','-', 'single') dis.dis(code) 1 0 LOAD_NAME0 (x) 3 LOAD_CONST 0 (1) 6 BINARY_ADD 7 STORE_NAME 1 (y) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE You may well find these byte codes more meaningful. Note that there is a list of opcodes at http://docs.python.org/lib/bytecodes.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a web-editor I can use with Python?
On Fri, 13 Jun 2008 22:10:51 +0100, Ognjen Bezanov wrote: I am building an application using WxWidgets, and its job is to manage HTML data in a database. Now I need essentially a HTML editor that I can embed into my program, that will parse the HTML and allow the user to edit it. How about wx.richtext.RichTextCtrl , along with the wx.richtext.RichTextHTMLHandler ? http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a set of lambda functions
On Sun, 25 May 2008 13:43:15 +0200, Martin Manns wrote: I try to get a set of lambda functions that allows me executing each function code exactly once. Therefore, I would like to modify the set function to compare the func_code properties (or the lambda functions to use this property for comparison). With Ivan's approach, you lose access to the actual lambdas, so you need to create a new function and then modify its code object to actually call the code; this seems a little clunky to me. You might instead want to wrap the lambdas in an object that will do the comparison you want: class Code(object): def __init__(self, func): self._func = func def __cmp__(self, other): return cmp(self._func.func_code, other._func.func_code) def __call__(self, *args, **kwargs): return self._func(*args, **kwargs) func_set = set(Code(f) for f in funclist) -- http://mail.python.org/mailman/listinfo/python-list
Re: which datastructure for fast sorted insert?
On Sun, 25 May 2008 13:05:31 -0300, Gabriel Genellina wrote: Use a list, and the bisect module to keep it sorted: That's worth doing if you need the data to be sorted after each insert. If the OP just needs the data to be sorted at the end, using a data structure with fast inserts (like a set) and then sorting at the end will likely be faster. -- http://mail.python.org/mailman/listinfo/python-list
Re: which datastructure for fast sorted insert?
On Sun, 25 May 2008 15:49:16 -0700, notnorwegian wrote: i meant like set[pos], not iterate but access a specific position in the set. If you need to access arbitrary elements, use a list instead of a set (but you'll get slower inserts). OTOH, if you just need to be able to get the next item from the set, you can use an iterator: now i have to do: s = toSet.pop() toSet.add(s) i = iter(toSet) s = i.next() if i want to get the url of the next item in a set, how would i do that? i can do this with a list: def scrapeSitesX(startAddress, toList, listPos): return scrapeSites(toList[listPos], toList, listPos+1) to use recursion with a list. i can work around that but it doesnt get as elegant. Do you have to use recursion here? Why not: for site in toList: scrape(site) -- http://mail.python.org/mailman/listinfo/python-list
Re: which datastructure for fast sorted insert?
On Sun, 25 May 2008 18:42:06 -0700, notnorwegian wrote: def scrapeSites(startAddress): site = startAddress sites = set() iterator = iter(sites) pos = 0 while pos 10:#len(sites): newsites = scrapeSite(site) joinSets(sites, newsites) You change the size of sites here, which means you can no longer use the iterator. wtf? im not multithreading or anything so how can the size change here? How about: def scrape_sites(start_address): sites = set([start_address]) sites_scraped = set() # This will run until it doesn't find any new sites, which may be # a long time while len(sites) 0: new_sites = set() for site in sites: new_sites.update(scrape_site(site)) sites_scraped.update(sites) sites = new_sites.difference(sites_scraped) return sites -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
On Sun, 25 May 2008 21:41:09 -0400, Jerry Stuckle wrote: The the good programmers are able to adapt to the language and make the most of whatever language they're using. The result is good code. OTOH, poor programmers I have known have found all kinds of excuses - from the language itself to lack of requirements, to anything else they can blame, except the real root of the problem. That's true - but I wonder if there might not be differences at the margins. Some languages (and, which is not quite the same but not easy to fully distinguish either, the communities around some languages) may encourage mediocre programmers to produce slightly more or less mediocre programs. Some features of Python (the one that really stands out for me is not default-initializing variables on first use; the comparatively clean standard library might be another), and some features of the Python community (which, IME, has more members more explicitly committed to writing clean code) I think do make Python a better environment for us mediocre programmers. But maybe I'm wrong - I've never been paid to write Python programs, whereas I have been paid to write PHP, so I might just be projecting my frustrations with work onto the language. I've also not used PHP5 much in anger, which does look to be a lot nicer than earlier versions. -- http://mail.python.org/mailman/listinfo/python-list
Re: error using all()/numpy [TypeError: cannot perform reduce with flexible type]
On Fri, 23 May 2008 00:12:35 -0700, Marc Oldenhof wrote: It seems that Python calls numpy's all instead of the standard one, is that right? If so, how can I call the standard all after the numpy import? [import numpy is not a desirable option, I use a lot of math in my progs] I think the ideal solution is to try and persuade yourself that typing numpy. in front of some functions now and then is not that big a price to pay to avoid name collisions; using an editor with code completion would probably help in that task. You could also try: import numpy as n which reduces the typing a bit and limits you to one possible name collision, or from numpy import array, gradient #and whatever else you need or import numpy array = numpy.array gradient = numpy.gradient # Then you can access the names you use a lot # directly, while accessing stuff you use less # frequently via numpy.whatever in which case you'll know exactly which names you're overwriting. Peter's solution, of explicitly deleting some names that you've imported, strikes me as less good, because you might find the same problem recurs later, if the numpy developers add new names to the module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
On Thu, 22 May 2008 19:35:50 -0700, Charles Hixson wrote: Although when comparing Candygram with Erlang it's worth noting that Candygram is bound to one processor, where Erlang can operate on multiple processors. (I'd been planning on using Candygram for a project at one point, but this made it unusable.) Really? The FAQ says it uses operating system threads, which I would have thought would mean it runs on multiple processors (modulo, I suppose, the issues with the GIL). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
On Mon, 12 May 2008 16:39:25 -0700, Dave Parker wrote: I've read that one of the design goals of Python was to create an easy- to-use English-like language. That's also one of the design goals of Flaming Thunder at http://www.flamingthunder.com/ , which has proven easy enough for even elementary school students, even though it is designed for scientists, mathematicians and engineers. A COBOL for the 21st century! Just what we need. -- http://mail.python.org/mailman/listinfo/python-list
Re: Purpose of operator package
On Wed, 14 May 2008 00:38:44 +0200, Christian Heimes wrote: Eric Anderson schrieb: Seems like unnecessary code but obviously I know nothing about Python. Correct, the truth example isn't a good example. if argv is better. I hadn't heard of operator.truth before. Does it do anything different from bool(x) ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Database vs Data Structure?
On Thu, 17 Apr 2008 19:30:33 -0700, erikcw wrote: use some sort of data-structure (maybe nested dictionaries or a custom class) and store the pickled data-structure in a single row in the database (then unpickle the data and query in memory). Why would you want to do this? I don't see what you would hope to gain by doing this, over just using a database. -- http://mail.python.org/mailman/listinfo/python-list
Re: gc question
On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote: Well, that suits me. The most unnatural thing about Python was adapting to the idea of just letting unreleased resources go jogging off wherever. :) Yes, that's a bad habit that garbage collection can encourage. GC is good for managing memory, but not good for managing other resources, so if an object holds some other resource, it's important to make sure the resource is released in a timely fashion rather than relying on the finalizer (the __del__ function). CPython uses reference counting, so it usually destroys objects fairly soon after the stop being used. But JPython and IronPython don't do reference counting, so forgetting to clean up resources can be a significant problem. Where's the f.close? You don't need it! Although, you still don't need f.close, with the new with statement: with open('myfile') as f: string = f.readline() # f.close() gets called automatically here, without waiting for # garbage collection. If you want to use this in 2.5, you have to write: from __future__ import with_statement The big advantage here is that f.close will get called if the block exits normally, or if there is an exception. For more, see http://effbot.org/pyref/with.htm . -- http://mail.python.org/mailman/listinfo/python-list
Re: joining strings question
On Fri, 29 Feb 2008 08:18:54 -0800, baku wrote: return s == s.upper() A couple of people in this thread have used this to test for an upper case string. Is there a reason to prefer it to s.isupper() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Speed of light [was Re: Why not a Python compiler?]
On Mon, 11 Feb 2008 14:07:49 -0800, Erik Max Francis wrote: experience. The notion of impetus -- where an object throw moves in a straight line until it runs out of impetus, then falls straight down -- is clearly contrary to everyday experience of watching two people throw a ball back and forth from a distance, since the path of the ball is clearly curved. It's clear _to us_ because when we think about such things, we think in Newtonian terms. I'm not at all sure it would have been clear to people in the middle ages; when you throw a ball, it whizzes by so fast, it's hard to be sure how it's actually moving. -- http://mail.python.org/mailman/listinfo/python-list
Re: type, object hierarchy?
On Sun, 03 Feb 2008 21:31:44 -0800, 7stud wrote: On Feb 3, 10:28 pm, 7stud [EMAIL PROTECTED] wrote: From the docs: issubclass(class, classinfo) Return true if class is a subclass (direct or indirect) of classinfo. print issubclass(Dog, object) #True So Dog is a subclass of object print issubclass(type, object) #True and type is also a subclass of object. But print issubclass(object, type) # False so print issubclass(Dog, type) #False which is what you would expect - Dog is a subclass of object, and object isn't a subclass of type, so Dog isn't a subclass of type either. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make format operator % work with unicode as expected
On Sun, 27 Jan 2008 05:32:40 +, Peter Pei wrote: Yes, it is true that %s already support unicode, and I did not contradict that. But it counts the number of bytes instead of characters, and makes things like %-20s out of alignment. If you don't understand my assertion, please don't argue back and I am only interested in answers from those who are qualified. What version of python are you using? On python 2.4 and 2.5 on linux, %-20s counts the characters, not the bytes, or, I think it does. when I run: print u'%-20s|\n%-20s|' % (u'foo bar', u'foo bár') the output is: foo bar | foo bár | -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems getting Python scripts to run on server
On Wed, 23 Jan 2008 19:41:17 -0800, Yansky wrote: Hi, I'm having a lot of problems getting any Python scripts to run on my website. I have put them in the cgi-bin directory and chmodded both the directory and files to 755. But when I try to access the script, I get a 404 error: http://forboden.com/cgi-bin/wp.py Note that you don't get a 404 error _from the web server_ - you get it from wordpress (or at least, I do when I look at your page). So what I think is happening is that either the server, or wordpress, doesn't see a file at the URL /cgi-bin/wp.py, and so it thinks your are trying to access a wordpress post, and http://forboden.com/cgi-bin/wp.py is getting translated to http://forboden.com/index.php/cgi-bin/wp.py . I suspect the problem is in the rewrite rules in the .htaccess in your root directory. My wordpress installation has these rewrite rules: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d Which, as I understand it mean not a file and not a directory respectively. If your cgi-bin is not in your document root, presumably cgi-bin/wp.py will indeed show up as not being a file or directory. I'm no mod_rewrite wizard, but looking at the docs[1], maybe you could replace those two lines above with: RewriteCond %{REQUEST_URI} !-U (thought the docs say this can impact your server's performance!) I'm just guessing at the cause of your problem, but I hope this helps. [1] http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Immutable Geometry Types
On Sun, 16 Dec 2007 18:13:47 -0800, [EMAIL PROTECTED] wrote: I am learning python, having learnt most of my object orientation with java, and decided to port some of my geometry classes over. I haven't used immutability in python before, so thought this would be an interesting chance to learn. I am looking for feedback on any ways in which I might have left variables unprotected, and ways in which I am not being pythonic. I'm not sure it's pythonic to worry too much about enforcing the immutability; and disabling setattr makes the internal attribute setting a pain in the arse, for little real gain. class Angle (object): I'm not sure about this, but you might want to make Angle a subclass of float ; it would save you re-implementing the comparison operators (although you'ld still have to re-implement the arithmetic operators to get them to return an Angle instance rather than a float). def __init__(self, val, type = 'rad'): if type == 'rad': super(Angle, self).__setattr__('_value', val) else: super(Angle, self).__setattr__('_value', math.radians(val)) You might want to normalize the angle to between 0 and 2*pi here (though you might not, depending on exactly what you want to represent). Assuming that the user meant degrees in the else branch strikes me as a mistake; what if they mis-typed rad as rsd or something? Better to explicitly check, and raise an exception if the value isn't one of 'rad' or 'deg'. Another thing you might want to consider is using keyword arguments, rather than a string. Like: def __init__(self, radians=None, degrees=None): if radians is not None: self._value = radians elif degrees is not None: self._value = math.radians(degrees) else: raise TypeError(Angle creation must specify \ keyword argument 'radians' or 'degrees') Used like: a = Angle(math.pi) # Uses radians by default a = Angle(radians=2*math.pi) # Or you can specify it explicitly a = Angle(degrees=180) # Or specify degrees def __setattr__(self, name, value): Suppress setting of data - Angle is immutable self._immutableError() def __delattr__(self, name): Suppress deleting of data - Angle is immutable self._immutableError() As I say, I wouldn't bother with these, as they make the implementation more annoying to no real gain. def __add__(self, other): if isinstance(other, Angle): return Angle(self._value + other._value) return NotImplemented Using 'isinstance' is usually a mistake - rather than checking for type, you should just use an object as if it were the correct type and, if necessary, deal with the resulting exceptions. This means you can use objects of a different type, as long as they have the right interface. Here, I'd do: def __add__(self, other): return Angle(self.radians + other.radians) and likewise for __sub__. def __mul__(self, other): return self * other if isinstance(other, Angle): return Angle(self._value * other._value) return NotImplemented Leaving aside my earlier point about not checking for types, does it even make sense to multiply an angle by another angle? I would have thought you multiplied angles by numbers. So just do: def __mul__(self, other): return Angle(self._value * other) And the same for __div__ def fromCos(self, c): return angle with specified cos return Angle(math.acos(c)) fromCos = classmethod(fromCos) You could use decorators here; and the preferred python style for method names is all lower case, separated by underscores: @classmethod def from_cos(self, c): return Angle(math.acos(c)) radians = property(lambda self: self._value, lambda x: self._immutableError()) You don't need to explicitly raise an exception in the setter; just don't specify a setter function, and attempting to set the property will raise an AttributeError. DEG_30 = Angle(math.radians(30)) Given that you've gone to the trouble of creating a constructor that will take values as degrees, why not use it here? -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Sun, 09 Dec 2007 11:58:05 -0800, MonkeeSage wrote: class A attr_accessor :a # == self.a, # accessible to instances of A def initialize @a = foo # A.__a # only accessible from class scope of A end end Once again, there is no such thing as an attribute that is not a method in ruby, and there is no such thing as setting an *attribute* (= is a method also). You're trying to *re-implement* rubys mechanism in python in your example, but in pythons mechanism, all attributes already have built-in getter/setter. So the correct analogy is a variable that is accessible from within the classes scope only (A.__a), and then exposed to instances through an attribute (self.a). Your example leaves out a variable accessible only from within the scope of the class, and adds a new attribute accessible from the instance (_a). Either I'm not understanding you, or you're not understanding what A.__a means in python. A.__a is a class attribute, not an instance attribute - it's equivalent to @@a in ruby, not @a. If I understand what you're saying, a better python example to make your point might be: class A(object): def __init__(self): self.__a = foo # equivalent to @a self.a = self.__a # exposes self.__a Except that this only allows you to access '__a' via the exposed attribute 'a', not bind it to a new object. If you do: inst = A() inst.a = bar you don't modify inst.__a, unlike the following ruby code, which does modify @a . inst = A.new inst.a = bar -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Sat, 08 Dec 2007 11:23:57 -0800, MonkeeSage wrote: The equivalent python idiom is something like: class A: __a = foo def __init__(self): self.a = A.__a [...] Which roughly translates to this in ruby: class A attr_accessor :a def initialize @a = foo end end [...] Not really. In ruby an ivar is accessible within the class *only*, but not from without (like a mangled python class var), unless you declare an accessor (or write the accessor methods yourself). So my example is closer, and is not a WTF, if you know how ruby works. In your python example, the class attribute is mangled, but the instance attribute isn't, whereas your ruby code has no class attribute, and an instance attribute that isn't (directly) accessible outside the class. The equivalent in python would involve a mangled instance attribute, like: class A(object): def __init__(self): self.__a = foo def get_a(self): return self.__a def set_a(self, val): self.__a = val a = property(get_a, set_a) -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] minimalist web server
On Sat, 01 Dec 2007 19:02:41 -0800, Daniel Fetchinson wrote: The reason I need this is that my current best strategy to avoid ads in web pages is putting all ad server names into /etc/hosts and stick my local ip number next to them (127.0.0.1) so every ad request goes to my machine. I run apache which has an empty page for 404 errors so I'll In this case, do you need a webserver at all? If your browser tries to access a web server on 127.0.0.1 and there isn't one, won't the result, in most cases, be more or less the same as if the server returned a 404? -- http://mail.python.org/mailman/listinfo/python-list
Re: eof
On Wed, 21 Nov 2007 17:06:15 -0800, braver wrote: Why do I have to count sizes of lines read and compare it to some filesize or do other weird tricks just to see, in a way not changing my input stream, whether it's at the, well, EOF? Because you can't, generally, tell whether or not a stream is at the end of the file without reading from it; the C standard library doesn't guarantee that the EOF status is set until _after_ you've tried to read past the end of the file. I don't know, but I suspect that may be why python doesn't support querying files for EOF status - the fact that EOF can be false when you've read all the data in the file is a source of confusion to lots of C programmers. It looks like ruby internally buffers the stream itself, which is how come it can support this. According to the docs: Note that IO#eof? reads data to a input buffer. http://www.ruby-doc.org/core/classes/IO.html#M002309 I'd imagine that's inefficient in a lot of cases; and I don't think it provides much benefit. What's the hardship in checking the return values of your IO calls? Or iterating over the file, which is a more elegant solution in many cases. -- http://mail.python.org/mailman/listinfo/python-list
Re: find and remove \ character from string
On Sat, 15 Sep 2007 19:34:45 +0300, Konstantinos Pachopoulos wrote: Hi, i have the following string s and the following code, which doesn't successfully remove the \, but sucessfully removes the \\. There is no \\ in the string; there's one \ , which gets succesfully removed. s=Sad\\asd\asd When you write a string in the source code \\ gets changed to \ and \a gets changed to ASCII Bell (BEL) (that's what the docs say), which is a (non-printable) control code that is supposed to make the terminal beep. newS= for i in s: ... if i!=\\: Here, your test is true if i is not \ ... newS=newS+i ... newS 'Sadasd\x07sd' And here, you have a string containing no backslashes, but containing a character with ASCII code 7; it turns out that ASCII code 7 is the ASCII Bell, i.e., the character that you added to the string when you wrote '\a'. -- http://mail.python.org/mailman/listinfo/python-list
Re: Coming from Perl - SOLVED
On Thu, 13 Sep 2007 23:49:32 -0400, Amer Neely wrote: In trying to track down why this script would not run on my host, it has to come to light that Python is installed, however the Apache module is not. So, short story is - I was flogging a dead horse. Which Apache module? You don't need any special modules (just the regular CGI one) to use python in a CGI script. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE for Python
On Tue, 21 Aug 2007 21:23:25 -0300, Ricardo Aráoz wrote: Do you know if for in-house development a GPL license applies? (Qt4 and/or Eric4). (I'm not sure if I've understood your question right) If you distribute an app that _uses_ PyQT, you have to comply with the GPL (or buy a license from Trolltech), but note that this doesn't really have anything to do with Eric4. Running Eric4 doesn't require a license (either the GPL or Trolltech), and code you write using Eric4 doesn't have to be licensed according to the GPL either. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about a web server
On Mon, 20 Aug 2007 00:02:47 -0700, Frank Millman wrote: When responding to the POST data received, it sends a 301 response, no headers, and then the html page. [...] According to the notes, You don't have to know much about the HTTP protocol at all. Except some basic that when the client request something it is a GET, and when the client sends something it is in our case a POST. Some basic responce codes like 200 is OK for GET, and 404 is file not found, 301 is OK for a Post. [...] I googled for 'http response code 301', and found that it is actually a redirection code. It seems that the notes are misleading. [...] So I guess my questions are - 1. what is the correct response for a POST? I think the answer is 200. However, I assume the author is trying to demonstrate a particular technique. Can anyone explain what that may be. The code at that site looks wrong to me; I suspect the original author was confused about status codes. If you return a 301 redirect code, you should include a Location: header specifying the URI to redirect to, which that code doesn't do. Also, if you return a redirect code, you probably shouldn't include any page content (except perhaps a link to the redirected page). Note also that 301 is a permanent redirect, that is, it should be used when the URI has changed permanently (and might cause your browser to, e.g., update its bookmarks). You're probably not going to use it in normal operation. I'm not sure what the author was trying to do, but there is one quite common case where redirects are used with POST request. When the POST request does something that you are probably not going to want to repeat, but you want the resulting page to contain information that the user might want to refresh, it's common to have the POST return a 302 status (a temporary redirect). One example where this is useful is posting comments to a forum or blog. Usually, when the comment is posted, you want to return to the list of all the comments. But the user might refresh that list of comments, and you don't want their comment to be posted again when they refresh. So you would have the POST for the comment respond, not with a list of comments, but with a redirect _to_ the list of comments. -- http://mail.python.org/mailman/listinfo/python-list
Re: split on NO-BREAK SPACE
On Sun, 22 Jul 2007 21:13:02 +0200, Peter Kleiweg wrote: Here is another space: u'\uFEFF'.isspace() False isspace() is inconsistent Well, U+00A0 is in the category Separator, Space while U+FEFF is in the category Other, Format, so it doesn't seem unreasonable that one is treated as a space and the other isn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: CP4E revival
On Thu, 24 May 2007 20:03:29 +1000, Richard Jones wrote: Hoop-jumping implemented to prevent just this kind of direct linking (and thus not saving of the PDF to local disk to view, and thus increasing the load on the server). I'm not sure I see the connection - if you're serving something as application/pdf, then people are going to download it or view it directly as they see fit (or as their browser is configured), whether or not they got their by clicking a link or pressing two buttons (indeed, using the buttons makes it _harder_ to save the PDF to disk, if that's what you want to enforce, because users can't right-click/save-as; if their browser is set up to open PDFs directly, they can't change that behavior without reconfiguring their browser). -- http://mail.python.org/mailman/listinfo/python-list
Re: What makes an iterator an iterator?
On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote: I thought that an iterator was any object that follows the iterator protocol, that is, it has a next() method and an __iter__() method. ... class Parrot(object): ... def __init__(self): self.next = self._next() self.next isn't a method here, it's a generator. You could do: def __init__(self): self.next = self._next().next But, having tested, that doesn't appear to work either - I think this is because, again, self.next is not strictly a method, it's an attribute that happens to be callable. The python manual gives you a possible solution: ---QUOTE http://docs.python.org/lib/typeiter.html --- Python's generators provide a convenient way to implement the iterator protocol. If a container object's __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods. ---END QUOTE--- i.e., just rename your _next function to __iter__ . Your class won't itself be an iterator, but it will be usable in for statements and so one, and convertable to an iterator with the iter builtin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pep 3105: the end of print?
On Tue, 20 Feb 2007 10:46:31 -0800, Beliavsky wrote: I think the C and C++ committees also take backwards compatibility seriously, in part because they know that working programmers will ignore them if they break too much old code. While that's true, C++ compiler vendors, for example, take backwards compatibility significantly less seriously, it seems to me. A year or so ago, I tried compiling something I'd written for g++ 2, using a then-recent-ish g++ 3; it failed spectacularly. Likewise with Visual C++ 6 and a Visual C++ 2005. The suggestion that working programmers will reject python if a major version change introduces some backwards incompatibilities is not borne out by the experience of any other language I am aware of. -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On Mon, 11 Dec 2006 23:24:07 -0500, Ken Tilton wrote: Also, Python does not support a functional style of programming so the line is the only meaningful textual entity. In this sense the primitiveness of Python makes editing easier. Why do you say that? Wouldn't a block in python be a meaningful textual entity in the same way a lisp form would be? -- http://mail.python.org/mailman/listinfo/python-list
Re: merits of Lisp vs Python
On Sun, 10 Dec 2006 03:18:07 -0500, Bill Atkins wrote: We're not counting lines here, you goon. We're talking about how expressive constructs are and how closely they match your concept of what you want to do. The conditional example is lower-level; you're talking to the interpreter instead of saying what you want to achieve. You're having to repeat things because that's what the language asks of you, instead of describing in a higher-level way what you're actually doing. To be a little provocative, I wonder if the idea that you're talking to the interpreter doesn't apply more to lisp than to python; you can have any syntax you like, as long as it looks like an AST. One of the things I've always found off-putting about lisp as that all the syntax looks the same. In Algol-derived languages, each syntactic construct has a fairly distinctive appearance, so when, for instance, I encounter a for loop, I can quickly recognize that that's what it is, and bracket out the scaffolding and pick out the details that interest me. With lisp, I can't do that, I have to read through the sexp, decide on what syntax it is, and then remind myself where to look for the relevant specific details. Now, this might well be just due to my comparative lack of familiarity with lisp; I'd be interested to hear if you lisp people find different lisp constructs as visually distinctive as constructs in python (or other similar languages). But I think what people are getting at when they complain about all the brackets in lisp may actually be this issue of a visual distinction between different constructs (this is also a reason why having a limited number of syntactic constructs can be helpful - there are a probably a limited number of stereotypical layouts a programmer can keep in their mind at once). -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote: I agree -- the reversed() function appears to be an obvious case of purity overriding practicality :( str(reversed(some string)) 'reversed object at 0xb7edca4c' repr(reversed(some string)) 'reversed object at 0xb7edca4c' This doesn't seem particularly pure to me, either. I would have thought str(some_iter) should build a string out of the iterator, as list(some_iter) or dict(some_iter) do. I guess this might have to wait for Python 3, but str ought to be a proper string constructor, not a produce a printable representation of function, particularly when we have repr to do the latter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Replace Whole Object Through Object Method
On Mon, 26 Jun 2006 19:40:52 -0700, digitalorganics wrote: A misuse of inheritance eh? Inheritance, like other language features, is merely a tool. I happen to be using this tool to have my virtual persons change roles at different points in their lifetime, as many real people tend to do. Thus, at these points, B is indeed an A. What a person is, whether in real life or in my program, is not static and comes into definition uniquely for each moment (micro-moment, etc.) of existence. Now, please, I have no intention of carrying the conversation in such a silly direction, I wasn't inviting a discussion on philosophy or some such. I seek to work the tools to my needs, not the other way around. But thinking about the problem in the vocabulary provided by the programming language can be helpful in coming up with a solution. If inheritance tells you what an object _is_, and membership tells you what a role _has_, and a role is something that a person has, that suggests that an implementation where roles are members of a person might be simpler than trying to use inheritance. Like, for instance: class Role(object): def __init__(self, person): self.person = person class Worker(Role): def do_work(self): print self.name, is working class Employer(Role): def __init__(self, person): Role.__init__(self, person) self.employees = [] def add_employee(self, worker): self.employees.append(worker) def boss_people_around(self): for employee in employees: print self.name, is telling, employee.name, what to do class Person(object): def __init__(self, name): self.roles = [] self.name = name def add_role(self, role_class): self.roles.append(role_class(self)) def forward_to_role(self, attr): for role in self.roles: try: return getattr(role, attr) except AttributeError: pass raise AttributeError(attr) def __getattr__(self, attr): self.forward_to_role(attr) bill = Person('Bill') bill.add_role(Worker) bob = Person('Bob') bob.add_role(Employer) bill.work() bob.boss_people_around() -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Programmer Question
On Mon, 26 Jun 2006 10:47:58 -0700, [EMAIL PROTECTED] wrote: whats the difference between raw input and input? 'input' is used to ask the user to input a python expression, which is then run, and 'input' returns the result of executing that expression. For example: (define a function which prints something out) def func(): ... print You're calling a function ... return Function result ... (now, call input) res = input('Type python here: ') (python outputs the prompt ) Type python here: (and, if you type the python code to call a function after the prompt) Type python here: func() (then python calls the function, which prints out) You're calling a function (meanwhile, the result of calling the function gets assigned to 'res') print res Function result 'raw_input' just returns whatever text the user typed in. That's what you want to use here. 'raw_input' returns a string, which you'll need to convert to a number with the 'int' function, like so: text = raw_input('Type in a number: ') number = int(text) -- http://mail.python.org/mailman/listinfo/python-list
Re: printing out elements in list
On Mon, 08 May 2006 00:44:39 -0700, micklee74 wrote: i have a list with contents like this alist = ['QWER' , 'askfhs', 'REWR' ,'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' ] how can i convert this list into a dictionary such that dictionary = { 'QWER':'askfhs' , 'REWR' : 'sfsdf' , 'FGDG', 'sdfsdgffdgfdg' } This strikes me as a little bit voodish, but you could do: dictionary = dict(zip(alist[::2], alist[1::2])) -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
On Sat, 06 May 2006 23:05:59 -0700, Alex Martelli wrote: Tomasz Zielonka [EMAIL PROTECTED] wrote: ... higher level languages. There are useful programming techniques, like monadic programming, that are infeasible without anonymous functions. Anonymous functions really add some power to the language. Can you give me one example that would be feasible with anonymous functions, but is made infeasible by the need to give names to functions? In Python, specifically, extended with whatever fake syntax you favour for producing unnamed functions? Monads are one of those parts of functional programming I've never really got my head around, but as I understand them, they're a way of transforming what looks like a sequence of imperative programming statements that operate on a global state into a sequence of function calls that pass the state between them. So, what would be a statement in an imperative language is an anonymous function that gets added to the monad, and then, when the monad is run, these functions get executed. The point being, that you have a lot of small functions (one for each statement) which are likely not to be used anywhere else, so defining them as named functions would be a bit of a pain in the arse. Actually, defining them as unnamed functions via lambdas would be annoying too, although not as annoying as using named functions - what you really want is macros, so that what looks like a statement can be interpreted is a piece of code to be executed later. Here, for instance, is an article about using scheme (and, in particular, macros), to produce a fairly elegant monad implementation: http://okmij.org/ftp/Scheme/monad-in-Scheme.html -- http://mail.python.org/mailman/listinfo/python-list
Re: why _import__ only works from interactive interpreter?
On Sun, 07 May 2006 16:21:01 -0700, [EMAIL PROTECTED] wrote: So, if this is right, I need to put the .py file to be imported inside sys.path!! And the relative path will be usedto find the module. Can I __import__ providing the absolute path? import sys print sys.path ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gst-0.10', '/usr/lib/python2.4/site-packages/gtk-2.0', '/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode', '/usr/lib/site-python'] Compare with: [EMAIL PROTECTED]:~/src/tests$ cat test.py import sys print sys.path [EMAIL PROTECTED]:~/src/tests$ python test.py ['/home/tim/src/tests', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gst-0.10', '/usr/lib/python2.4/site-packages/gtk-2.0', '/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode', '/usr/lib/site-python'] Note that the first entry in sys.path when run from the interactive intepreter is a blank string, which doesn't appear in the output from the script - I assume that's what is allowing the interactive version to import via an absolute path. I'm not sure if this is the intended behavior or a bug. You could make your script work the same way as the interactive interpreter by doing: import sys sys.path.append('') mod = __import__('/your/absolute/path/module') But it might be better to just add the particular path: sys.path.append('/your/absolute/path') mod = __import__('module') -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
On Sat, 06 May 2006 21:19:58 -0400, Bill Atkins wrote: There are also cases where a function is so trivial that the simplest way to describe it is with its source code, where giving it a name and putting it at the beginning of a function is just distracting and time-consuming. E.g.: (remove-if (lambda (name) (find #\- name :test #'char=)) list-of-names) What's the sense of giving that function its own name? It's much clearer to simply write it in place. Yes, it's _possible_ to use named functions, but in this case its functionality is so simple that it's clearer to simply type it in place. Why is this expressiveness a bad thing, aside from its power to wreck an indentation-significant language? Well, you can do that with python's current, non-indentation-significance-wrecking, lambda syntax, so I don't think that's a particularly persuasive example. Note also that the only limitation python has on where you can define functions is that you can't define them inside expressions (they have to be statements), so you could define a named function right before the call to remove-if, which removes some of the advantage you get from the lambda (that is, the function definition is not very far from when it's used). Actually, I think the limitation on python that is operative here is not significant whitespace, but the distinction between statements and expressions. (crossposts trimmed) -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
On Fri, 05 May 2006 17:26:26 -0700, Xah Lee wrote: Regarding the lambda in Python situation... conceivably you are right that Python lambda is perhaps at best left as it is crippled, or even eliminated. However, this is what i want: I want Python literatures, and also in Wikipedia, to cease and desist stating that Python supports functional programing. (this is not necessarily a bad publicity) And, I What does lambda have to do with supporting or not supporting functional programming? -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
On Fri, 28 Apr 2006 14:27:00 -0700, nikie wrote: Steven Bethard wrote: L = ['C', 'A', 'D', 'B'] positions = dict((item, i) for i, item in enumerate(L)) Do you need the generator expression here? dict(enumerate(L)) should be equivalent, no? Isn't this bound to be less efficient? I mean, inserting the items into a dict is probably O(n log n), which is definitely worse than O(n) for searching the list twice. And, of course, it would yield different results if 'A' or 'D' are in the list more than once. Although presumably the dict method might be quicker if you were comparing the positions a large number of times. Incidentally, does python have a built-in to do a binary search on a sorted list? Obviously it's not too tricky to write one, but it would be nice if there was one implemented in C. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
On Fri, 28 Apr 2006 16:39:33 -0700, nikie wrote: I V wrote: Do you need the generator expression here? dict(enumerate(L)) should be equivalent, no? I think the generator is needed to swap the item and the index. dict(enumerate(L)) would yield a dict like {0:'C', 1:'A'...} Oh, of course, I wasn't paying attention. Incidentally, does python have a built-in to do a binary search on a sorted list? Obviously it's not too tricky to write one, but it would be nice if there was one implemented in C. I once read in an algorithm book that it took 10 years from the first binary search publication until a correct version was published, so, it actually is a bit tricky... Better stick to the bisect module. Don't know if it's written in C, though. Thanks for pointing out the bisect module - that's exactly what I was looking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing interfaces in Python...
[EMAIL PROTECTED] wrote: I see that Python is missing interfaces. The concept of an interface is a key to good programming design in Java, but I've read that they aren't really necessary in Python. I am wondering what technique I can use in Python to get the same benefits to a program design that I would get with interfaces in Java. To use interfaces in python, just what you would do in Java, except don't use interfaces. To expand on that slightly Zen answer, think about why you use interfaces in Java. The interface declaration tells the compiler that your object implements a specific set of functions, or that your function expects an object that implements these functions. Then, at run time, the actual type of the object is used to decide what function to call. However, python doesn't to any type checking at compile time, so it just uses the dynamic type of the object to decide what function to call. How would I approach this problem in Python? I think I would use an abstract class instead of an interface for IFixable, since Python supports multiple inheritance, but I'm not sure this is correct. Concretely: class Car: def fix(self): print Your car is ready, sir class Bus: def fix(self): print Your bus is ready, sir class Mechanic: def repair(self, customer, vehicle): vehicle.fix() customer.bill() class Customer: def bill(self): print Ouch, that was expensive me = Customer() my_bus = Bus() my_car = Car() m = Mechanic() m.repair(me, my_bus) m.repair(me, my_car) Which gives the output: Your bus is ready, sir Ouch, that was expensive Your car is ready, sir Ouch, that was expensive If you try and repair something that can't be fixed: m.repair(me, me) you get: Traceback (most recent call last): File test.py, line 30, in ? m.repair(me, me) File test.py, line 14, in repair vehicle.fix() AttributeError: Customer instance has no attribute 'fix' Obviously, you don't want this to happen when people use your program. Java would check this at compile time, but as python doesn't, you can write a unit test to check that the object's you want to implement the relevant functions really do. def is_fixable(obj): try: obj.fix except AttributeError: return False return True assert is_fixable(Car()) assert is_fixable(Bus()) assert not is_fixable(Customer()) assert not is_fixable(Mechanic()) -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing interfaces in Python...
Jonathan Daugherty wrote: Except when you need to handle exceptions when those methods don't exist. I think interfaces can definitely be useful. I think I see what you mean, but that's an odd way to put it. Typically, you aren't going to handle the exceptions produced by type errors. Of course, you want some way to test that your code doesn't have type errors. Static type checking is one way of doing the requisite testing, unit tests are another, but it's the tests that are useful, not the interfaces per se. Adding interfaces to python, which doesn't support static type checking, would be useless IMO. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing string from one file to another
Kun wrote: This works fine but instead of typing in a 'body', i would like the initial python program to just send a string as the body of the email. now normally i'd just set the msg in the mail.py file equal to the string, however, i do not know how to link a string from another python file to the mail.py file. Where does mail.py get the body from at the moment? And how are you invoking mail.py? The obvious would be to import mail.py and call a function in it; then, you would just need to change the string you pass to the function. But presumably that's not how you've got it set up or you wouldn't be asking the question. If you can explain a bit more how your program works that would be helpful, maybe post an exerpt of the code that shows where mail.py gets invoked from the main program, and the bit of mail.py that accesses the body that gets sent. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing string from one file to another
Kun wrote: mail currently gets the body from an input box. this is where mail.py gets invoked: OK, I'm a bit confused. Where is the initial python program in all this? You seem to have an one python program (mail.py) and an HTML form. As it stands, I don't see why you can't change mail.py so that it refers to your string instead of msg.as_string() . -- http://mail.python.org/mailman/listinfo/python-list
Re: recursion and linked lists
John Salerno wrote: The printable value of node1 is 1, node2 is 2 and node 3 is 3. node1.next is node2, node2.next is node3 and node3.next is None. This might be painfully obvious, but I don't understand when the print statement is getting called. If you call printBackward with node1, then you skip the if statement, head becomes node1, tail becomes node2 and then you call printBackward again with node2. During this call you call printBackward again with node 3 and then the next time the if statement returns. So when does the print happen, and how does it print 3 different values? It seems like you wouldn't get to it until the last time printBackward returns, and 'head' at that point would be 3, which Each time printBackward gets called, it has it's own separate 'head' variable. We could imagine they're all separate variables head1 for the first time printBackward is called, head2 for the second, and so on. The first time printBackwards gets called, it's local 'head' variable (head1) gets set to 1, and so on. is the first number printed. But doesn't it stop at this point? Where do 2 and 1 come from? Note that print gets called after _each_ time that printBackward returns. So, as the different calls to printBackward return, they print whatever 'head' was set to in that invocation. Now, logically enough, the last call to printBackward is the first to return, so the last value of 'head' is printed first, and so in in the reverse order of the list. Maybe this will help you visualize what is going on: call printBackward with arg [1, 2, 3] head1 = 1 call printBackward with arg [2, 3] head2 = 2 call printBackward with arg [3] head3 = 3 call printBackward with arg None return print head3 ( == 3) return print head2 (== 2) return print head1 (== 1) return -- http://mail.python.org/mailman/listinfo/python-list
Re: instance and class-hierarchy ?
Bror Johansson wrote: Is there a good and general way to test an instance-object obj for having a class belonging to a certain sub-tree of the hierarchy with a common parent class C? If I understand you correctly, isinstance ought to do the job: class A(object): pass class B(A): pass class C(B): pass c = C() assert isinstance(c, C) assert isinstance(c, B) assert isinstance(c, A) However, I'm not sure it's great style to have to inquire about the type of an object, as I would worry it would be fragile if you redesign your class hierarchy. Maybe an alternative would be to add a method to your 'C' class to accomplish whatever it is you need to do? Still, if that doesn't work (sometimes algorithms just are tightly coupled to the specific class hierarchy, and you can't avoid it), isinstance should work. -- http://mail.python.org/mailman/listinfo/python-list
Re: No Cookie: how to implement session?
Sullivan WxPyQtKinter wrote: As you said, There is no solution? I mean, tracing a real session without using tricks like hidden field and cookies in CGI script? As people have said, this isn't a limitation of python, it's a feature of HTTP. You might want to consider whether you actually need sessions - see if you can design your application to use REST (see e.g. http://www.xfront.com/REST-Web-Services.html , or there's lots of information on Google). People have also mentioned this in passing, but third alternative to cookies and hidden fields is to use a session key in the query string - this can be used for GET requests, so would work in redirects as well as form submissions. Try: http://yoursite.example/page?session=key Then you need to remember, whenever you include a link to your site that should retain the session information to add the session key to the URL. You could define a function: def session_url(url, key, **params={}): qstring = %s=%s % ('session', urllib.quote(key)) for (name, value) in params.items(): qstring += %s=%s %(urllib.quote(name), urllib.quote(value)) return qstring And use it like: #Do redirect print Location: + session_url('new_page', session_key) Or: # Redirect to a page that loads the item called 'anitem' print Location: + session_url('new_page', session_key, {'item', 'anitem'}) If you want to link to this URL in an HTML page, you need to remember to escape the '' character: print a href='%s'Edit item %s/a % (cgi.escape(session_url('edit', session_key, {'item', item_name})), item_name) Then, if you need to submit a form, you can add the key as a hidden field. -- http://mail.python.org/mailman/listinfo/python-list
Re: CGI redirection: let us discuss it further
Sullivan WxPyQtKinter wrote: 1. Are there any method (in python of course) to redirect to a web page without causing a Back button trap(ie, when user click the back button on their web browser, they are redirect to their current page, while their hope is probably to go back to the last page they have seen, rather than the redirection page with a Location: url head and blank content.)? I guess this may vary from browser to browser, but on Mozilla at least, if your CGI script returns one of the 300 status codes, then the redirect page doesn't get added to the browser history, and so the back button works as expected. 2. Are there any method to use relative path, rather than full absolute URI path in Location: url? It is very essential for later transplant work, e.g.,transplant a folder of cgi scripts from one web server to another, with different URL. You don't have to use absolute URLs in a Location: header returned by a CGI script. The web server will handle relative URLs for you. See the CGI spec: http://hoohoo.ncsa.uiuc.edu/cgi/out.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't get the real contents form page in internet as the tag no-chche
dongdong wrote: using web browser can get page's content formally, but when use urllib2.open(http://tech.163.com/2004w11/12732/2004w11_1100059465339.html;).read() the result is htmlheadMETA HTTP-EQUIV=REFRESH CONTENT=0;URL=http://tech.163.com/04/1110/12/14QUR2BR0009159H.html; This line here instructs the browser to go to http://tech.163.com/04/1110/12/14QUR2BR0009159H.html . If you try loading that with urllib2, do you get the right content? If the people behind that web page new how to use the web, they wouldn't use the META HTTP-EQUIV hack, and instead would have instructed their web server to return a 300 redirect response, which would have allowed urllib2 to follow the redirect and get the right content automatically. If you have any influence with them, you could try and persuade them to set up their web server properly. -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the general way of separating classes?
John Salerno wrote: How does the __init__ file help if you are still individually importing class1 and class2 in each other module of your program? Felipe's example is a little confusing because he uses the same name for the module and the class. Here's another example: --- package/class1.py --- class C1: pass --- package/class2.py --- class C2: pass --- package/__init__.py --- from class1 import C1 from class2 import C2 --- end --- Now, in your code you can do: import package c = package.C1() If you hadn't included the lines in __init__.py, you would have to write: import package c = package.class1.C1() -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 354: Enumerations in Python
Paul Rubin wrote: Hmm, I also see the PEP doesn't specify what's supposed to happen with Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat') Solar_system = enum('sun', 'mercury', 'venus', 'earth',) # etc. print Weekdays.sun == Solar_system.sun so that's another shortcoming with the PEP. I think it does, doesn't it? From the PEP: Values within an enumeration cannot be meaningfully compared *except with values from the same enumeration*. The comparison operation functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a value from an enumeration is compared against any value not from the same enumeration or of a different type. (my emphasis) -- http://mail.python.org/mailman/listinfo/python-list
Re: ls files -- list packer
kpp9c wrote: Namely i have organized a bunch of folders that have soundfiles in them and would like Python to slurp up all the .aif/.aiff (or .wav whatever) files in a given set of directories. My friend hacked up this is perl: $files = `ls /snd/Public/*.aiff`; You could use posix.popen to duplicate the perl hack: files = posix.popen('ls /snd/Public/*.aiff').read().strip() @snd_filelist = split('\n',$files); snd_filelist = files.split('\n') I would like something similar, that works with python that is more elegant and maybe even more robust. Lucklily, python lets you avoid this kind of horrible hack. Try os.listdir: snd_filelist = [f for f in os.listdir('/snd/Public/') if f.endswith('.aiff')] I think it's more elegant, and it's certainly more robust. but i am failing miserably and my perl friends mock me. Now you get to mock your perl friends! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to *Search* with google from inside my programme and get the search result?
Frank Potter wrote: Does google supply some webservice to programmers? I did see Googling for google api gets you to: http://www.google.com/apis/ It appears to be a SOAP API, which you can access with python, but I think you'll need a third-party library. Googling for python soap gets you: http://www-128.ibm.com/developerworks/library/ws-pyth5/ which might be a place to start. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Nicola Musatti wrote: I don't think this is all there is to it. Even though a class such as Image might not have a sensible default, initial state it still might not be reasonable to burden it with the ability to collect the information needed to reach such an initial state. To put it it another way: a car is a car, it isn't a car factory. What's the burden, though? Surely the only burden is that the class needs to take the relevant parameters to its __init__ method, which is no more of a burden than providing some other initialization method that takes the relevant parameters. Factory functions (or classes) are there to solve this problem and still allow a clean separation of concerns. Although instances of Klass are created uninitialized, they only live in this state within their factory and only reach trhe outside world only when they are in a usable state. This may be my limited imagination, but I can't think of a situation when you would prefer something like: def factory(info): k = Klass() data = get_initial_data(info) k.set_data(data) return k to: def factory(info): data = get_initial_data(info) return Klass(data) What would be the value of doing the initialization in a separate method, rather than the constructor? -- http://mail.python.org/mailman/listinfo/python-list
Re: A simple question string.replace
Haibao Tang wrote: Is it possible to substitue all '1.1' to some value else without using re. You could try: import sys values = sys.stdin.readline().split() while values: results = [] for value in values: if value != '1.1': results.append(value) else: results.append('something else') print '\t'.join(results) values = sys.stdin.readline().split() -- http://mail.python.org/mailman/listinfo/python-list
Re: Making dir's
Klaus Alexander Seistrup wrote: Or os.makedirs(): Although that may or may not do what the OP wants. I was assuming she was trying to produce a directory structure like: /dir/C/ /dir/ASM/ /dir/Python/ os.makedirs() produces a directory hierarchy, like: /dir/C/ASM/Python/ -- http://mail.python.org/mailman/listinfo/python-list