Re: lacking follow-through
On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: This is the strangest post I've seen since I've joined this list (only recently). What the ? Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a bot!? :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Wed, 03 Sep 2008 01:23:47 -0400, Derek Martin wrote: On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: The subprocess module is also supposed to replace os.system and os.spawn*, neither of which involve opening pipes. Uh... it's a replacement for os.popen(), which -- guess what -- opens pipes. From the documentation: subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* If it weren't called `Popen` but `Spawn` instead I guess you would argue that it *must* be `Spawn` because it spawns processes and even it is not using `spawn*()` under the hood it uses the concept of spawn with some extras. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: And if they model an action there must be some way to activate the action That's a reasonable assumption, but as I also said, the object might just describe the action -- essentially the equivalent of a struct in C. ``struct``\s in C describe *actions*!? Functions do this. And a class that describes an action that is executed in the `__init__()` method is conceptually a function and shouldn't be a class. There must be a better name for the thing it returns. Again guideline, not law, but a very strong guideline IMHO. but the instances of `Popen` are no actions. There's no way to execute a `Popen` instance. Yes there is... you execute it when you instantiate the object. But then the instance itself isn't an action but the result of one. At the time of instantiation, you open the P (pipes). For an object which describes an action, I think it's perfectly sensible that instantiation is when the action occurs, […] Here I disagree again. Because the type/class name of an instance should be a name of the thing/concept of the instance, not the action used to create it. Yet some of you state your case as if it is incontrovertable fact. I've given a good case as to why it IS a good name (one which I genuinely support), and disagree as you may, none of the points any of you have made invalidate or even weaken my argument. Maybe from your POV. Facts: It doesn't use the `popen()` function So? Neither does the C version of popen(), but that function is still called popen()! Now you lost me. The C version of `popen()` isn't recursive, why on earth should it be, so what's that statement supposed to mean!? to three file objects, more attributes and methods), the function used on Windows under the hood is called `CreateProcess()` not `CreatePipe()`. How does Windows implement popen()? [I think they call it _popen() though...] Doesn't matter because the `Popen()` implementation doesn't use `popen()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Wed, 03 Sep 2008 03:09:18 -0400, Derek Martin wrote: On Wed, Sep 03, 2008 at 06:40:10AM +, Marc 'BlackJack' Rintsch wrote: On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: And if they model an action there must be some way to activate the action That's a reasonable assumption, but as I also said, the object might just describe the action -- essentially the equivalent of a struct in C. ``struct``\s in C describe *actions*!? Functions do this. struct run { int speed; direction_type direction; }; Guess what, I don't like the name because it doesn't describe an action but a state of, e.g. a `Runner`. :-) but the instances of `Popen` are no actions. There's no way to execute a `Popen` instance. Yes there is... you execute it when you instantiate the object. But then the instance itself isn't an action but the result of one. So? A class doesn't represent an action, remember? It represents a thing. Isn't that what you said? Yes and that's why the type name should not describe the action but the the thing that results from it. IMHO. But I said that already. Maybe from your POV. Facts: It doesn't use the `popen()` function So? Neither does the C version of popen(), but that function is still called popen()! Now you lost me. The C version of `popen()` isn't recursive, why on earth should it be, so what's that statement supposed to mean!? Sorry, did I go too fast for you? Your facts seem to be suggesting that for Python's Popen class to be named Popen, it should use the C popen() function. So you imply that I think any function should only have a name of a function it uses under the hood!? I still don't get that sentence. Sorry, but you are contradicting yourself (repeatedly), and your arguments don't make any sense. I don't contradict myself. Either you are playing silly naming games with `popen()` on different levels (concept, Popen, popen() (Python), popen() (C)) or you just don't *want* to understand my arguments. I understand your arguments why you think `Popen` is a proper name, but don't share them. It's okay for me if you don't like my arguments against it and for something like `Process`, but telling me they don't make any sense and patronizing me doesn't make your arguments more convincing. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Tue, 02 Sep 2008 05:02:07 -0700, Nicola Musatti wrote: On Sep 1, 9:23 am, Jeremy Banks [EMAIL PROTECTED] wrote: Hi. I wondered if anyone knew the rationale behind the naming of the Popen class in the subprocess module. Popen sounds like the a suitable name for a function that created a subprocess, but the object itself is a subprocess, not a popen. It seems that it would be more accurate to just name the class Subprocess, can anyone explain why this is not the case? The Python class is a generalization of the standard Posix function of (almost) the same name: http://opengroup.org/onlinepubs/007908775/xsh/popen.html So it's a name of a *function* and it's a little bit unsuitable for a *class*. As Jeremy wrote: the instances represent *processes* not popens, whatever that may be. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: What is module initialization?
On Tue, 02 Sep 2008 14:32:30 +0100, dudeja.rajat wrote: I found on the net that there is something called module initialization. Unfortunately, there is not much information for this. However, small the information I found module initialization can be of use to me in my project. Module initialization is what happens when you import a module the first time. In pure Python modules the module level code is executed and in extension modules a special initializing function may be called. However, there is one case when a module updates one such global variable but the variable is not getting updated in the module containing global symbols ( variables). Sounds unlikely if you *really* update the attribute of the module and not just rebind a local name that was bound to the object in the global module before. Example: from spam import egg egg = 42 # This does *not* change `spam.egg` but just the local binding! Could some one provide me a sample code of module intialization? And how can I ensure that module initialization is done only once? Module initialization is only done once, there's nothing to ensure. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: what's the difference between f(a) and f(*a)
On Tue, 02 Sep 2008 06:24:21 -0700, qxyuestc wrote: showed above: the result from sum1() and sum2() is the same. So, what is the difference between f(a) and f(*a) f(a) - f([1, 2, 3]) f(*a) - f(1, 2, 3) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Tue, 02 Sep 2008 09:28:42 -0400, Derek Martin wrote: On Tue, Sep 02, 2008 at 12:27:49PM +, Marc 'BlackJack' Rintsch wrote: The Python class is a generalization of the standard Posix function of (almost) the same name: http://opengroup.org/onlinepubs/007908775/xsh/popen.html So it's a name of a *function* and it's a little bit unsuitable for a *class*. As Jeremy wrote: the instances represent *processes* not popens, whatever that may be. I would argue that they don't represent processes at all; the object is a set of files which connect the standard I/O streams of a subprocess to its parent, and methods to operate on those files. And the process' ID, an attribute with the process' return code, a method to wait until the process is finished and file objects to communicate with the process. The C library's popen() function, on which this class is based, provides a means to open a file and connect it to the standard steams of a subprocess, making it more closely analogous to what the Popen class does/provides. As such, Popen is a better name to describe this object than subprocess would be. Is strongly disagree. The class provides an interface to start and communicate with a `Subprocess`. Instances stand for processes. With your reasoning the `file` type should be called `open`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: converting a sed / grep / awk / . . . bash pipe line into python
On Tue, 02 Sep 2008 10:36:50 -0700, hofer wrote: sed 's/\.\..*//' \### remove '//' comments | sed 's/#.*//' Comment does not match the code. Or vice versa. :-) Untested: from __future__ import with_statement from itertools import ifilter, ifilterfalse, imap def is_junk(line): line = line.rstrip() return not line or line.startswith('//') or line.startswith('#') def extract_numbers(line): result = map(int, line.split()[:2]) assert len(result) == 2 return result def main(): with open('test.txt') as lines: clean_lines = ifilterfalse(is_junk, lines) pairs = imap(extract_numbers, clean_lines) print '\n'.join(b for a, b in pairs if a + b == 42) if __name__ == '__main__': main() Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Tue, 02 Sep 2008 11:39:09 -0400, Derek Martin wrote: On Tue, Sep 02, 2008 at 01:57:26PM +, Marc 'BlackJack' Rintsch wrote: I would argue that they don't represent processes at all; the object is a set of files which connect the standard I/O streams of a subprocess to its parent, and methods to operate on those files. And the process' ID, an attribute with the process' return code, a method to wait until the process is finished and file objects to communicate with the process. The name popen is an abbreviation of pipe open -- the function, and the class, open pipes to communicate with another process. What you said is correct; however there are numerous other ways to open subprocesses. The focus of popen is the communication aspect -- the opening and control of the pipes -- not the subprocess. That's the key difference between popen() and all the other methods of starting a subprocess. But I'm not talking about the `popen()` function but the `subprocess.Popen` class. The C library's popen() function, on which this class is based, provides a means to open a file and connect it to the standard steams of a subprocess, making it more closely analogous to what the Popen class does/provides. As such, Popen is a better name to describe this object than subprocess would be. Is strongly disagree. The class provides an interface to start and communicate with a `Subprocess`. Instances stand for processes. There's more than one way to look at it. You can disagree all you like, but your interpretation disagrees with the historical intent of popen. That's why I think the name `Popen` is not so good for it. Because it does more than `popen()` and if it is called `Subprocess` or just `Process` then it would be merely an implementation detail, that the `popen()` function is called at some point. If it is at all, because `popen()` on C level can just open a pipe in *one* direction. Note that in all of these links that talk about popen, the focus is on opening pipes or file objects, not on subprocesses: http://www.opengroup.org/onlinepubs/009695399/functions/popen.html http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen http://docs.hp.com/en/B9106-90010/popen.3S.html http://www.faqs.org/docs/artu/ch07s02.html And all of the links talk about the `popen()` function, not about the functionality the `Popen` class provides. Which is much more than that simple pipe `popen()` returns. The Linux man page unfortunately copies (verbatim) the FreeBSD man page, which gets it wrong. You can not open a process, but you can definitely open a pipe. Ah, when their terminology doesn't match yours, they must get it wrong. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy/Scipy set field of matrix?
On Tue, 02 Sep 2008 13:27:06 -0700, cnb wrote: m matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) how do I set the field 1,2 (=6) to 45 for example? and how do I initialize a matrix and then add values in a for-loop? Im using PIL and want to store all the pixels of an image in a matrix. But I can't find the appropriate operations. Work through the tutorial in the Python documentation and read some introduction to Numpy. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Inquiry regarding the name of subprocess.Popen class
On Tue, 02 Sep 2008 18:15:07 -0400, Derek Martin wrote: Classes represent things, and class names should be nouns. Is that a law? It's a common guideline. Classes are instantiated by invoking their class names as a function call -- the computing equivalent of a verb. Why then, must they be named as nouns? Can you not, in fact, have classes which describe (or model) actions? Wouldn't you name them using verbs if you did? Me personally no. I would use `FooAction` instead of `Foo` or something similar. And if they model an action there must be some way to activate the action but the instances of `Popen` are no actions. There's no way to execute a `Popen` instance. That said, this is the most valid point anyone has made... You should have made it when the module was being designed. :-D My point is, if you don't think Popen is a good name for the class, that's your opinion, but it is only that: an opinion. Like your opinion that it *is* a good name. Yet some of you state your case as if it is incontrovertable fact. I've given a good case as to why it IS a good name (one which I genuinely support), and disagree as you may, none of the points any of you have made invalidate or even weaken my argument. Maybe from your POV. Facts: It doesn't use the `popen()` function, it gives something more complex than a simple pipe (no obligatory shell, up to three file objects, more attributes and methods), the function used on Windows under the hood is called `CreateProcess()` not `CreatePipe()`. `Popen` creates a process and represents a proxy object to communicate with it, so `Process` is a good name for that concept/thing. It's a way more self explaining name, even for people who know the `popen()` function because there's a concept called process but none called popen. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Know if a object member is a method
On Mon, 01 Sep 2008 11:45:36 +0200, Luca wrote: But not so easy to fool a type check: type(x) == new.function False Of course that's not bullet-proof either. I leave it as an exercise to discover how you might break that piece of code. Ok, so... What is the best way to do this? The most pythonic? The most pythonic might be not checking at all but simply *call* the object and deal with possible failures. What's your use case? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0b2 cannot map '\u12b'
On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: I doubt the OP 'chose' cp437. Why does Python using cp437 even when the default encoding is utf-8? On WinXP sys.getdefaultencoding() 'utf-8' s='\u012b' s Traceback (most recent call last): File stdin, line 1, in module File C:\Program Files\Python30\lib\io.py, line 1428, in write b = encoder.encode(s) File C:\Program Files\Python30\lib\encodings\cp437.py, line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in position 1: character maps to undefined Most likely because Python figured out that the terminal expects cp437. What does `sys.stdout.encoding` say? To put it another way, how can one 'choose' utf-8 for display to screen? If the terminal expects cp437 then displaying utf-8 might give some problems. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3.0b2 cannot map '\u12b'
On Mon, 01 Sep 2008 14:25:01 -0400, Terry Reedy wrote: Marc 'BlackJack' Rintsch wrote: On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: Most likely because Python figured out that the terminal expects cp437. What does `sys.stdout.encoding` say? The interpreter in the command prompt window says CP437. The IDLE Window says 'cp1252', and it handles the character fine. Given that Windows OS can handle the character, why is Python/Command Prompt limiting output? The windows command prompt expects cp437 because that's what old DOS programs print to it. Characters the IDLE window cannot display (like surrogate pairs) it displays as boxes. But if I cut '[][]' (4 chars) and paste into Firefox, I get 3 chars. '[]' where [] has some digits instead of being empty. It is really confusing when every window on 'unicode-based' Windows handles a different subset. That's because it is not 'unicode-based'. Communication between those programs has to be done with bytes, so the sender has to encode unicode characters in the encoding the receiver expects. Is this the fault of Windows or of Python and IDLE (those two being more limited that FireFox)? It's nobodies fault. That's simply how the encoding stuff works. To put it another way, how can one 'choose' utf-8 for display to screen? If the terminal expects cp437 then displaying utf-8 might give some problems. My screen displays whatever Windows tells the graphics card to tell the screen to display. But the terminal gets bytes and expects them to be cp437 encoded characters and not utf-8. So you can't send whatever unicode character you want, at least not without changing the encoding of the terminal. In OpenOffice, I can select a unicode font that displays at least everything in the BasicMultilingualPlane (BMP). But OOo works with unicode internally, so there's no communication with outside programs involved here. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Lining Up and PaddingTwo Similar Lists
On Fri, 29 Aug 2008 09:40:32 -0700, W. eWatson wrote: Actually, I'm getting the file names from listdir, and they appear to be sorted low to high. I tried it on a folder with lots of dissimilar files. But that's not guaranteed. It depends on the operating system and file system driver if the names are sorted or not. In [14]: os.listdir? Type: builtin_function_or_method Base Class: type 'builtin_function_or_method' String Form:built-in function listdir Namespace: Interactive Docstring: listdir(path) - list_of_strings Return a list containing the names of the entries in the directory. path: path of directory to list The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with list.insert
On Thu, 28 Aug 2008 09:13:00 -0700, SUBHABRATA wrote: import re def wordchecker1(n): # INPUTTING STRING a1=raw_input(PRINT ONE ENGLISH SENTENCE FOR DICTIONARY CHECK:) #CONVERTING TO LOWER CASE a2=a1.lower() #CONVERTING INTO LIST a3=a2.split() #DICTIONARY a4=open(/python25/Changedict3.txt,r) a5=a4.read() a6=a5.split() found=[] not_found=[] #SEARCHING DICTIONARY for x in a3: a7=\n a8=a7+x if a8 in a5: a9=a5.index(a8) a10=a5[a9:] a11=re.search(\xe0.*?\n,a10) a12=a11.group() a13=a12[:-1] found.append(a13) elif a8 not in a5: a14=x not_found.append(a14) else: print Error found.extend(not_found) # THE OUTPUT print OUTPUT STRING IS a15=(' '.join(found)) #THE OUTPUT STRING print a15 # SPLITTING OUTPUT STRING IN WORDS a16=a15.split() #TAKING OUT THE WORD FROM OUTPUT STRING for word in a16: #MATCHING WITH GIVEN STRING a17=a2.find(word) if a17-1: print The word is found in the Source String a18=a3.index(word) a19=a3[a18] print a19 #INSERTING IN THE LIST OF TARGET STRING a20=a16.insert(a18,a19) print a16 a21=( .join(a16)) print a21 a1, a2, a2, …, a20? You must be kidding. Please stop numbering names and use *meaningful* names instead! Could you describe them problem better, with sample inputs and expected outputs. There must be a better way that that unreadable mess above. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: cannot find object instance
On Thu, 28 Aug 2008 08:35:07 -0700, jimgardener wrote: moduleA.py import moduleB […] moduleB.py -- import moduleA […] Don't do that. Circular imports are a code smell. If two modules are coupled that tight it's usually a sign that you want just one module or factoring out something into a third module that is imported by both old modules. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: file data to list
On Thu, 28 Aug 2008 12:11:39 -0700, Anish Chapagain wrote: I am facing problem for extracting file data to the list so as to have graph plotted through list. my file(eg: data.txt) is having data like this, cnt0001a 29000 xretya 01 cnt0002a 29850 brishal 02 cnt0003a 31250 kristal 03 from here, I need to copy data 29000, 29850, 31250 into a single list and 01, 02, 03 to another so as to plot graph using these value. Then work through the tutorial in the documentation, pay attention to strings, lists, files, and their methods. The try to implement it and come back with some source code and specific questions. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: [Q] How to ignore the first line of the text read from a file
On Thu, 28 Aug 2008 10:16:45 -0700, norseman wrote: Benjamin Kaplan wrote: On Thu, Aug 28, 2008 at 12:11 AM, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello, I am new to Python and have one simple question to which I cannot find a satisfactory solution. I want to read text line-by-line from a text file, but want to ignore only the first line. I know how to do it in Java (Java has been my primary language for the last couple of years) and following is what I have in Python, but I don't like it and want to learn the better way of doing it. file = open(fileName, 'r') lineNumber = 0 for line in file: if lineNumber == 0: lineNumber = lineNumber + 1 else: lineNumber = lineNumber + 1 print line Can anyone show me the better of doing this kind of task? Thanks in advance. -- Files are iterators, and iterators can only go through the object once. Just call next() before going in the for loop. Also, don't use file as a variable name. It covers up the built-in type. afile = open(file_name, 'r') afile.next() #just reads the first line and doesn't do anything with it for line in afile : print line http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list == actually: import os file = open(filename, 'r') for line in file: dummy=line for line in file: print line is cleaner and faster. That's not cleaner, that's a 'WTF?'! A ``for`` line over `file` that does *not* iterate over the file but is just there to skip the first line and a completely useless `dummy` name. That's seriously ugly and confusing. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting references to obect instances into a list
On Wed, 27 Aug 2008 08:32:52 -0700, [EMAIL PROTECTED] wrote: Thanks for your reply Simon. I will read the article you told me to but first, please, have a look at this snippet: Please read the article! m = [2,3,4] p = ['a','b','c'] q = [m,p] q [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] del p q [[2, 3, 4, 'a', 'b', 'c'], ['a', 'b', 'c']] How come q is not updated after I deleted p? Because neither the name `q` nor the list object bound to it has anything to do with the name `p`. ``del`` does not delete objects but *names*. Objects exist as long as there is a reference to them. You deleted the name `p` and thus one reference to the list with the three characters but there's still the reference from the list bound to `q` to that three character list. What did you expect for an updated q anyway? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: generate methods at runtime, but the wrong one gets called
On Mon, 25 Aug 2008 12:52:44 +0200, Maric Michaud wrote: In other OOP language I would encourage you to implement this logic in some sort of singleton, but in python we don't like this construct, module level variables and function do perfectly the job, simple as they are. Modules are some sort of singletons in Python. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Struct class random access
On Mon, 25 Aug 2008 13:03:09 -0700, castironpi wrote: struct.Struct lets you encode Python objects into structured memory. It accepts a format string, and optionally a buffer and offset to/from which to read/write the structure. What do you think of random access for the results? (unproduced) packer= struct.Struct( 'IIIf255p' ) packer.pack_into( buf, off, 10, 20, 30, 0.5, 'abc' ) packer.unpack_from( buf, off, 2 ) #reads field 2 30 I don't like it for the same reason I don't like index access on tuples or lists that represent a record -- the numbers are quite meaningless. Names for the components result in much easier to understand source code, so I would prefer to use `ctypes` or `construct` to create such a record. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Private attribute
On Mon, 25 Aug 2008 21:44:49 +0100, Ken Starks wrote: def __getattr__(self,attrname): if attrname == 'gridsize': return 0.8 def __setattr__(self,attrname,value): if attrname == 'gridsize': pass else: self.__dict__[attrname]=value […] I admit I haven't used properties, and had to look them up. Pretty cool indeed ! But an extra unnecessary level of complexity for my needs here, I feel. Compare this with your approach above and point out the extra complexity please: @property def gridsize(self): return 0.8 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: why in returns values for array and keys for dictionary
On Mon, 25 Aug 2008 19:57:06 -0700, alex23 wrote: On Aug 26, 10:49 am, ++imanshu [EMAIL PROTECTED] wrote: Wouldn't it be nicer to have 'in' return values (or keys) for both arrays and dictionaries. Arrays and Dictionaries looked so similar in Python until I learned this difference. […] In both cases, 'in' returns a boolean indicating the existence of an item in the list, or a key in the dict. I'm not sure why you'd need it to return the item you're checking for the existence of, as you'd have to have that item before you could do the check. Have I missed what you're asking for here? Could you provide a pseudocode example to demonstrate what you mean? The OP isn't talking about the ``in`` operator but ``in`` as part of ``for … in …``. So it's actually the question why ``list(a_dict)`` doesn't return a list of values but a list of keys. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Struct class random access
On Mon, 25 Aug 2008 14:49:14 -0700, castironpi wrote: I'm interested in the speed benefit, so you don't have to reconstruct the entire 'record' just to read/write one 'field'. How in ctypes? Only the field accessed is converted. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8: Byte Order Mark (BOM) vs coding cookie
On Sun, 24 Aug 2008 07:28:53 -0700, twyk wrote: So is it good style to omit the BOM in UTF-8 for Python 3.0? I'd say yes because it is unnecessary with UTF-8 and it messes up the she- bang line of scripts. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to search the Python manuals
On Sat, 23 Aug 2008 21:00:57 +, JBW wrote: It is much easier to find where to look if the documentation corpus has a proper index. Since indexing is hard work that's effectively impossible to automate, I suspect Python's documentation is no better than many other open-source software projects. I think the indexes of the documentation are quite good: http://docs.python.org/lib/genindex.html http://docs.python.org/ref/genindex.html First occurance of default in the reference index leads to the information about default parameters and that they are executed once, when the ``def`` statement is executed: http://docs.python.org/ref/function.html#l2h-634 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: dropwhile question
On Sat, 23 Aug 2008 14:54:09 -0700, Rajanikanth Jammalamadaka wrote: list(itertools.dropwhile(lambda x: x5,range(10))) [5, 6, 7, 8, 9] Why doesn't this work? list(itertools.dropwhile(lambda x: 2x5,range(10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] It *does* work. `dropwhile()` drops as long as the callable returns a true value and then it stops dropping. First value is 0 and ``2 0 5`` is `False` so nothing is dropped. What have you expected? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: exception handling in complex Python programs
On Tue, 19 Aug 2008 22:24:45 -0700, eliben wrote: You want to look up Easier to Ask Forgivness than Permission (EAFP) which is touted as the canonical error-handling paradigm for Python. Any (semi)complete guides on this canonical paradigm online ? I've only found some references in maillist discussions. There's the glossary in the documentation: http://docs.python.org/tut/node18.html Look under 'duck-typing', 'EAFP', and 'LBYL'. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: exception handling in complex Python programs
On Wed, 20 Aug 2008 18:37:02 +0200, Bruno Desthuilliers wrote: I personally think this is sloppy because you have to couple the exception type with the function --- between file() and open() in Python 2 and 3, a NameError is thrown with open() in Python 3 ??? I suspect this has nothing to do with any error happening while opening the file. NameError means the name doesn't exists in the current namespace nor it's enclosing namespaces. Could it be possible that open() has been removed from Py3k ? No it's moved/changed but there's still a name for it in the builtin namespace. `file` on the other hand is gone: Python 3.0b2 (r30b2:65080, Aug 20 2008, 20:41:17) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type help, copyright, credits or license for more information. open class 'io.OpenWrapper' file Traceback (most recent call last): File stdin, line 1, in module NameError: name 'file' is not defined Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Get parameters from the URL
On Thu, 21 Aug 2008 10:04:35 +0530, Sohrab Pawar wrote: I'm a python noob so don't be mean :) I have a URL like http://mySite.net?userID=398age=28 I'm trying to create a new python script that is called when a user click a button Redirect. When a user clicks the Redirect button, I want to send the user to either of the 2 pages, depending on the age of the user (sent as a parameter using the URL). What is the best way to 1. Read the URL and get the parameters (age=28 in this case) 2. Redirect the the user accordingly I have done this kind of thing in a jsp/servlet environment but I have no idea how to proceed in the Python world. If you really got that string you can use the modules `urlparse` and `cgi` to get the query part: In [48]: url = 'http://mySite.net?userID=398age=28' In [49]: urlparse.urlparse(url) Out[49]: ('http', 'mySite.net', '', '', 'userID=398age=28', '') In [50]: cgi.parse_qs(urlparse.urlparse(url)[4]) Out[50]: {'age': ['28'], 'userID': ['398']} But maybe you should read about the `cgi` module and how to use it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: python custom command interpreter?
On Wed, 20 Aug 2008 18:46:42 -0400, Derek Martin wrote: How so? What could be easier than rm -rf directory? C:\rm -rf directory Illegal command: rm. Hm. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Good python equivalent to C goto
On Sat, 16 Aug 2008 23:20:52 +0200, Kurien Mathew wrote: Any suggestions on a good python equivalent for the following C code: while (loopCondition) { if (condition1) goto next; if (condition2) goto next; if (condition3) goto next; stmt1; stmt2; next: stmt3; stmt4; } (Don't) use the `goto` module: http://entrian.com/goto/ :-) from goto import goto, label # ... while loop_condition: if condition1 or condition2 or condition3: goto .next print 'stmt1' print 'stmt2' label .next print 'stmt3' print 'stmt4' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Jason Orendorff's path module
On Tue, 12 Aug 2008 03:41:46 -0700, andybak wrote: I know this has been consigned to oblivion by the BDFL but I'm rather addicted to it's use. I notice the original site is no longer there. Has anyone got a cached copy of the page that I can host for posterity? You can download a copy from the Python package index: pypi.python.org Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: for x,y in word1, word2 ?
On Sun, 10 Aug 2008 23:14:50 -0700, ssecorp wrote: I know zip but lets say I have a word painter and I want to compare it to a customer's spelling, he might have written paintor and I want to check how many letters are the same. Now I know how I could do this, it is not hard. I am just wondering if these is any specific simple syntax for it. No special syntax for that, but you can combine the `sum()` function, a generator expression and `zip()`: In [40]: sum(int(a == b) for a, b in zip('painter', 'paintor')) Out[40]: 6 Or this way if you think it's more clear: In [41]: sum(1 for a, b in zip('painter', 'paintor') if a == b) Out[41]: 6 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with global variables
On Fri, 08 Aug 2008 13:10:48 -0400, Anthony Kuhlman wrote: I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = [] def goo(): global foo foo = [] foo.append(2) def moo(): print foo In an ipython session, I see the following: In [1]: from test import * In [2]: foo Out[2]: [] In [3]: goo() In [4]: foo Out[4]: [] In [5]: moo() [2] I don't understand this behavior. I assumed that foo as defined in test.py is a global object, but that doesn't seem to be the case. ``global`` means module global. There's no really global namespace in Python. The ipython session seems to be dealing with one copy of foo while goo() and moo() are using an entirely different copy. The import binds the list from the module to the name `foo` in the IPython namespace. When you call `goo()` it binds the name `foo` *within the module* to a new list. This has of course no influence on the name in the IPython namespace which is still bound to the list object that was bound to `test.foo` before. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: regex question
On Tue, 05 Aug 2008 11:39:36 +0100, Fred Mangusta wrote: In other words I'd like to replace all the instances of a '.' character with something (say nothing at all) when the '.' is representing a decimal separator. E.g. 500.675 500675 but also 1.000.456.344 1000456344 I don't care about the fact the the resulting number is difficult to read: as long as it remains a series of digits it's ok: the important thing is to get rid of the period, because I want to keep it only where it marks the end of a sentence. I was trying to do like this s=re.sub([(\d+)(\.)(\d+)],... ,s) but I don't know much about regular expressions, and don't know how to get the two groups of numbers and join them in the sub. Moreover doing like this I only match things like 345.000 and not 1.000.000. What's the correct approach? In [13]: re.sub(r'(\d)\.(\d)', r'\1\2', '1.000.456.344') Out[13]: '1000456344' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: very large dictionary
On Fri, 01 Aug 2008 00:46:09 -0700, Simon Strobl wrote: I tried to load a 6.8G large dictionary on a server that has 128G of memory. I got a memory error. I used Python 2.5.2. How can I load my data? What does load a dictionary mean? Was it saved with the `pickle` module? How about using a database instead of a dictionary? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to have multiple loop variables?
On Wed, 30 Jul 2008 10:49:58 -0700, laredotornado wrote: I don't know why I thought this would work, but I would like to have 3 variables in my for loop per iteration. Those familiar will know that this ms1 = {'managed1':7019:8020,'managed2':7020:8021} for m, lp, ssl_lp in ms1.items(): managedServer = create(m,'Server') print 'creating managed server '+m managedServer.setListenAddress('147.191.71.70') managedServer.setListenPort(lp) managedServer.setEnabled(0) cd('SSL/cgServer') managedServer.setEnabled(1) managedServer.setListenPort(ssl_lp) managedServer.setCluster(clus1) causes File /export/third-party/etsbea/home/etsbea/tests/wlst/ createcluster.py, line 9 ms1 = {'managed1':7019:8020,'managed2':7020:8021} ^ SyntaxError: invalid syntax How would I set up the ms1 array such that I can use three items per object? `ms1` is a dictionary and not an array. You could use a tuple as value: In [5]: ms1 = {'managed1': (7019, 8020), 'managed2': (7020, 8021)} In [6]: for a, (b, c) in ms1.iteritems(): ...: print a, b, c ...: managed1 7019 8020 managed2 7020 8021 Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Rant (was Re: x*x if x10
On Sun, 27 Jul 2008 16:41:19 +0200, Diez B. Roggisch wrote: DaveM schrieb: Getting back to the list concatenation, I finally found the itertools.chain command which is the most compact and fastest (or second fastest by a trivial amount, I can't remember which). Along the way, I must have tried/used half a dozen methods, ...which brings me back my initial PERL comment. There's more than one way to do it in Python, too. Any non-trivial task has that property. I don't know enough perl to have an example ready that shows something that python has only one way of doing and perl has several. But I *do* know that taking the python zen literally is fruitless. I think it should be taken more literally than the wrong reduction to there should be only one way. People tend to forget obvious and preferably all the time. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Attack a sacred Python Cow
On Sat, 26 Jul 2008 21:46:31 -0700, s0suk3 wrote: (It's true that C++ has more OO features than Python, like private/ public members, virtual methods, etc. Oh yeah, again the discussion about `private`/`public` and if that's an important OOP feature. :-) Aren't *all* methods in Python virtual? And what's etc.? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling external program from within python
On Fri, 25 Jul 2008 08:13:55 -0700, oj wrote: On Jul 25, 3:44 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Because usually if a program *prompts* the user to enter input (and that was what I read from the OP's post), one has to deal with pseudo terminals, not with stdin/out. How does the program writing some text before taking input change how it takes input? It might not write the text before taking input because it is buffered. But if the controlling program waits for some text before sending input to the other program all hangs. If it runs in a terminal and takes input from the user via keyboard, as in the user types a response and presses enter, it's most likely using stdin, in which case subprocess would be perfect. But buffering messes with the order of inputs and outputs. Buffering is different if you talk to a real (or pseudo) terminal or to a file or pipe and the calling program can't influence the called programs buffering except if it pretends to be a terminal, which pexpect does. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: Marc 'BlackJack' Rintsch wrote: I can't even remember when I deleted something from a list in the past. Still, doesn't that strike you as.. workaround? No, I find it actually safer; I don't have to care where modifications of the list might be seen elsewhere in the program. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
On Wed, 23 Jul 2008 09:42:29 -0700, castironpi wrote: On Jul 23, 9:11 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 23 Jul 2008 14:10:22 +0200, mk wrote: Marc 'BlackJack' Rintsch wrote: I can't even remember when I deleted something from a list in the past. Still, doesn't that strike you as.. workaround? No, I find it actually safer; I don't have to care where modifications of the list might be seen elsewhere in the program. Ciao, Marc 'BlackJack' Rintsch a[:]= newlist and a= newlist have two completely different effects, and one is just as safe as 'del'. Besides, del isn't safe to be seen elsewhere in the program in other threads, if they aren't locking the GIL. As usual you are talking nonsense… Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating Through List or Tuple
On Tue, 22 Jul 2008 14:43:10 -0700, Samir wrote: Is there a way to loop or iterate through a list/tuple in such a way that when you reach the end, you start over at the beginning? For example, suppose I define a list daysOfWeek such that: daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] If today is Sunday, I can set the variable day to today by: i = iter(daysOfWeek) day = i.next() print day sunday If I want to find out the day of the week 2 days from now, then this code works ok: for x in xrange(2): day = i.next() print day tuesday However, when extending my range beyond the number of items in the list, I receive an error. For example, if I want to find out the day of the week 11 days from today, I get this: for x in xrange(11): day = i.next() Traceback (most recent call last): File pyshell#87, line 1, in module for x in xrange(11): day = i.next() StopIteration Is there a way to easily loop through a list or tuple (and starting over at the beginning when reaching the end) without having to resort to an if or while statement? For sequences: days_of_week[(today + offset) % len(days_of_week)] For iterables in general: `itertools.cycle()` Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the role of python2.6 and C++?
On Mon, 21 Jul 2008 16:17:00 +0800, 甜瓜 wrote: I'm confused about the motivation of releasing python2.6 and python3.0 at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0 is new style python. That's how it is. 2.6 is backwards compatible with 2.5. […] But even without the intermediate version 2.6, project transformation with be smooth enough, and then 2.5, 2.6 will be replaced by 3.0. I will not spend any time on studying 2.6. So why does python development team put many efforts on 2.6? What is the role of 2.6? It's a version that makes the transition smoother. You really should take that detour via 2.6. There should be some of the changes from 3.0 in 2.6 that don't mess with backwards compatibility, and a script that tries to automate the conversion from 2.6 to 3.0. This spares a lot of work when porting to 3.0. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the name of a variable which was used as a function parameter.
On Mon, 21 Jul 2008 09:01:10 -0700, Ravi Kotecha wrote: I thought this was pretty cool and since I spent 30 mins or so goggling before giving up and figuring out myself I thought I'd share it with you. def a(a): ... for k,v in sys._getframe(1).f_locals.items(): ... if id(v) == id(a): ... print k ... hello = 123 a(hello) hello ## pretty cool. Or ugly hack. Beauty lies in the eye of the beer holder… It's totally useless but I wanted to do it for logging purposes. Don't use such things in production code, please. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Written in C?
On Mon, 21 Jul 2008 11:26:27 -0700, castironpi wrote: On Jul 20, 11:59 pm, Michael Torrie [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: I'm not dissing Python, here. Just noting that, if it is written in C, that throws a curve at me in trying to balance the value of learning Python vs. some other major language. Definitely one of the most non-sequitor statements I have ever heard. Actually your entire post doesn't make much sense. Maybe you are a brother bot to castropini? Perhaps a less-trained one, although none of castropini's posts seem to make sense either. The AI needs a bit of work. Are you saying Python is not good for writing A.I., or the A.I. isn't good at writing Python? Are you saying python is not as smart as you. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: re: question
On Sun, 20 Jul 2008 18:39:52 +0100, Perl_Wizard wrote: Nobody any sensible answers. Too complicated I suppose! I've often been asked that, i'd be able to buy me a mars bar! Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Question
On Sat, 19 Jul 2008 10:27:28 +0100, perl_wizard wrote: Why is Perl so much better than python? You are so much better than python? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: MethodChain
On Sat, 19 Jul 2008 08:55:23 -0700, bearophileHUGS wrote: Found from Reddit, it's for e ECMA(Java)Script, but something similar may be useful for Python too: http://jsclass.jcoglan.com/methodchain.html http://blog.jcoglan.com/2008/07/16/where-did-all-my-code-go-using-ojay-chains-to-express-yourself-clearly/ What's called `MethodChain` there seems to be function composition in functional languages. Maybe `functools` could grow a `compose()` function. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Change PC to Win or Windows
On Sat, 19 Jul 2008 11:02:51 -0500, Grant Edwards wrote: On 2008-07-19, Dennis Lee Bieber [EMAIL PROTECTED] wrote: Which term applied to the TRS-80, the Apple II, Altair even... Not that I remember. I had a homebrew S-100 bus system, worked with varioius Commodore machines, a few Apples, and some other CP/M systems. I never heard any of them called a 'PC'. My recollection is that 'PC' was a term that IBM coined. The C64 that still sits on my desk has a label on it saying “commodore 64 - personal computer”. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: MethodChain
On Sat, 19 Jul 2008 13:57:33 -0700, bearophileHUGS wrote: Marc 'BlackJack' Rintsch: What's called `MethodChain` there seems to be function composition in functional languages. Maybe `functools` could grow a `compose()` function. To me it looks like a quite more refined thing, it's an object, it has some special methods, etc. I think it's not too much difficult to implement it with Python. The methods are a problem IMHO. You can't add an own method/function with the name `fire()` or `toFunction()`. `MethodChain` has to know all functions/methods in advance. You can add the methods of whole classes at once and there are over 300 pre-added, this begs for name clashes. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if an object IS in a list
On Sat, 19 Jul 2008 13:13:40 -0700, nicolas.pourcelot wrote: On 18 juil, 17:52, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: So, I use something like this in 'sheet.objects.__setattr__(self, name, value)': if type(value) == Polygon: for edge in value.edges: if edge is_in sheet.objects.__dict__.itervalues(): object.__setattr__(self, self.__new_name(), edge) Ok, I suppose it's confused, but it's difficult to sum up. ;-) You are setting attributes with computed names? How do you access them? Always with `gettattr()` or via the `__dict__`? If the answer is yes, why don't you put the objects the into a dictionary instead of the extra redirection of an objects `__dict__`? Yes, I may subclass dict, and change its __getitem__ and __setitem__ methods, instead of changing objets __setattr__ and __getattr__... But I prefer sheet.objects.A = Point(0, 0) than sheet.objects[A] = Point(0, 0) But with computed names isn't the difference more like setattr(sheet.objects, name, Point(0, 0)) vs. sheet.objects[name] = Point(0, 0) and getattr(sheet.objects, name) vs. sheet.objects[name] Or do you really have ``sheet.objects.A`` in your code, in the hope that an attribute named 'A' exists? Oh and the `type()` test smells like you are implementing polymorphism in a way that should be replaced by OOP techniques. I wrote 'type' here by mistake, but I used 'isinstance' in my code. ;-) Doesn't change the code smell. OOP approach would be a method on the geometric objects that know what to do instead of a type test to decide what to do with each type of geometric object. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: None in comparison
On Thu, 17 Jul 2008 23:52:13 -0700, r.grimm wrote: Hello, I'm a little confused about None in comparison. id ( None ) 3086100672L id ( 1 ) 134541104 None 1 True I thought, the id of the object is the last comparison criterion. Obviously that expectation is false. The result of a comparison between different types, with no `__cmp__()` method that says otherwise, is a arbitrarily but consistent ordering by type. The language doesn't even guarantee that it must be consistent in different runs of the same program in the same interpreter, just within one run. So if you plan to rely on such implementation details, your program is broken. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on Joining of list
On Fri, 18 Jul 2008 01:31:59 -0700, SUBHABRATA wrote: def try2(n): a1=raw_input(PRINT A STRING:) a2=a1.split() a3=God Godess Heaven Sky for x in a2: a4=a3.find(x) if a4-1: a5=a3[a4] print a5 elif a40: a6=x print It is not found print a6 else: print Error s=a5+ +a6 print s Here, if I put a string like: Petrol Helium Heaven Sky In s it is giving me S Helium But I am looking for an output of a5 and a6 concatenating all its values not the last ones. Can you suggest me any help? Am I missing any minor point? Maybe you should describe what the input looks like and what output you want to have and how the input and output are connected. In words, not in not very clear code with numbered names. That's a silly idea and makes understanding the code very hard. Please use meaningful names! Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression help
On Fri, 18 Jul 2008 10:04:29 -0400, Russell Blau wrote: values = {} for expression in line.split( ): if = in expression: name, val = expression.split(=) values[name] = val […] And when you get to be a really hard-core Pythonista, you could write the whole routine above in one line, but this seems clearer. ;-) I know it's a matter of taste but I think the one liner is still clear (enough):: values = dict(s.split('=') for s in line.split() if '=' in s) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: checking if an object IS in a list
On Fri, 18 Jul 2008 07:39:38 -0700, nicolas.pourcelot wrote: So, I use something like this in 'sheet.objects.__setattr__(self, name, value)': if type(value) == Polygon: for edge in value.edges: if edge is_in sheet.objects.__dict__.itervalues(): object.__setattr__(self, self.__new_name(), edge) Ok, I suppose it's confused, but it's difficult to sum up. ;-) You are setting attributes with computed names? How do you access them? Always with `gettattr()` or via the `__dict__`? If the answer is yes, why don't you put the objects the into a dictionary instead of the extra redirection of an objects `__dict__`? Oh and the `type()` test smells like you are implementing polymorphism in a way that should be replaced by OOP techniques. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: __del__ methods
On Fri, 18 Jul 2008 11:31:20 -0700, Jason Baker wrote: I have a class that I need to do some finalization on when it dies. I know I can use the __del__ method, but I seem to recall that it impedes garbage collection. Is this the case? `__del__()` is not a deterministic destructor. So forget about reliable automatic clean up. Do it yourself with an explicit call to a `close()` method or something like that. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: how to avoid line return when using python -c 'print foo'
On Fri, 18 Jul 2008 23:04:06 +0200, TP wrote: All my problem is in the title. If I try: $ python -c 'print foo,' It does not change anything, surely because the line return is added by python -c. It is added by the interpreter at exit time. The interpreter tries to be smart here deciding for you that the last printed line before program exit should end in a newline. Use `sys.write()` instead of ``print``. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: __del__ methods
On Fri, 18 Jul 2008 12:26:35 -0700, Jason Baker wrote: I don't necessarily need deterministic cleanup. And I plan on doing something like a close() method as well. But I'd just like to make sure nothing slips between the cracks. :) `__del__()` isn't guaranteed to be called *at all*, so can't make sure nothing slips between the cracks with it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: properly delete item during for item in...
On Thu, 17 Jul 2008 09:27:27 -0700, Ratko wrote: for item in myList: del item Would this actually delete the item from the list or just decrement the reference counter because the item in myList is not associated with name item anymore (but still is with myList[itemIndex])? In other words, is item a temporary reference to myList[itemIndex] or is it actually that reference that myList has stored? The latter. Names are always bound to objects, you can't bind a name to another name or reference in Python. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging in __del__()
On Wed, 16 Jul 2008 12:38:50 +0100, Robert Rawlins wrote: So, am I right to assume that python will still handle its garbage disposal if I implement __del__(), it just handles circular references in a slightly different way, but to the same effect. Right? No. Circular references in objects with a `__del__()` implementation are not collected! Why are you using `__del__()` anyway? Are you aware of the promises that are *not* made! It's not guaranteed when the method is called nor if it is called at all! Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
On Wed, 16 Jul 2008 07:53:56 -0700, Keith Hughitt wrote: I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? That's not Python's business but the command shell's. Those characters are used for redirecting input and ouput from/to files in shells, so it should be covered in the documentation of the shell you are using. Including ways to protect the characters, so they reach the called program in arguments. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Amazon: Practical Django Projects by James Bennett (June 2008)
On Thu, 17 Jul 2008 05:41:11 +0200, Stefan Scholl wrote: Fredrik Lundh [EMAIL PROTECTED] wrote: Stefan Scholl wrote: Django isn't ready. That's a remarkably ignorant statement. The 1.0 release will be in September. So what? It's not the version number that matters but features and stability. It's not uncommon in open source projects to have very usable software with a version number below 1.0. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: String flags - redundant?
On Tue, 15 Jul 2008 18:14:15 +0300, Alexandru Palade wrote: I'm rather a Python newbie, so I've put myself a question. Are these two statements (performance-wise) equal? r Text and Text I mean using the raw flag speeds up things because the interpreter doesn't need to look after escape sequences? Or it's rather optimized? I'm asking you this because I want to know how my -style comments should be written in order not to affect the performance. *Please* stop worrying about the speed of the compilation here. If you have doubts about speed then measure and find the bottlenecks in your code and iff you find hotspots *then* try to optimize. But only iff the program is *to slow*, not when it's fast enough anyway. In that case you should always favor more readable code above speed. And another short question... Are there any flags to specify variables intercalation in a string? I mean I have x apples, how can i specify for the interpreter to substitute x with it's value? (in case *x* is a variable). And if this flag exists is it better to use I have + x + apples or the above mentioned way? Maybe you should work through the tutorial in the Python documentation. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals question
On Tue, 15 Jul 2008 23:54:46 +1000, Peter Anderson wrote: Python is a dynamically typed language in which names can represent values of different types during the execution of a program. In fact the names used in the program are really just labels for various quantities and objects. The assignment operator simply creates an association between a name and a value. This is different from C, for example, in which a name (variable) represents a fixed size and location in memory... As an old mainframe programmer, I understand the way C does things with variable but this text got me wondering how Python handles this association between variable name and value at the lower level. Is it like a fifo list? Why a fifo list? Names don't remember the values and types they are bound to over time, there's just one binding at any time if a name exists. Internally you can think of a pointer to a struct that represents the object. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote: Kay, can you show example of such generator? ReIter, for example, work with usual generators. But for big iterator, I think is no any good solutions. IMHO we can discern 2 types of iterators: re-startable (based on internal Python objects) and not re-startable (with an external state, side- effects)... Has nothing to do with internal vs. external. Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with curses
On Sat, 12 Jul 2008 20:49:56 -0400, Clay Hobbs wrote: Unfortunately, the error message isn't very helpful. But it would be helpful to tell it. If you get exceptions, always copy'n'paste the traceback here. People might know what the exception means and share their wisdom. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator clone
On Sun, 13 Jul 2008 18:51:19 -0700, Yosifov Pavel wrote: Well, I think Python's iterators, especially the generators, are beautiful. More importantly, I think there is no general way to make iterators copyable, regardless of the programming language. The problem is that most of the useful ones depend on external state. Hmm, but tee() de facto do it (clone iterator) and ignore side-effects of iterator (external state). And tee() create independent **internal** state of iterator (current position). `tee()` doesn't copy the iterator or its internal state but just caches it's results, so you can iterate over them again. That makes only sense if you expect to use the two iterators in a way they don't get much out of sync. If your usage pattern is consume iterator 1 fully, and then re-iterate with iterator 2 `tee()` has no advantage over building a list of all results of the original iterator and iterate over that twice. `tee()` would be building this list anyway. But **external** state - is headache of programmer. So, iterator/generator have to be method for copy itself (the tee() implementation) or be re- startable. Why not? Because it's often not possible without generating a list with all results, and the advantage of a low memory footprint is lost. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create a timer/scheduler in Python?
On Sat, 12 Jul 2008 10:30:00 +0100, John Dann wrote: Looking around on the net I can see references to a thread timer, but I'm not really looking to start any new threads (I just want part of the GUI to update every 2 secs) and don't want to get into that sort of complication while still just learning Python. Look into the GUI toolkit because that's typically something solved with functions from the specific toolkit. Is there really no simple timer/scheduler function available in Python? You can do that quite easily with threads but almost all GUI toolkits don't like it if you access the GUI from multiple threads. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: strip() using strings instead of chars
On Fri, 11 Jul 2008 16:45:20 +0200, Christoph Zwerschke wrote: Bruno Desthuilliers schrieb: DRY/SPOT violation. Should be written as : prefix = 'http://' if url.startswith(prefix): url = url[len(prefix):] That was exactly my point. This formulation is a bit better, but it still violates DRY, because you need to type prefix two times. It is exactly this idiom that I see so often and that I wanted to simplify. Your suggestions work, but I somehow feel such a simple task should have a simpler formulation in Python, i.e. something like url = url.lstripstr(('http://', 'https://')) I would prefer a name like `remove_prefix()` instead of a variant with `strip` and abbreviations in it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Manipulating bitsets in struct
On Wed, 09 Jul 2008 20:04:24 -0400, Allen wrote: I'm using Python to do some simple network programming, and found the struct module very useful for such things, but is there a way to easily manipulate bitsets such as a 16 bit word being split into 4 parts like 2 bits, 1 bit, 4 bits, and 9 bits? Perhaps something like: struct.pack('!h(2:1:4:9)',2,0,1,100) Take a look at Construct_ instead of `struct`. .. _Construct: http://construct.wikispaces.com/ Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and decimal character entities over 128.
On Wed, 09 Jul 2008 16:39:24 -0700, bsagert wrote: Some web feeds use decimal character entities that seem to confuse Python (or me). I guess they confuse you. Python is fine. For example, the string doesn't may be coded as doesn#8217;t which should produce a right leaning apostrophe. Python hates decimal entities beyond 128 so it chokes unless you do something like string.encode('utf-8'). Python doesn't hate nor chokes on these entities. It just refuses to guess which encoding you want, if you try to write *unicode* objects into a file. Files contain byte values not characters. Even then, what should have been a right-leaning apostrophe ends up as ’. The following script does just that. Look for the string The Canuck iPhone: Apple doesnâ €™t care after running it. Then you didn't tell the application you used to look at the result, that the text is UTF-8 encoded. I guess you are using Windows and the application expects cp1252 encoded text because an UTF-8 encoded apostrophe looks like '’' in cp1252. Choose the encoding you want the result to have and anything is fine. Unless you stumble over a feed using characters which can't be encoded in the encoding of your choice. That's why UTF-8 might have been a good idea. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search much slower then grep on some regular expressions
On Mon, 07 Jul 2008 16:44:22 +0200, Sebastian \lunar\ Wiesner wrote: Mark Wooding [EMAIL PROTECTED]: Sebastian lunar Wiesner [EMAIL PROTECTED] wrote: # perl -e '(a x 10) =~ /^(ab?)*$/;' zsh: segmentation fault perl -e '(a x 10) =~ /^(ab?)*$/;' (Did you really run that as root?) How come, that you think so? The '#' is usually the prompt of root accounts while ordinary users get a '$'. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: compatible image type
On Fri, 04 Jul 2008 01:15:30 -0700, gordon wrote: then later on i want to create a Photoimage using ImageTk.PhotoImage(file=pathname) and display it on a canvas. the extn can be anything ..even zip or bat ,doc whatever depending on user selection...I want to put someway to raise an error message to the user if he selects a file with extension not of a compatible image type for PhotoImage.How should i do this? should i check 'extn' to a list of compatible image type extensions(something like [''jpg','jpeg','png','gif'...] ) or is there a better way? Just catch the exception raised by `PhotoImage` if a non compatible file was selected!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Static Class Initialization Question.
On Fri, 04 Jul 2008 14:59:05 +0200, Thomas Troeger wrote: Bruno Desthuilliers wrote: I want to have a list of such classes instantiated automatically on Of course I meant class instances ... sorry :) It's always good to have an example to compensate for English errors *g*. Well, class instances is still a little bit ambiguous in a language where classes are objects too. ;-) Ah I knew there was something and I couldn't find it in the docs anymore! Now my potential follow-up question is answered as well, namely how I can instantiate with variable argument lists, like this: bla = [A(*args) for args in ((), (1,), (1, 2))] map(str, bla) ['A(0,1)', 'A(1,1)', 'A(1,2)'] Looks like you want default values for the arguments of `A.__init__()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: n00bie wants advice.
On Tue, 01 Jul 2008 23:25:53 -0700, bsagert wrote: This simple script writes html color codes that can be viewed in a browser. I used short form hex codes (fff or 000, etc) and my list has only six hex numbers otherwise the results get rather large. I invite criticism as to whether my code is pythonic. You should not rebind the name `list` because it shadows the built in type of that name then. A more descriptive name would be nice anyway, i.e. `hex_digits`. And strings are iterable too, so it's a bit shorter and easier to type the digits a string. Repeatedly concatenating strings with ``+=`` might be performance problem. Python strings are immutable so this operation has to copy the involved and growing strings over and over again. Although the current CPython implementation can optimize here in some cases, the usual idiom is to use the `join()` method of strings to build a string from components in a list or iterable. Alternative implementation of your script: from __future__ import with_statement def main(): html_template = ('htmlheadstyleh1{margin:0}/style/headbody\n' '%s\n' '/body/html\n') header_template = 'h1 style=background:#%s%s/h1' hex_digits = '369bdf' colors = (a + b + c for a in hex_digits for b in hex_digits for c in hex_digits) html = html_template % '\n'.join(header_template % (c, c) for c in colors) with open('test.html', 'w') as html_file: html_file.write(html) if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: how to judge urllib.Request is finished?
On Tue, 01 Jul 2008 15:16:03 +0800, oyster wrote: currently I am using [code] req=urllib2.Request(url) data='' if '/htm' not in data: fd=urllib2.urlopen(req) data=fd.read() time.sleep(10) time.sleep(10) blahblah [/code] That looks very strange. Why the ``if`` and the `sleep()`\s? The ``if`` condition is always true, so it's completely unnecessary. The `read()` call is blocking, that means it returns iff the complete data is read. So there's no need to wait or to check if all is read. If there's a problem with the connection an exception should be raised by `urllib2`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Having problems using Tkinter
On Tue, 01 Jul 2008 03:13:42 -0700, viv1tyagi wrote: Hi everyone ! ! ! I'm just a month old in the world of Python and trying to develop an application using Tkinter in which a new window pops out on a particular button press.The code for this new window is in AddKlas.py file. The problem is all the content of the new window is overwritten on the previous window. Below is the code of the two files There can be only one `Tkinter.Tk` instance per running program. Other top level windows have to be `Tkinter.Toplevel` instances. And you should reconsider your usage of classes. You are just abusing them as containers for functions without using `self` really. And you should pass the instance of the parent widget as first argument to constructors of widgets. Otherwise the very first, i.e. the `Tk` instance, is assumed, which is not true for the widgets that should appear in the `Toplevel` instance. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Error from zipfile
On Tue, 01 Jul 2008 16:38:23 +0100, Wesley Brooks wrote: Dear Users, I'm having a problem when trying to move script from Linux to Windows. A zipfile opperation is failing with the message: BadZipFile: File is not a zip file I have a simple scripts that reads a zip file in the same way as any other file into a string, then sends it across to a network where it is saved as perusual into a file, […] Are you sure you read and save the file in binary mode, especially on windows!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Please check my understanding...
On Tue, 01 Jul 2008 12:35:01 -0700, Tobiah wrote: list.append([1,2]) will add the two element list as the next element of the list. list.extend([1,2]) is equivalent to list = list + [1, 2] and the result is that each element of the added list becomes it's own new element in the original list. It's not 100% equivalent because `list.extend()` mutates the original list while ``+`` creates a new list object: In [8]: a = [1, 2, 3] In [9]: b = a In [10]: b.extend([4, 5]) In [11]: b Out[11]: [1, 2, 3, 4, 5] In [12]: a Out[12]: [1, 2, 3, 4, 5] In [13]: b = b + [6, 7] In [14]: b Out[14]: [1, 2, 3, 4, 5, 6, 7] In [15]: a Out[15]: [1, 2, 3, 4, 5] Is that the only difference? From the manual: s.extend(x) |same as s[len(s):len(s)] = x But: (python 2.5.2) a [1, 2, 3] a[len(a):len(a)] = 4 Traceback (most recent call last): File stdin, line 1, in module TypeError: can only assign an iterable Have you tried `extend()` with the same value? In [15]: a Out[15]: [1, 2, 3, 4, 5] In [16]: a.extend(6) --- type 'exceptions.TypeError' Traceback (most recent call last) /home/bj/ipython console in module() type 'exceptions.TypeError': 'int' object is not iterable See, both ways need something iterable. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping-related Memory Leak
On Mon, 30 Jun 2008 10:55:00 -0700, Tom Davis wrote: To me, this seems illogical. I can understand that the GC is reluctant to reclaim objects that have many connections to other objects and so forth, but once those objects' scopes are gone, why doesn't it force a reclaim? For instance, I can use timeit to create an object instance, run a method of it, then `del` the variable used to store the instance, but each loop thereafter continues to require more memory and take more time. 1000 runs may take .27 usec/pass whereas 10 takes 2 usec/pass (Average). `del` just removes the name and one reference to that object. Objects are only deleted when there's no reference to them anymore. Your example sounds like you keep references to objects somehow that are accumulating. Maybe by accident. Any class level bound mutables or mutable default values in functions in that source code? Would be my first guess. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a path to components
On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: You can just split the path on `os.sep', which contains the path separator of the platform on which Python is running: components = pathString.split(os.sep) Won't work for platforms with more than one path separator and if a separator is repeated. For example r'\foo\\bar/baz//spam.py' or: In [140]: os.path.split('foo//bar') Out[140]: ('foo', 'bar') In [141]: 'foo//bar'.split(os.sep) Out[141]: ['foo', '', 'bar'] Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a path to components
On Sat, 07 Jun 2008 02:15:07 -0700, s0suk3 wrote: On Jun 7, 3:15 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Fri, 06 Jun 2008 23:57:03 -0700, s0suk3 wrote: You can just split the path on `os.sep', which contains the path separator of the platform on which Python is running: components = pathString.split(os.sep) Won't work for platforms with more than one path separator and if a separator is repeated. For example r'\foo\\bar/baz//spam.py' or: In [140]: os.path.split('foo//bar') Out[140]: ('foo', 'bar') In [141]: 'foo//bar'.split(os.sep) Out[141]: ['foo', '', 'bar'] But those are invalid paths, aren't they? No. See `os.altsep` on Windows. And repeating separators is allowed too. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Thu, 05 Jun 2008 23:56:40 -0700, dwahli wrote: On Jun 6, 8:44 am, Terry Reedy [EMAIL PROTECTED] wrote: Of course, enumerate(iterable) is just a facade over zip(itertools.count(), iterable) So you could write: gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])) print list(gen) Useless use of a generator expression. This: gen = itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]) print list(gen) has the same effect without the intermediate generator that does nothing but passing the items. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Harry Potter?
On Thu, 05 Jun 2008 11:58:14 +0200, Helmut Jarausch wrote: Today I've got an email from Amazon recommending me Harry Potter and the Deathly Hallows and they told me why they recommended this book, because I've bought Core PYTHON Programming Didn't know, Harry Potter is a Python fan. I would've expected something with more magic, like Perl. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Thu, 05 Jun 2008 08:21:41 +, Antoon Pardon wrote: On 2008-06-04, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 04 Jun 2008 09:34:58 +, Antoon Pardon wrote: On 2008-06-04, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: it makes sense to me to also test if they work as documented. If they affect the behaviour of some public component, that's where the documentation should be. As I said they are public themselves for someone. Isn't that contradictory: Public for someone I always thought public meant accessible to virtually anyone. Not to only someone. For the programmer who writes or uses the private API it isn't really private, he must document it or know how it works. How does that make it not private. Private has never meant accessible to noone. And sure he must document it and know how it works. But that documentation can remain private, limited to the developers of the product. It doesn't have to be publicly documented. If the audience is the programmer(s) who implement the private API it is not private but public. Even the public API is somewhat private to a user of a program that uses that API. The public is not virtually anyone here. Depends at which level you look in the system. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Wed, 04 Jun 2008 15:55:38 +1000, Ben Finney wrote: Marc 'BlackJack' Rintsch [EMAIL PROTECTED] writes: On Wed, 04 Jun 2008 13:50:42 +1000, Ben Finney wrote: It seems you [alex23] have a different idea of what unit testing is for from me. For me it's about finding bugs where documentation and implementation disagree. Where documentation is specified externally-visible behaviour of the unit, I agree with this. And if you document private functions By definition, private functions are not part of the publicly documented behaviour of the unit. Any behaviour exhibited by some private component is seen externally as a behaviour of some public component. But only indirectly, and it's often harder to predict the corner cases that might trigger bugs or to test error testing in dependent private functions. Private functions offer an API that's public to someone, so they ought to be documented and tested. it makes sense to me to also test if they work as documented. If they affect the behaviour of some public component, that's where the documentation should be. As I said they are public themselves for someone. Because the official API relies on the correct implementation of the private parts it uses under the hood. Only to the extent that the documented behaviour of the API is affected. The main benefit of marking something as not public is that one *is* free to change its behaviour, so long as the public API is preserved. One more reason to test the individual private functions because a change of such a function shouldn't make it necessary to change the unit tests of the public API. One part of writing unit tests is invoking functions with arguments that you think are corner cases. For example test if a function that takes a list doesn't bomb out when you feed the empty list into it. Or if it handles all errors correctly. This sounds like part of the externally-visible behaviour of the code unit; i.e. something that belongs in the public API. I agree that this is the domain of a unit test. If a function `f()` calls internally `_g()` and that function might even call other private functions, then you have to know how `f()` works internally to create input that checks if error handling in `_g()` works correctly. No, you don't need to know how it works internally; you need only know what guarantees it must keep for its external behaviour. How do you know the corner cases then? Often it is interesting how a function that takes integers copes with zero, so that might be a test. It's easy if you test a function directly but you need to know the internals if you must find arguments that lead to a dependent function called with zero. Contrived example: def _g(i): return (42 / i) if i else 0 def f(x): return _g(x + 23) Here ``f(-23)`` is a special corner case that should be tested somehow. And I think it is better tested as explicit test of `_g()` than with a test of `f()`. Testing for corner cases needs some knowledge about the implementation, but that shouldn't be transitive. The tests for `f()` should assume that `_g()` itself has promised in its documentation was already covered by a unit test. If someone wants to alter the `_g()` function, or remove it entirely while preserving the correct behaviour of `f()`, that should have no effect on the external behaviour of `f()`. That is to say, the knowledge of the internals of `f()` in your example is actually knowledge of something that should be documented as part of the external behaviour of `f()` — that, or it's not relevant to the behaviour of `f()` and shouldn't be unit tested in order that encapsulation is preserved. `f()`'s documentation should mention that it works for all integers including -23 with -23 explicitly mentioned? What do you do in such a situation? Build something from untested private parts and just test the assembled piece? Assert the corner-case behaviour of `f()`, through unit tests that operate on `f()` without caring about its internals. And this way missing many potential bugs? I prefer to test the private functions too. After all the private functions are not private to the everybody, there *are* functions that rely on them working correctly. Then for *those* interfaces, unit tests can be devised that make assertions about those interfaces. Now you lost me. So essentially you don't test private functions unless they are used somewhere, then they should be tested too. As private functions that are not used, shouldn't be there in the first place, every function private or public should be tested, right!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: readline() seek() ???
On Wed, 04 Jun 2008 14:30:19 -0700, DataSmash wrote: I have a text file that contains thousands of lines and each line is 256 characters long. This is my task: For each line in the file, move to the 25th character, if the character is a T, move to the 35th character of the line and read 5 characters from there. Capture these 5 characters and write them to a new text file, each 5 characters separated by a comma. No `readline()`, it's not a line based format but a record based one, and no `seek()` because you don't need to access the records in random order. Just use `read()` to read the 256 byte records one at a time and string slicing to extract the data. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Wed, 04 Jun 2008 09:34:58 +, Antoon Pardon wrote: On 2008-06-04, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: it makes sense to me to also test if they work as documented. If they affect the behaviour of some public component, that's where the documentation should be. As I said they are public themselves for someone. Isn't that contradictory: Public for someone I always thought public meant accessible to virtually anyone. Not to only someone. For the programmer who writes or uses the private API it isn't really private, he must document it or know how it works. And he should IMHO write tests for it and expect private functions written by others to be tested. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Q about object identity
On Tue, 03 Jun 2008 23:08:46 +0200, Christian Heimes wrote: [EMAIL PROTECTED] schrieb: Hello, I am testing object identity. If I do it from the interpreter, I get strange results. print [] is [] False print id([]), id([]) 3083942700 3083942700 Why is that? Isn't this an error? No, it's not an error. You are getting this result because the list implementation keeps a bunch of unused list objects in a free list. It's an optimization trick. Python has to create two different list objects for [] is [] while it can reuse the same list object for id([]) == id([]). I don't think you need optimization tricks for the explanation. In ``[] is []`` there need to be two lists that exist at the same time to be compared by the ``is`` operator. With ``id([]) == id([])`` just the id numbers have to exist at the same time, so the execution may look like this: • create empty list • call `id()` with it • remember first id number • when `id()` returns, the list is not referenced anymore and can be garbage collected • create empty list, and here the list object might get allocated at the same memory location as the first empty list → same id. • call `id()` with it • remember second id number • garbage collect second empty list • compare both numbers Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Wed, 04 Jun 2008 13:50:42 +1000, Ben Finney wrote: alex23 [EMAIL PROTECTED] writes: So the basic answers I'm seeing that do just fine are: 1. Don't test private functions. 2. Add functionality _to_ the private functions for testing. 3. Change the interface for the purpose of testing. All of which seem exceptionally inefficient and run counter to the whole purpose of unit testing. It seems you have a different idea of what unit testing is for from me. For me it's about finding bugs where documentation and implementation disagree. And if you document private functions it makes sense to me to also test if they work as documented. Because the official API relies on the correct implementation of the private parts it uses under the hood. Isn't the entire point of encapsulation to separate internal components from the external interface? Why would a unit test, the whole purpose of which is to assert some aspect of the external behaviour of the unit of code, care about how that code unit is implemented internally? One part of writing unit tests is invoking functions with arguments that you think are corner cases. For example test if a function that takes a list doesn't bomb out when you feed the empty list into it. Or if it handles all errors correctly. If a function `f()` calls internally `_g()` and that function might even call other private functions, then you have to know how `f()` works internally to create input that checks if error handling in `_g()` works correctly. So it goes against your understanding of unit tests. What do you do in such a situation? Build something from untested private parts and just test the assembled piece? I prefer to test the private functions too. After all the private functions are not private to the everybody, there *are* functions that rely on them working correctly. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing HTML
On Mon, 02 Jun 2008 01:03:05 -0700, miller.paul.w wrote: I've searched the standard library docs, and, while there are a couple options for *reading* HTML from Python, I didn't notice any for *writing* it. I guess that's where the many templating engines are used. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Formatting Output
On Mon, 02 Jun 2008 00:34:09 -0700, [EMAIL PROTECTED] wrote: i am building a little script and i want to output a series of columns more or less like this: 1 5 6 2 2 8 2 9 5 The matter is that i don't know in advance how many columns there will be. By the way, each column will be actually FLOATs, not INTs. How can i do this ? Any help welcome. Regards, Look at string methods, `join()` for example, and string formatting with the ``%`` operator. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: php vs python
On Mon, 02 Jun 2008 18:21:26 -0700, Joel Koltner wrote: Arnaud Delobelle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] This is wrong, because if you know well one language only, you tend to think that the principles that underpin it are universal. So you will try to shoehorn these principles into any other language you use. Fair point, although I guess I was assuming the language you were good in was something that covers, say, 90% of contemporary programming practices, e.g., something like C++ : If you're truly good at C++ (and percentage-wise of all programmers, relatively few are), there are not many things that I'm aware of that are tremendously different in any other programming language. Function decorators from Java and some of the function programming stuff from Lisp, perhaps, but those are pretty small additions (well within the 10%). I think you are talking about something a little different than Arnaud. You are talking about the 10% that's new in another language that has to be learned additionally and Arnaud is talking about the stuff the programmer already knows about the old language that somewhat works in the new one but is all but optimal and thus has to be *unlearned*. From C++ to Python or Java this is RAII and deterministic destructors for instance. Other old habits from people coming to Python are: using indexes where they are not needed, trivial getters and setters, putting *everything* into classes and every class into a module, and so on. Another difference are internal versus external iterators. In Python you write the loop outside the iterable and pull the items out of it. In other languages (Ruby, Io, …) iterables do internal iteration and you give them a function where all item are pushed into one at a time. Perhaps I should reduce my claim to those good at programming in any first class language like C++ are generally going to write at least above-average code in any other language. :-) What makes C++ a first class language? And did you quote first class for the same reason than I did? ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Integrating a code generator into IDLE
On Sun, 01 Jun 2008 10:40:09 -0500, Sam Denton wrote: Code generators seem to be popular in Python. I don't think so. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flaming Thunder
On Thu, 29 May 2008 17:57:45 -0400, D'Arcy J.M. Cain wrote: I guess I am still new to this group and don't understand its charter. I wasn't aware that it was a Flaming Blunder group. Can someone please point me to a newsgroup or mailing list dedicated to the Python programming language? By discussing language design of FT compared to other languages you can learn about Python. We all know that Python is brilliant -- here's the opportunity to think about why it is. :-) And it's basically only this very long thread, so it's easy to filter and ignore in a decent news reader. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: question
On Thu, 29 May 2008 15:41:29 -0700, Gandalf wrote: On May 30, 12:14 am, John Henderson [EMAIL PROTECTED] wrote: Gandalf wrote: how do i write this code in order for python to understand it and print me the x variable x=1 def (): x++ if x 1: print wrong else : print x () Example: x=1 def (x): x += 1 if x 1: return wrong else : return x print (x) John mmm isn't their any global variable for functions? There is but you shouldn't use global variables as they make program and data flow harder to understand, the code more difficult to test, and usually couples functions more tightly then they should. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list