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: 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
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: while-loop?
On Wed, 28 May 2008 19:56:55 +0200, huub wrote: > Being a newbie with Python, I'm trying a short program with this: > > > <..> >> t = RoboInterface() > > <..> >> while not t.Digital(1): # while endpoint is not reached >> 15 pass > > However, it always hangs on the 'while', which I can't find in the > tutorial at http://www.python.org/doc/. Assuming 'while' should work, > what's wrong with the code? Obviously the condition is alway true. Maybe you have to do something within the loop so it eventually will be false at some point!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: maximum recursion depth?
On Wed, 28 May 2008 02:28:54 -0700, bearophileHUGS wrote: > Dennis Lee Bieber, the ghost: >> I'd have to wonder why so many recursive calls? > > Why not? Because of the recursion limit of course. And function call overhead in Python is quite high compared to an iterative approach. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: which datastructure for fast sorted insert?
On Sun, 25 May 2008 00:10:45 -0700, notnorwegian wrote: > sets dont seem to be so good because there is no way to iterate them. Err: In [82]: for x in set(['a', 'b', 'c']): : print x : a c b Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: recursion with or without return?
On Sun, 25 May 2008 00:00:14 -0700, notnorwegian wrote: > when using recursion should one use a return statement or not? This decision has nothing to do with recursion. It's the same as in non recursive functions. If the function calculates something that you want to return to the caller you have to use ``return``. If the function just has side effects, e.g. printing a tree structure recursively, you don't have to ``return`` something. > but is there a guideline for this or it just taste or is it > considering good style or pythonic to always have a returnvalue? Well, you always have a return value anyway because there's an implicit ``return None`` at the end of every function. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On Sat, 24 May 2008 13:13:08 +0200, Johannes Bauer wrote: > George Sakkis schrieb: > >>> However, this "assignment and comparison" is not working. What's the >>> "Python way" of doing this kind of thing? >> >> The most obvious and readable of course: use two statements, as one >> should do regardless of the language, instead of resorting to error- >> prone hacks. > > As I said in the reply to Carl, this might be okay for if-clauses, but > is bothering me with while-loops. Then try to write the ``while`` loop as ``for`` loop and move the comparison into a generator function, or use the two argument variant of `iter()`, or `itertools.takewhile()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment and comparison in one statement
On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote: > Carl Banks schrieb: > >> p = myfunction() >> if p: >> print p >> >> (I recommend doing it this way in C, too.) > > This is okay for if-clauses, but sucks for while-loops: > > while (fgets(buf, sizeof(buf), f)) { > printf("%s\n", buf); > } > > is much shorter than > > char *tmp; > tmp = fgets(buf, sizeof(buf), f); > while (tmp) { > printf("%s\n", buf); > tmp = fgets(buf, sizeof(buf), f); > } Can be written in Python as: from functools import partial # ... for buf in iter(partial(f.read, buf_size), ''): print '%s\n' % buf Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: csv iterator question
On Fri, 23 May 2008 13:36:55 -0700, davidj411 wrote: > example of open method on file object: > fhandle=open(filename).readelines() Here the name `fhandle` is somewhat misleading. You don't bind the file object to that name, but the result of the call of the `readlines()` method. Which is a list of lines. If you would have bound the file object, you'd observe similar behavior to your CSV reader example. > example of csv.reader method: > reader = csv.reader(open(csvfilename)) Because here you are binding the reader object. Throw in a `list()` to read all CSV records into a list: records = list(csv.reader(open(csv_filename))) In both cases you don't close the file explicitly which might cause problems. That CPython closes it for you almost immediately is an implementation detail. Other implementations might let those open files stay open for much longer. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
On Fri, 23 May 2008 07:14:08 -0400, inhahe wrote: > If the GUI defines that it's a board layout like chess or > checkers and the player will move around the board, it's hard to say what's > left for the "logic" part to do. The logic part has the rules how you may move the pieces. The GUI shouldn't have to know how a knight, bishop, or queen can move or what castling is. > I can't think of any generalization for the fact that it's a 2D strategy > game. You could have a 2-dimensional array, the size of which is > determined by the GUI, No it isn't! The size is independent from the GUI. Most 2D strategy games have maps that are way large than the GUI displays at once. You almost always see just a portion of the model of the game world in the GUI. > but even motion on it would have to be defined by the GUI, in which case > the GUI would simply be using the "logic" part for storing the array and > accessing it via index values. And then there's no reason not to put > the array inside the GUI. There are plenty of reasons. You tie the game to one GUI this way. No way to change the GUI toolkit or to split the game into server (game logic) and client (different GUIs, web application). Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: ctypes help
On Thu, 22 May 2008 21:55:41 -0700, gianluca wrote: > Yes, I know it but when I load a function (a=myDLL.myFUNCT()) I've an > exception like this: > > Traceback (most recent call last): > File "", line 1, in > myDLL.myFUNCT() > File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ > func = self.__getitem__(name) > File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: function 'myFUNCT' not found Then maybe the DLL doesn't contain a function called `myFUNCT`. Any chance you compiled your C as C++ and name mangling kicked in? Can you show a minimal C source for a DLL, how you compiled it, what you did on the Python side to call it, and how it fails? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Relationship between GUI and logic?
On Thu, 22 May 2008 23:37:45 -0400, John Salerno wrote: > I know that it is good programming practice to keep GUI and logic code > physically separate, by using XRC for example, but I'm wondering if it's > also good practice (and even possible) to keep them separate from an > implementation standpoint as well. Basically what I mean is, should it > be possible to write, for example, the logic for a strategy game without > even knowing what the graphics will look like or how they will work? Yes, that's possible. > To be more specific, let's say I want to create a simple, 2D strategy > game. It will have a board layout like chess or checkers and the player > will move around the board. Let's say this is all I know, and perhaps I > don't even know *this* for sure either. Is it possible to write the > logic for such a game at this point? Maybe even this is possible. But here you are not only drawing the line between GUI and logic but also within the logic part itself because the board layout isn't (just) a GUI issue. If you have checkers, hexagons, or other shapes also has influence on the logic part, because you need slightly different algorithms for finding ways from tile `A` to tile `B`, or to decide when a piece is blocked by others, and how the rules to move pieces around look like. Just imagine how to modify chess rules to a board with hexagonal patterns. It would severely change the logic part. > Another example could be printing messages to the player. If I need to > say "You killed the monster!", is there a general way to write this, or > do I need to specifically refer to GUI widgets and methods, etc. in > order for it to be displayed properly? The observer pattern can be used here. The GUI has to register a callback function with your logic engine and every time you want to inform the player about something, your game logic calls that function with the message. It doesn't have to know if it will be rendered as graphic on screen, displayed as text in a terminal, or synthesized as sexy female computer voice. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: simple way to touch a file if it does not exist
On Wed, 21 May 2008 17:56:38 -0700, bukzor wrote: > On May 21, 5:37 pm, Nikhil <[EMAIL PROTECTED]> wrote: > >> if os.path.exists('file'): >> open('file', 'w').close() >> >> Right? > > You only want to blank it if it exists? If it doesn't exist you won't > create it. > The .close() is superlative: since you don't keep the value, it gets > deallocated and closed by the destructor. The language neither guarantees *when* an object will be deallocated nor that its destructor is called *at all*. It's cleaner to explicitly close the file. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: getting dir(x), but not as list of strings?
On Wed, 21 May 2008 07:54:32 +, mh wrote: > I want to iterate over members of a module, something like: > > for i in dir(x): > if type(i) == types.FunctionType: ... > > but of course dir() returns a list of strings. If x is a module, > how can I get the list of its members as their actual types? Take a look at the `inspect` module. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError: module object has no attribute
On Tue, 20 May 2008 23:31:15 +0530, Nikhil wrote: > Peter Otten wrote: >> Nikhil wrote: >> >>> I have recently written a small module. When I import the module, I >>> always get the error >>> >>> >>> only when I do >>> >>> >>> from local.my.module import * >>> >>> -- >>> Traceback (most recent call last): >>>File "", line 1, in >>> AttributeError: 'module' object has no attribute '/xyz/py/file' >>> --- >>> >>> >>> but when I do the below, I do not get any error. >>> >>> -- >>> >> import local.my.module >>> >> >>> -- >>> >>> Any ideas on what could be wrong? >> >> Are you abusing the __all__ attribute? >> >> $ cat tmp.py >> __all__ = ['/xyz/py/file'] >> >> $ python -c "from tmp import *" >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'module' object has no attribute '/xyz/py/file' >> > > Yes, I am. Is there any reason not to? That your module raises the `AttributeError` and is broke is not reason enough!? :-) > basically, since this is implemented in the module, I have to export it > since the caller to the function in the module is responsible for > ensuring he has enough proper permissions to read the file. What do you mean by "implemented in the module"? `__all__` is for names that live in the module's namespace -- '/xyz/py/file' isn't even a legal identifier name in Python! Ciao, Marc 'BlackJack' Rintsch. -- http://mail.python.org/mailman/listinfo/python-list
Re: scaling problems
On Tue, 20 May 2008 10:47:50 +1000, James A. Donald wrote: > 2. It is not clear to me how a python web application scales. Ask YouTube. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: scaling problems
On Tue, 20 May 2008 13:57:26 +1000, James A. Donald wrote: > The larger the program, the greater the likelihood of inadvertent name > collisions creating rare and irreproducible interactions between > different and supposedly independent parts of the program that each > work fine on their own, and supposedly cannot possibly interact. How should such collisions happen? You don't throw all your names into the same namespace!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Compress a string
On Tue, 20 May 2008 00:38:57 -0400, John Salerno wrote: > def compress(s): > new = [] > > for c in s: > if c not in new: > new.append(c) > return ''.join(new) > > > No, wait! I can do better! > > def compress(s): > new = [] > [new.append(c) for c in s if c not in new] return ''.join(new) > > Wow, list comprehensions are cool. And it's a misuse of list comprehension here IMHO because they are meant to build lists, not to cram a ``for``/``if`` loop into a one liner. You are building a list full of `None` objects, just to throw it away. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: this worked before...' '.join([`x x` for x in range(1, 6)])
On Mon, 19 May 2008 15:28:48 -0700, notnorwegian wrote: > ' '.join([`x x` for x in range(1, 6)]) > > anyone can tell me what im doing wrong? I doubt that this worked before because that's a syntax error: In [84]: ' '.join([`x x` for x in range(1, 6)]) File "", line 1 ' '.join([`x x` for x in range(1, 6)]) ^ : invalid syntax The backticks are syntactic sugar for the `repr()` function and ``repr(x x)`` isn't legal syntax either. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: test mult vars to same value, how to shorten expr?
On Mon, 19 May 2008 20:36:45 -0700, notnorwegian wrote: > if i want o test: > if a == 5 and b ==5 and c==5 ... z==5 > > is there some synctactic suagr for this? > > rather than maiking one of my own i mean, something built-in like: > if a,b,c... z == 5: Since Python 2.5 there's `all()`: In [81]: a, b, c, d = 5, 5, 5, 6 In [82]: all(x == 5 for x in (a, b, c)) Out[82]: True In [83]: all(x == 5 for x in (a, b, c, d)) Out[83]: False Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: conventions/requirements for 'is' vs '==', 'not vs '!=', etc
On Mon, 19 May 2008 12:39:36 -0700, destroy wrote: > I'm wondering what is the canonical usage of the keywords 'is' and > 'not' when you're writing conditionals and loops. The one I've been > following is completely arbitrary--I use the symbols '==', '!=' for > numerical comparisons and the words 'is', 'not' for everything else. That's wrong. Use ``==`` and ``!=`` for testing equality/inequality and ``is`` and ``is not`` for identity testing. And testing for identity is quite rare. Rule of thumb: Use it only for known singletons like `None`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
On Mon, 19 May 2008 00:14:25 -0700, sapsi wrote: > Yes, that could be the case. Browsing through hadoop's source, i see > stdin in the above code is reading from piped Java DataOutputStream. > I read of a libray on the net Javadata.py that reads this but it has > disappeared. > What is involved in reading from a Dataoutputstream? According to the Java docs of `DataInput` and `DataOutput` it is quite simple. Most methods just seem to write the necessary bytes for the primitive types except `writeUTF()` which prefixes the string data with length information. So if it is not Strings you are writing then "hadoop" seems to throw in some information into the stream. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
On Sun, 18 May 2008 22:11:33 -0700, sapsi wrote: > I am using HadoopStreaming using a BinaryInputStream. What this > basically does is send a stream of bytes ( the java type is : private > byte[] bytes) to my python program. > > I have done a test like this, > while 1: > x=sys.stdin.read(100) > if x: > print x > else: > break > > Now, the incoming data is binary(though mine is actually merely ascii > text) but the output is not what is expected. I expect for e.g > > all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 > 118.010.241.12 60370 128.210.5.176 > > However i get a 1 before all and a 4 just after \n and before the 6. > > My question is : how do i read binary data(Java's byte stream) from > stdin? > Or is this actually what i'm getting? If there's extra data in `x` then it was sent to stdin. Maybe there's some extra information like string length, Java type information, or checksums encoded in that data!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: morning in Python
On Sun, 18 May 2008 11:15:06 +0200, Martin v. Löwis wrote: >> Full day later, I think it, to emphasize state, would prioritize >> context. The reason for the huge ramble was, believe it or not, >> namespace conflict... as though any other states around here might >> nose in. > > I think the namespace conflict is rather in cities than in states. > For example, there are several cities called "Berlin", but only > one state (that I know of) is called "Mecklenburg-Vorpommern". > In some cases, prefixing helps, e.g. you don't call it "York" > when that already exists, but "New York". The state or the city "New York"!? And wasn't the city object bound to the name "New Amsterdam" once? :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Classmethods are evil
On Sat, 17 May 2008 04:01:50 +, Ivan Illarionov wrote: > After re-reading "Python is not Java" I finally came to conclusion that > classmethods in Python are a very Bad Thing. > > I can't see any use-case of them that couldn't be re-written more clearly > with methods of metaclass or plain functions. *The* use case IMHO are alternative constructors. They belong to the class, so functions are not as clear and it's possible to have more than one class in a module with class methods of the same name, e.g. `A.from_string()` and `B.from_string()` vs. `create_a_from_string()` and `create_b_from_string()`. And I don't see how functions can be inherited by sub classes like class methods can. Metaclasses are more clear than class methods? You must be joking!? > They have the following issues: > 1. You mix instance-level and class-level functionality in one place > making your code a mess. Writing meta classes just for alternative constructors seems to be more of a mess to me. Too much magic for such a simple case for my taste. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: no inputstream?
On Thu, 15 May 2008 06:08:35 -0700, max wrote: > i currently have locations of the mp3s in question as strings, which > works for parsing local files, but gives me a "No such file or > directory" error when it tries to process URLs. it seems terribly > inefficient to download each mp3 just to get at that small tag data, > and i assume there's a way to do this with file() or open() or > something, i just can't get it to work. You can use `urllib2.urlopen()` to open URLs as files. But if you deal with ID3 V1 tags you'll have to download the file anyway because those are in the last 128 bytes of an MP3 file. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Is using range() in for loops really Pythonic?
On Tue, 13 May 2008 10:20:41 -0700, John Nagle wrote: > Matt Nordhoff wrote: > >> Well, you should use "xrange(10)" instead of "range(10)". > >CPython really is naive. That sort of thing should be a > compile-time optimization. It's not naive, it can't know at compile time what object is bound to the name `xrange` at runtime. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Literate programs in Python
On Tue, 13 May 2008 08:28:00 -0700, Paul Miller wrote: > Alternatively, does anyone know of any literate programming tools which > support Python well? There's PyLit_. It uses reStructuredText_ and can translate between a reStructuredText with code blocks and source code with the text as comments in both directions. .. _PyLit: http://pylit.berlios.de/ .. _reStructuredText: http://docutils.sourceforge.net/ Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Backslash frowned upon?
On Tue, 13 May 2008 03:25:06 -0700, wxPythoner wrote: > Why is the \ backslash character frowned upon? Is it frowned upon? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Is using range() in for loops really Pythonic?
On Mon, 12 May 2008 11:23:07 -0700, Carl Banks wrote: > On May 12, 3:42 am, Ben Finney <[EMAIL PROTECTED]> > wrote: >> Because of the precedent of those names, choosing one of those names >> doesn't make it clear to the reader that the value is never used; > > > Why is it even necessary to document this? This is the thing that > baffles me the most about this thread. I do it (with a "special" name) because static source checkers issue a warning for unused variables. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
On Tue, 13 May 2008 03:25:51 +, Yves Dorfsman wrote: > Marc 'BlackJack' Rintsch wrote: >>>>y, _, d, _, _, _, _, _, _ = time.localtime() >>> But you still have have a variable that's using memory for nothing. I >>> find this unsatisfactory... >> >> Get over it… > > Than what's the point of wanting a better language if every time we run in > something that looks wrong, or something that could be done better we should > just "get over it" ? That advice wasn't for every time something looks wrong but this particular one. You can solve it with `operator.itemgetter()` but that means importing another module and calling a function which looks much more "heavy weight" to me than one reference to an unused object which might go away at the end of the function anyway soon. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: anonymous assignment
On Mon, 12 May 2008 03:40:03 +, Yves Dorfsman wrote: > Paul Rubin wrote: > >> You can just use a variable name than you ignore. It's traditional to >> use _ but it's not a special keyword, it's just a another variable >> name: >> >>y, _, d, _, _, _, _, _, _ = time.localtime() > > But you still have have a variable that's using memory for nothing. I > find this unsatisfactory... Get over it… Or use `operator.itemgetter()`: In [36]: operator.itemgetter(0, 2)(time.localtime()) Out[36]: (2008, 12) :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Some error messages in Python are ugly
On Sun, 11 May 2008 01:10:19 -0700, wxPythoner wrote: > This really looks ugly for an error message: > > [1]+ Stopped python It's neither an error message nor does it come from Python. It's a message from your shell about job control. Seems you have stopped the running process, which happens to be Python, by pressing + or - for example. > Please explain to me the role of the '+' sign. Refer to the manual of your shell. I guess it says, that the stopped process was/is the current job, i.e. the one commands like ``fg`` or ``bg`` operate on if you leave out the argument. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: People still using Tkinter?
On Sat, 10 May 2008 00:20:33 -0500, Kenneth McDonald wrote: > Any guesses as to how many people are still using Tkinter? And can > anyone direct me to good, current docs for Tkinter? AFAIK `Tkinter` hasn't changed much over time, so "old" documentation is still current. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: the lvalue curse? let's play with this crazy idea ;)
On Fri, 09 May 2008 02:13:34 -0700, XLiIV wrote: > Let's take a look at two ways of thinking... > the standard one which is well-known and loved by almost everyone :) > and that crazy concept below which suprised evan me :wacko: > > > import time > > ftime = time.time() > localtime = time.localtime(ftime) > localtime = list(localtime[:3]) > localtime = [str(i) for i in localtime] > print '-'.join(localtime) > > > It's harder to read than the below concept, isn't? > Maybe I didn't used to this way of thinking yet. I hope it'll change > soon or i'll quit ;) Maybe it's also harder to read than this:: print '-'.join(map(str, time.localtime()[:3])) Of course, if you don't mind the extra padding zeroes in day and month:: print time.strftime('%Y-%m-%d') > > time.time() -> ftime -> time.localtime() -> p -> p[:3] -> g -> list(g) > -> '-'.join() > You are a little bit inconsistent with the arguments. `g` is explicitly mentioned in ``list(g)``. But why the intermediate names at all? > My example conclusion and not-ansewered-yet question... > -it's nice to read and choosing the good names to variables aren't so > important > -what is the purpose of the variables here? :) Exactly. But look at my snippet above: No intermediate names either. > I realize that there is no chance to implement it, but I really want > to share it :] Maybe you should look into languages like SmallTalk or Io where everything is done with method calls. Your example in Io:: Date now do("#{year}-#{month}-#{day}" interpolate linePrint) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle problem
On Thu, 08 May 2008 23:35:04 +0200, Hrvoje Niksic wrote: > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes: > >> On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: >> >>> The thing is, I'm not using slots by choice. I'm using the standard >>> lib "socket" class, which apparently uses slots. >> >> `socket` objects can't be pickled. Not just because of the >> `__slot__`\s but because a substantial part of their state lives in >> the operating system's space. > > Of course, if it makes sense to pickle sockets in the application, one > is can do so by defining __getstate__ and __setstate__: When does it make sense!? > class Connection(object): > def __init__(self, host, port): > self.host = host > self.port = port > self.init_sock() > > def init_sock(self): > self.sock = socket.socket() > self.sock.connect((host, port)) > ... init communication ... But if you unpickle it while the original connection is still open it can't connect. If it's not open anymore, there's no one answering at host/port anymore or some program that has no idea what this connection is all about. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle problem
On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: > The thing is, I'm not using slots by choice. I'm using the standard > lib "socket" class, which apparently uses slots. `socket` objects can't be pickled. Not just because of the `__slot__`\s but because a substantial part of their state lives in the operating system's space. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie to python --- why should i learn !
On Thu, 08 May 2008 15:49:01 +0200, pistacchio wrote: > Marc 'BlackJack' Rintsch ha scritto: >> On Thu, 08 May 2008 04:17:01 -0700, s0suk3 wrote: >> >>> Are you a newbie to Python, or to programming in general? I'll assume >>> you are a newbie to programming in general because of that last >>> question you asked. Things in Python are easier than in almost any >>> other programming language. Here are three Hello World programs: >> >> Counterexamples for quite short "greetings" in other programming languages: >> >> (Free)BASIC:: >> >> Print "Hello World!" > > freebasic is another language i'd point out to a newbie, even if it is > not as multiplatform as python if. it has a decent community and a large > amount of libraries. it doesn't let you explore functional or, worse, > object oriented programming nor you can write server side programs with > it. OOP support is under development and why can't you write "server side programs" in it? CGI is possible. > The others are examples of easy "hello world" languages, but, passed > that, i think they don't have the same capabilities of python on terms > of support, kind of programs you can write and even overall complexity > (haskell forces you to functional programming, io is really a minor > language, ocalm forces you to di OOP and, if writing hello world is > simple, on the other hand ir may have lines of code that read like: > > | [] -> [] Okay, Haskell's pure functional approach feels somewhat "weird". Io is a minor language but a quite nice one IMHO. Simple syntax and relatively simple semantics but very powerful. OCaml doesn't enforce OOP. It's some kind of "mirror" of Python. Python is an OOP language with support for functional programming, and OCaml is a functional language with support for OOP. The biggest pro for Python among the easy and clear syntax languages is the standard library and the amount of third party modules. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie to python --- why should i learn !
On Thu, 08 May 2008 04:17:01 -0700, s0suk3 wrote: > Are you a newbie to Python, or to programming in general? I'll assume > you are a newbie to programming in general because of that last > question you asked. Things in Python are easier than in almost any > other programming language. Here are three Hello World programs: Counterexamples for quite short "greetings" in other programming languages: (Free)BASIC:: Print "Hello World!" OCaml:: print_string "Hello World!" ;; Io:: "Hello World!" linePrint Haskell:: main = putStrLn "Hello World!" Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Truncate beginning of a file
On Sun, 04 May 2008 22:06:42 -0700, s0suk3 wrote: > file.truncate(X) will truncate the file to at most X bytes (i.e. leave > the first X bytes of the file and throw away the rest). Is there a way > to throw away, say, the first X bytes of the file, and leave the rest? > (Without opening the same file for reading, reading and processing, > overwriting the file with the new processed data, etc.) No. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: generator functions in another language
On Sat, 03 May 2008 16:39:43 -0700, castironpi wrote: > I'm actually curious if there's a way to write a generator function > (not a generator expression) in C, or what the simplest way to do it > is... besides link the Python run-time. The reference implementation of Python is written in C, so obviously there must be a way to write something like generators in C. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame: rect moveto?
On Sat, 03 May 2008 09:51:06 -0700, globalrev wrote: > http://www.pygame.org/docs/ref/rect.html#Rect.move > > well i need to put my rect ina specific place and i donw know from > where i will move it so i need a function rect.moveTo(x,y). > > how do i do that? No need for a function or method:: rect.topleft = (x, y) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: is +=1 thread safe
On Fri, 02 May 2008 19:23:54 +0100, Arnaud Delobelle wrote: > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes: > >> >> There are no modern processors with an opcode for incrementing a memory >> location!? At least my C64 can do that. ;-) > > Indeed! I remember a simple use was to make the border change colour > very fast, a v. cool effect when you're 12! > > CLV > LOOP: INC $D020 > BVC LOOP > > (from memory, untested!) That works but I think LOOP: INC $D020 JMP LOOP is a bit more straight forward. Shorter in opcodes, equal in bytes, the loop is as fast but you save the two cycles of the CLV. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: creating a list from a inconsistent text file
On Fri, 02 May 2008 04:14:47 -0700, Jetus wrote: > I have a comma delimited file that is separated by comma's, and then > sometimes by "," > > c:\temp\05-06-08\Sale1,659 CECIL,"659 CECIL,40211", > 1,659,CECIL,AVENUE,LOUISVILLE,40211,"$65,276.78 " > c:\temp\05-06-08\Sale2,637 SOUTH 27TH,"637 SOUTH 27TH,40211", > 2,637,SOUTH 27TH,STREET,LOUISVILLE,40211,"$45,456.95 " > c:\temp\05-06-08\Sale3,2709 ELLIOT,"2709 ELLIOT,40211", > 3,2709,ELLIOT,AVENUE,LOUISVILLE,40211,"$49,349.66 " The items are always delimited by commas but some items themselves contain a comma and therefore are enclosed in double quotes. So it's not inconsistent. > How do I convert that line into a list? Use the `csv` module in the standard library. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: get number that is raised to the power of
On Fri, 02 May 2008 19:19:07 +1000, Astan Chee wrote: > Hi, > Im not sure if this is more of a math question or a python question. I > have a variable in python: > >>> v = 10.0**n > is there a way to find the value of n if i know only v aside from > str(v).split('+')[1] ? that seems like too much of a hack and I was > wondering if there was a faster way of doing it? That hack isn't even working properly because ``str(10.0**1)`` has no '+' in its string representation. Solution: n = math.log(v, 10) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: is +=1 thread safe
On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote: > Of course it's not thread safe. For the same reason and more basic, > even the expression i++ is not thread safe in C++. > > Any such calculation, on modern processors, requires three operations: > retrieve value of i into a register, > increment the register > write the value into i. There are no modern processors with an opcode for incrementing a memory location!? At least my C64 can do that. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: no cleanup on TERM signal
On Fri, 02 May 2008 04:36:06 +, Yves Dorfsman wrote: > x.del() gets executed if: > -I del x, then run gc.collect() > -simply exit the script > -get the script to abort on an exception > > But if I kill it with the default signal TERM, the script dies, but I don't > get the message, so I am assuming that python isn't taking the time to > cleanup, even though that is (was) what TERM was intended for. > > Has this been discussed before ? Is worth a suggestion (PEP) ? There is the docs for `__del__()` saying this method is not guaranteed to be called at all. Don't use it if you *need* that method to be called. Just like `finalize()` in Java, it can't be used for deterministic destruction, so it's not that useful after all. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: computing with characters
On Wed, 30 Apr 2008 13:12:05 +0200, Torsten Bronger wrote: > However, join() is really bizarre. The list rather than the > separator should be the leading actor. You mean any iterable should be the leading actor, bacause `str.join()` works with any iterable. And that's why it is implemented *once* on string and unicode objects. Okay that's twice. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help on left padding
On Mon, 28 Apr 2008 04:37:02 -0700, rajesh kataraki wrote: > My requirement is I am using one variable ex. var = 5 which is > integer. > And this variable, I m using in some string. But I want this var > to be used as 005 again integer in this string. In [22]: '%03d' % 5 Out[22]: '005' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: removing extension
On Sun, 27 Apr 2008 15:06:54 +, Matt Nordhoff wrote: > Arnaud Delobelle wrote: >> More simply, use the rsplit() method of strings: >> >>>>> path = r'C:\myimages\imageone.jpg' >>>>> path.rsplit('.', 1) >> ['C:\\myimages\\imageone', 'jpg'] >> >> >>>>> path = r"C:\blahblah.blah\images.20.jpg" >>>>> path.rsplit('.', 1) >> ['C:\\blahblah.blah\\images.20', 'jpg'] >> >> HTH > > There's os.path.splitext(), which probably does just about exactly that. Not exactly. In the case of no extension `os.path.splitext()` still works: In [14]: 'foo/bar.txt'.rsplit('.') Out[14]: ['foo/bar', 'txt'] In [15]: 'foo/bar'.rsplit('.') Out[15]: ['foo/bar'] In [16]: os.path.splitext('foo/bar') Out[16]: ('foo/bar', '') Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: convert images
On Sun, 27 Apr 2008 06:42:13 -0700, wilson wrote: > i converted some P5 type .pgm images to .jpg using > […] > ie if oldimage.pgm has pixels > [29 31 38 ..., 10 4 18] > then the corresponding jpg image has > [29 31 38 ..., 10 3 17] > > why this difference? shouldn't they be identical?can someone pls > explain this? JPEG uses a lossy compression algorithm, i.e. the image loses quality and therefore the pixel values are not exactly the same as before saving. If you want get the exact values back you have to use another image format. For RGB or RGBA data PNG is a good format. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: diffing and uniqing directories
On Sat, 26 Apr 2008 20:35:29 -0700, rustom wrote: > On Apr 27, 12:31 am, [EMAIL PROTECTED] wrote: >> On Apr 26, 1:14 pm, "Rustom Mody" <[EMAIL PROTECTED]> wrote: >> […] > > If this is an answer to my question I dont understand it! castironpi is either a bot or trolling. Just ignore its posts. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting an attribute without calling __setattr__()
On Sat, 26 Apr 2008 08:28:38 -0700, animalMutha wrote: >> Consider reading the *second* paragraph about __setattr__ in section >> 3.4.2 of the Python Reference Manual. > > if you are simply going to answer rtfm - might as well kept it to > yourself. Yes, but if you are telling where exactly to find the wanted information in the documentation, like John did, you are teaching the OP how to fish. Which is a good thing. Much more helpful than your remark anyway. You might as well have kept it to yourself. :-þ Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Little novice program written in Python
On Fri, 25 Apr 2008 10:24:16 +0200, Robert Bossy wrote: > John Machin wrote: >> On Apr 25, 5:44 pm, Robert Bossy <[EMAIL PROTECTED]> wrote: >> >>> Peter Otten wrote: >>> If the OP insists in not examining a[0] and a[1], this will do exactly >>> the same as the while version: >>> >>> for p in a[2:]: >>> if p: >>> print p >>> >>> >> >> ... at the cost of almost doubling the amount of memory required. > Indeed. Would it be a sensible proposal that sequence slices should > return an iterator instead of a list? I don't think so as that would break tons of code that relies on the current behavior. Take a look at `itertools.islice()` if you want/need an iterator. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using copy.copy with my own class
On Tue, 22 Apr 2008 11:13:43 -0600, Jeffrey Barish wrote: > By the way, I have simplified somewhat the code in the explanation. Please simplify the code to a minimal example that still has the problem and *show it to us*. It's hard to spot errors in code that nobody except you knows. -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditional for...in failing with utf-8, Spanish book translation
On Mon, 21 Apr 2008 08:33:47 +0200, Hunter wrote: > I've narrowed the problem down to a simple test program. Check this out: > > --- > > # -*- coding: utf-8 -*- > > acceptable = "abcdefghijklmnopqrstuvwxyzóíñú" # this line will work > acceptable = "abcdefghijklmnopqrstuvwxyzóíñúá" # this line won't > #wtf? > > word = "¡A" > word_key = ''.join([c for c in word.lower() if c in acceptable]) > print "word_key = " + word_key > > --- > > Any ideas? I'm really stumped! You are not working with unicode but UTF-8 encoded characters. That's bytes and not letters/characters. Your `word` for example contains three bytes and not the two characters you think it contains: In [43]: word = "¡A" In [44]: len(word) Out[44]: 3 In [45]: for c in word: print repr(c) : '\xc2' '\xa1' 'A' So you are *not* testing if ¡ is in `acceptable` but the two byte values that are the UTF-8 representation of that character. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: "Help needed - I don't understand how Python manages memory"
On Sun, 20 Apr 2008 22:46:37 +1000, Hank @ITGroup wrote: > Apology for the previous offensive title~~ > :) > Thanks, Rintsch, Arnaud and Daniel, for replying so soon. > > I redid the experiment. What following is the record - > > ``starting python``# == Windows Task Manager: > Python.exe *4,076 *K memory-usage == > >>> st1='abcdefg'*99 # == 10,952 K == > >>> del st1 # == *4,104*K == > >>> st1='abcdefg'*99 # == 10,952 K == > >>> del st1 # == 4,104 K == > > >>> li = ['abcde']*99 # == 8,024 K == > >>> del li# == *4,108* K == > > >>> from nltk import FreqDist # == 17,596 == > >>> fd = FreqDist()# == 17,596 == > >>> for i in range(99):fd.inc(i) # == 53,412 == > >>> del fd # == *28,780* == > >>> fd2 = FreqDist() # == 28,780 == > >>> for i in range(99):fd2.inc(i) # == 53,412 == > >>> del fd2# == 28,780 K == > > >>> def foo(): > ... fd3 = FreqDist() > ... for i in range(99):fd3.inc(i) > > >>> foo() # == *28,788* K == > > >>> def bar(): > ... fd4 = FreqDist() > ... for i in range(99):fd4.inc(i) > ... del fd4 > # == 28,788 K == > >>> bar() # == 28,788 K == > > > That is my question, after ``del``, sometimes the memory space returns > back as nothing happened, sometimes not... ... > What exactly was happening??? Something. Really it's a bit complex and implementation dependent. Stop worrying about it until it really becomes a problem. First of all there's no guarantee that memory will be reported as free by the OS because it is up to the C runtime library if it "gives back" freed memory to the OS or not. Second the memory management of Python involves "arenas" of objects that only get freed when all objects in it are freed. Third some types and ranges of objects get special treatment as integers that are allocated, some even preallocated and never freed again. All this is done to speed things up because allocating and deallocating loads of small objects is an expensive operation. Bottom line: let the Python runtime manage the memory and forget about the ``del`` keyword. It is very seldom used in Python and if used then to delete a reference from a container and not "bare" names. In your `bar()` function it is completely unnecessary for example because the name `fd4` disappears right after that line anyway. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: ???Python Memory Management S***s???
On Sun, 20 Apr 2008 18:40:26 +1000, Hank @ITGroup wrote: > In order to evaluate the memory operation, I used the codes below: > > """ > > string1 = ['abcde']*99# this took up an obvious memory space... > > del string1 # this freed the memory > successfully !! Indirectly. ``del`` does not delete objects but just names, so you deleted the name `string1` and then the garbage collector kicked in and freed the list object as it was not reachable by other references anymore. > """ > For primary variants, the *del* thing works well. However, challenge the > following codes, using class-instances... > > """ > > from nltk import FreqDist # nltk stands for Natural Language Tool > Kit (this is not an advertisement ~_~) > > instance = FreqDist() > > instanceList = [instance]*9 > > del instanceList # You can try: nothing is freed by this > """ How do you know this? And did you spot the difference between 99 and 9!? Are you aware that both lists contain many references to a *single* object, so the memory consumption has very little to do with the type of object you put into the list? In the second case you still hold a reference to that single instance though. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Wed, 16 Apr 2008 12:32:00 -0700, Aaron Watters wrote: >> > Perhaps this will inspire improved linters and better coding >> > practices >> >> Better coding practices such as extensive unit tests? > > Greetings from Earth. What planet are you from? :) > > There is always the possibility that frustrated > programmers will decide that "using something other > than python" is a "better coding practice". I've seen > it happen. So the average quality of Python coders raises. Cool. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: vary number of loops
On Wed, 16 Apr 2008 06:31:04 -0700, nullgraph wrote: > I'm new to Python and the notion of lambda, and I'm trying to write a > function that would have a varying number of nested for loops > depending on parameter n. This just smells like a job for lambda for > me, but I can't figure out how to do it. Any hint? That has nothing to do with ``lambda``. If you don't think "Hey, that's smells like a job for a function." then it's no job for ``lambda``, which is just a way to define a function without automatically binding it to a name like ``def`` does. One solution to your problem is recursion. Untested: def foo(xs): if xs: for elt in xs[0]: for ys in foo(xs[1:]): yield [elt] + ys else: yield [] Called as ``foo([A, B])``. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Java or C++?
On Mon, 14 Apr 2008 00:49:13 -0700, xakee wrote: > Well if you need an easier transition, go for java. But personally i > would recommend you to go for C/C++. What's that C/C++!? C and C++ are quite different languages. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Game design : Making computer play
On Mon, 14 Apr 2008 00:13:56 -0700, v4vijayakumar wrote: > In computer based, two player, board games, how to make computer play? > Are there any formal ways to _teach_ computer, to choose best possible > move? That depends on the type of the game. For a certain class of games one can use the `minimax method`_ for instance. .. _minimax method: http://en.wikipedia.org/wiki/Minimax Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, image not appearing in function but without function
On Sun, 13 Apr 2008 08:57:29 -0700, skanemupp wrote: > why is the first program not working? when i click the screen the map > is not appearing. > > the second program works. > > > > from Tkinter import * > > master = Tk() > > w = Canvas(master, width=700, height=600) > w.pack(expand = YES, fill = BOTH) > > def mapper(): > mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\world-map.gif') > w.create_image(10, 10, image = mapq, anchor = NW) > > def key(event): > print "pressed", repr(event.char) > > def callback(event): > w.focus_set() > print "clicked at", event.x, event.y > mapper() > print 'yo' > square = w.create_oval(event.x-5,event.y-5,event.x+5,event.y+5, > fill="black") > > w.bind("", key) > w.bind("", callback) > w.pack() > > > mainloop() Python doesn't know that the Tk side still needs the image and frees the memory when `mapper()` is done and `mapq` the only name to the `PhotoImage` instance goes out of scope. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Choose an Unlimited Web Hosting for free
On Sun, 13 Apr 2008 08:42:52 -0700, John Nagle wrote: > Unlimited Free Domain & Web Hosting wrote: >> How to Choose an Unlimited Web Hosting >> 1) Visit www.xxx.com to get domain and hosting >> 2) Unlimited Bandwidth ,this mean unlimited data transmission for your >> client access. >> 2) Unlimited Space , you can upload file for unlimited . >> 3) Unlimited Email , many of email account can created . >> 5) SSL Security , used SSL / HTTPS to protect your web . >> 6) LINUX , WINDOWS and MAC , can access form many operating system. > > This is some spamming "reseller" for Xxxx Hosting. And now you've spread the spam to those whose news servers filtered the original message. Thanks... Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter, overwrite Label-text?
On Thu, 10 Apr 2008 07:37:08 -0700, skanemupp wrote: > i know how to do this already. the problem is i want the text to stay > in the windowa nd not start overwriting "Answer:". Then don't use `place()` but let Tkinter handle the layout with the pack and/or grid layout manager. GUIs with `place()` are a bad idea because the GUI may look odd or is even unusable on other peoples computers with other screen resolutions, fonts, and font sizes. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: PROBLEMS WITH PYTHON IN SOME VARIABLE,FUNCTIONS,ETC.
On Wed, 09 Apr 2008 16:16:14 +0200, Diez B. Roggisch wrote: > And then you reply telling us about the greatness of Bangalore and your > product to come. Which is somewhat amusing that people who claim to produce > the greatest software being incapable of debugging it deems me as odd - to > say the least. That's not odd, that's perfectly normal for really clever code: Debugging is twice as hard as writing the code in the first place.Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: I am worried about Python 3
On Wed, 09 Apr 2008 05:04:20 -0700, jmDesktop wrote: > If I continue in Python 2.5.x, am I making a mistake? Is it really > that different? No it's still Python and most things you've learned with 2.x stay the same. > Here is an excerpt that is causing me concern: > > Two new versions of the language are currently in development: version > 2.6, which retains backwards compatibility with previous releases; and > version 3.0, which breaks backwards compatibility to the extent that > even that simplest of programs, the classic 'Hello, World', will no > longer work in its current form. Sounds a bit like FUD. While it's true that the classic greeting will break because the ``print`` statement turned into a `print()` function, it's not a ground shaking change that makes all knowledge about 2.x obsolete or radically changes the look of Python programs. Old:: print 'Hello World' New:: print('Hello World') There will be a `2to3.py` program coming with Python 2.6 that tries to convert most changes automatically. You may have to change the 2.6 code in a way that makes the automatic conversion possible but it is a important goal for the Python developers to make the transition as smooth as possible as far as I can tell. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, add pressed buttons onto string display string, how to?
On Sat, 05 Apr 2008 13:17:45 -0700, skanemupp wrote: >> input = "hello" >> input += " world" >> print input > > this i know. im wondering how to handle the variable in the actual > program. this exception i get: > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__ > return self.func(*args) > File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py", > line 48, in > self.btnDisplay = Button(self,text='+',command=lambda > n="+":self.Display(n),width=1,height=1) > File "C:\Users\saftarn\Desktop\guiexperiments\calculatorGUI.py", > line 92, in Display > str = number + str > UnboundLocalError: local variable 'str' referenced before assignment Just like the message says: You are trying to use `str` (on the right hand side of the assignment) before anything is bound to that name. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: making buttons the same size?
On Sat, 05 Apr 2008 10:04:56 -0700, skanemupp wrote: > how do i do that? Please include enough from the post you are answering to make the context clear for someone who has not received the previous message. BTW I don't think the `width` argument of the `Button()` call is the best solution. Take a look at the options of the `grid()` call and figure out how to tell that the content of the cell should fill it, so that the Buttons in the grid automatically are equally sized in each row and column. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!
On Fri, 04 Apr 2008 20:26:13 -0700, 7stud wrote: > However, there is another way to cause a function to execute when an > event, like a button click, occurs on a widget: you use the widget's > bind() function: > > my_button.bind('', someFunc) That's a bad idea because now the `Button` doesn't act like a typical button anymore. This "fires" *always* and as soon as you press the mouse button on it. Compare this with the usual and from end users point of view expected behavior that pressing down the mouse button "presses" the button widget visually but doesn't cause any action until you release the button while still over it. This for instance makes it possible to change your mind and move the mouse cursor out of the buttons area with a pressed mouse button and prevent the action of that button. The preferred way to bind actions to `Button`\s is the `command` argument. The function is called with no arguments when the button is pressed, so it has to know all data it needs to fulfill its task. Usually this is done with anonymous functions and bound default values for short pieces of "variable" data:: def __init__(self): # ... button = Button(self, text='1', command=lambda n=1: self.display(n)) # ... def display(self, number): print number Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Prototype OO
On Thu, 03 Apr 2008 10:07:38 +0200, sam wrote: > [EMAIL PROTECTED] napisał(a): > > >> So, while I often use Python's lambdas, the imposed limitations is ok >> to me since I wouldn't use it for anything more complex. > >> Also - as a side note - while the syntax is a bit different, the >> resulting object is an ordinary function. > > And people start asking why this is that or the other way in Python, and you > can't give a good answer to newcomers, especially if Python was chosen as a > first learning language. You can't tell "because Python's parsing mechanism > don't allow statements in expressions...". But one can tell "because the way Python's syntax is based on indentation, no one has come up with a syntax for anonymous functions without the limitations of the current ``lambda``, that doesn't need 'curly braces' and is still as readable as Python is now." Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: non-terminating regex match
On Wed, 02 Apr 2008 16:01:59 +, Maurizio Vitale wrote: > And yes, I'm a total beginner when it comes to Python, but it seems > very strange to me that a regex match on a finite length string > doesn't terminate It does terminate, you just don't wait long enough. Try it with fewer characters and then increase the identifier character by character and watch the time of the runs grow exponentially. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding bmp image files
On Wed, 02 Apr 2008 10:51:39 -0700, pranav wrote: > I want to read a BMP file, do some processing and then write it in a > new file. The problem is in the third step. For reading the file, i > have converted the file into decimal numbers, representing the pixel > values. You have converted the data into numbers, not "decimal" numbers. > Then i perform calculations on those decimal numbers. Now i am > unable to convert those into the format as required by the "bmp" file. > Any one, who is into image reading/manipulation, please help. How have you converted the bytes into numbers and why can't you reverse that step? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Homework help
On Tue, 01 Apr 2008 09:11:12 -0700, bobby.connor wrote: > # (2 Points) Write a python function howMany(item,lst) which accepts > an item and a lst of items and returns the number of times item occurs > in lst. For example, howMany(3,[1,2,3,2,3]) should return 2. Study the methods on lists. > # (2 Points) Write a python function upTo(n) which accepts a non- > negative number n and returns a list of numbers from 0 to n. For > example, upTo(3) should return the list [0, 1, 2, 3]. Study the built in functions. I don't know if it is considered cheating but you can get away with binding an existing one to the new name. > # (2 Points) Write a python function dotProduct(a,b) which accepts two > lists of integers a and b that are of equal length and which returns > the dot product of a and b. I.e., the sum a0 * b0 + ... + an-1 * bn-1 > where n is the length of the lists. For example: > > dotProduct([1,2,3],[4,5,6]) is 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32 Again study the built in functions. Here the function from the `zip()` exercise below might be handy. > # (2 Points) A pair (exp0, exp1) is a combination of expressions that > are attached together by their joint membership in the pair. For > example: > >>>> (1+2, 'This') > (3, 'This') > > A component of a pair can be obtained using an index in brackets as > with lists (and strings!). For example: > >>>> (33,44)[0] > 33 And the exercise to solve is!? Study the built in data types. > Write a function zip(lst1, lst2) such that zip accepts two equal > length lists and returns a list of pairs. For example, zip(['a', 'b', > 'c'], [10, 20, 30]) should evaluate to the list [('a', 10), ('b', 20), > ('c', 30)]. Hey not even a rebinding necessary. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line input
On Mon, 31 Mar 2008 12:39:54 -0700, hexusnexus wrote: > How do I receive input from the command line in Python? Direct way `sys.argv`, comfortable way `optparse`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] troll poll
On Mon, 31 Mar 2008 10:04:31 -0700, Daniel Fetchinson wrote: > [Heavily off-topic fun stuff] > > This is a quick poll to have scientific data on our beloved troll community: > > Whose trolling behaviour is more professional? (check one) > > [X] - Xah Lee > [ ] - castironpi He dedicates some time to write up at least comprehensible postings that make *some* sense. > More specifically, who can create a bigger mess on c.l.py? (check one) > > [ ] - Xah Lee > [X] - castironpi Xah Lee's postings might be trolls but sometimes they spark some really interesting and serious subthreads, while the nonsense of castironpi is just irritating noise. > More specifically, who is more entertaining? (check one or none) > > [X] - Xah Lee > [ ] - castironpi Castironpibot becomes boring very quickly. Especially when it starts to answer its own posts. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: standard input, for s in f, and buffering
On Sun, 30 Mar 2008 21:02:44 +, Jorgen Grahn wrote: > I realize this has to do with the extra read-ahead buffering documented for > file.next() and that I can work around it by using file.readline() > instead. > > The problem is, "for s in f" is the elegant way of reading files line > by line. With readline(), I need a much uglier loop. I cannot find a > better one than this: > > while 1: > s = sys.stdin.readline() > if not s: break > print '', s , > > And also, "for s in f" works on any iterator f -- so I have to choose > between two evils: an ugly, non-idiomatic and limiting loop, or one > which works well until it is used interactively. > > Is there a way around this? Or are the savings in execution time or > I/O so large that everyone is willing to tolerate this bug? You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline, '')`` as iterable for `lines`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: question
On Sun, 30 Mar 2008 20:34:30 -0400, Steve Holden wrote: > [EMAIL PROTECTED] wrote: >> Presume. Silence first, then a broken triad vamps. How long til you >> recognize it? One sec., i'll attach a binary. > > Good grief, is this idibot still around? > > [leaves c.l.py for another month] Oh come on, don't let you scare away so easily. Put him in the filter list of your news client. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner advice
On Mon, 31 Mar 2008 07:23:00 +0200, Paul Scott wrote: > 3. pyXMLRPClib - active? Something better? There is an `xmlrpclib` in the standard library, so there is no need for an external package here. I even think that pyXMLRPClib is the one that's integrated in the standard library, so the external one might be "dead". > 4. I see that there are literally thousands of somewhat external looking > libraries for python, I presume that there is some way of bundling all > the deps into a single source and then compiling? or otherwise packaging > them all (this software will be for academia, so difficult installs are > out!) For Windows there are tools to bundle your source and all dependencies and even the interpreter itself. `py2exe` is such a tool. With InnoSetup or NSIS or similar programs you can then make a `setup.exe` for that spoiled Windows brats. :-) Under Linux many packages are available as distribution specific packages on most distributions. So for Linux you may get away with a README stating the dependencies of your program and a `setup.py` for installing your project. Look for `distutils` in the Python documentation for further information about `setup.py`\s. > 5. Editor - I am using Eric (which I quite like), any advice on IDE's? Use the one you like best. ;-) Many don't use an IDE but simply their favorite text editor. I'm happy with syntax highlighting, automatic indentation support for Python source code, and completion based on the content of open file(s) -- almost all serious editors have those features. And there's always an IPython console running to test small pieces of code. > All Email originating from UWC is covered by disclaimer > http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm Hey, that's a nice way to have a *short* stupid disclaimer. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: case insensitive lstrip function?
On Fri, 28 Mar 2008 15:48:09 -0700, Kelie wrote: > Is there such a function included in the standard Python distribution? AFAIK not. > This is what I came up with. How to improve it? Thanks. > > def lstrip2(s, chars, ingoreCase = True): > if ingoreCase: > s2 = s.upper().lstrip(chars.upper()) > return s[len(s)-len(s2):] > else: > return s.lstrip(chars) What about this: def lstrip2(string, chars, ignore_case=True): if ignore_case: chars = chars.lower() + chars.upper() return string.lstrip(chars) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with format string and unicode
On Fri, 28 Mar 2008 21:13:00 +0100, Hans Martin wrote: > this is probably a trivial problem, but a google search for "python" > and "unicode" and" format string" gives too many hits: If I specify > e.g. "%20s" in a format string and the string value contains UTF-8 > stuff (differing number of bytes per character), the length of the > resulting string (in characters) varies. How can I fix this? Use unicode strings instead. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle: several class instance objects in one file?
On Thu, 27 Mar 2008 12:28:25 +, Dominique.Holzwarth wrote: > Lets say I have instances of class A and class B: > > a = A() > b = B() > > Is it possible to pickle both of these instances to the same pkl-file or > will that have any bad impact for unpickle (i.e. the instance are > 'mixed' or 'destroyed')? Or should I rather use a seperate file for > every class instance I want to pickle? You can pickle a data structure, for example a tuple, that contains both instances. Or you can write one after the other into the pickle file. Then you'll have to retrieve them in two steps too. > Another very basic question about pickling class instances: > > To store the value of attributes of an instance is it enough for the > pickling-algorithm to use the __dict__ or do I have to implement the > _setstate_ and _getstate_ function? I didn't really get the meaning of > those while reading the python user manual... Usually `pickle` just works. Those methods can be used if you want to customize the process, for example if you don't want to pickle the entire object but just parts of it. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Circular references not being cleaned up by Py_Finalize()
On Tue, 25 Mar 2008 12:32:17 -0700, blackpawn wrote: > So what's the deal here? :) I want all objects to be freed when I > shut down and their destruction functions to be properly called. Then you want something that's not guaranteed by the language. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Does python hate cathy?
On Tue, 25 Mar 2008 14:58:51 +, Edward A. Falk wrote: > In article <[EMAIL PROTECTED]>, > Patrick Mullen <[EMAIL PROTECTED]> wrote: > >>Then again, I can count the number of times I have ever needed __del__ >>with no fingers (never used it!). Still, quite interesting to >>explore. > > I used it once, for an object that had a doubly-linked list. > The __del__() method walked the list, setting all the elements' > prev/next pointers to None to make sure the elements of the list would > get garbage-collected. Without the `__del__()` the elements would get garbage collected just fine. If you don't want to wait until the garbage collector in CPython detects the cycle, you can use `weakref`\s for one of the two "pointers" in each element. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiline CSV export to Excel produces unrecognized characters?
On Sun, 23 Mar 2008 23:30:11 -0700, felciano wrote: > The following reproduces the problem in python 2.5: > > import csv > row = [1,"hello","this is\na multiline\ntext field"] > writer = csv.writer(open("test.tsv", "w"), dialect="excel-tab", > quotechar='"') > writer.writerow(row) > > When opening the resulting test.tsv file, I do indeed see a cell with > a multi-line value, but there is a small boxed question mark at the > end of each of the lines, as if Excel didn't recognize the linebreak. > > Any idea why these are there or how to get rid of them? Any chance you are doing this on Windows and Excel doesn't like the return+linefeed line endings that Windows produces when writing files in text mode? Try 'wb' as mode for the output file. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search (works)|(doesn't work) depending on for loop order
On Sat, 22 Mar 2008 13:27:49 -0700, sgharvey wrote: > ... and by works, I mean works like I expect it to. > > I'm writing my own cheesy config.ini parser because ConfigParser > doesn't preserve case or order of sections, or order of options w/in > sections. > > What's confusing me is this: >If I try matching every line to one pattern at a time, all the > patterns that are supposed to match, actually match. >If I try to match every pattern to one line at a time, only one > pattern will match. > > What am I not understanding about re.search? That has nothing to do with `re.search` but how files work. A file has a "current position marker" that is advanced at each iteration to the next line in the file. When it is at the end, it stays there, so you can just iterate *once* over an open file unless you rewind it with the `seek()` method. That only works on "seekable" files and it's not a good idea anyway because usually the files and the overhead of reading is greater than the time to iterate over in memory data like the patterns. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: backslash in reading bytes
On Thu, 20 Mar 2008 03:24:49 -0700, Dravidan wrote: > I am trying to read some byte data as a string then using a library to > convert them a code: > >>>>reader = csv.DictReader(open('table.txt')) >>>>def eleFind(value): >>>>for row in reader: >>>>if row['byteCode'] == value: >>>>print row['Element'] >>>>return >>>>else: >>>>print "No Match Found:" >>>>eleFind('\x00\x00') > > My table contains: > > \x00\x00, > \x01\x00, > .. > > The program errors out. How can I fix/overide this backslash issue. What does `errors out` mean? It won't find two zero bytes. What you give at the `eleFind()` call are just *two* characters with a byte value of zero: In [116]: len('\x00\x00') Out[116]: 2 In [117]: print '\x00\x00' In [118]: len('\\x00\\x00') Out[118]: 8 In [119]: print '\\x00\\x00' \x00\x00 The backslash has a special meaning in string literals. If you don't want this meaning, you have to escape it with another backslash. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with PARAGRAPH SEPARATOR
On Thu, 20 Mar 2008 13:03:17 +, Dominique.Holzwarth wrote: > The output of the transformation (a big string containg the whole file) > contains a so called 'paragraph separator' (unicode: 2029). If I want to > pring that string (file) to the std out or a file object then I get a > "UnicodeError" saying that the unicode 2029 can't be encoded... > > Can anyone please tell me how I should handle that paragraph seperator? You have to encode the unicode object in an encoding that know this character. UTF-8 might be a candidate encoding for this. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Prototype OO
On Wed, 19 Mar 2008 17:59:40 +0100, sam wrote: > Can someone tell me why class-based OO is better that Prototype based, > especially in scripting langage with dynamic types as Python is? Is it better!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3 and PEP238 division
On Tue, 18 Mar 2008 04:47:49 -0700, Ninereeds wrote: > On Mar 17, 7:26 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: >> 2.6, I have read, have optional 'Py3' warnings, and a 2to3 conversion >> program > > The tools can work out the *intent* of any particular division > operator? Can work out whether the result should be integer or float, > independent of any particular set of arguments? Seems unlikely. The interpreter can at least print out warnings when a "normal" division operator is called with two `int`\s at runtime. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Regarding coding style
On Mon, 17 Mar 2008 12:51:14 -0700, [EMAIL PROTECTED] wrote: > On Mar 17, 12:15 pm, rockingred <[EMAIL PROTECTED]> wrote: >> On Mar 10, 11:30 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> >> >> Unfortunately, no free VC system existed for the language in which I >> was programming > > Explain? VC isn't language-specific. It is. It depends usually on the fact that there are individual files. Preferably text files if you want automagic merging of different changes. Now think of languages that are tightly coupled with their IDE storing only binary "tokenized" files instead of plain text or even one big binary file that contains all sources and resources of the project. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't xmlrpclib.dumps just dump an empty value instead of ?
On Mon, 17 Mar 2008 17:41:23 +0100, martin f krafft wrote: > also sprach martin f krafft <[EMAIL PROTECTED]> [2008.03.16.1421 +0100]: >> Why doesn't it just yield >> >> '\n\n\n\n' >> >> Or even just >> >> '\n\n\n' > > There's a difference between those two. The first one has an empty > string value ('') while the second one pretty clearly says that > there is a parameter but has no value. > > Why ? Because there is a difference between no value and the NULL value!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why doesn't xmlrpclib.dumps just dump an empty value instead of ?
On Sun, 16 Mar 2008 14:21:40 +0100, martin f krafft wrote: > Hi, > > xmlrpclib.dumps((None,), allow_none=True) yields > > '\n\n\n\n' > > Why doesn't it just yield > > '\n\n\n\n' > > Or even just > > '\n\n\n' > > Those are valid XML and valid XML-RPC, but isn't. In XML-RPC there is no `None`, so there's the non standard `allow_none` Option to allow `None` to be represented as . And is an empty or really valid XML-RPC? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange problem with structs Linux vs. Mac
On Sun, 16 Mar 2008 18:45:19 +0100, Martin Blume wrote: > I don't think this qualifies as a bug, but I am astonished > that the struct module does not tell you whether you are > big endian, you have to find out yourself with >struct.unpack('@I', s)[0]==struct.unpack(">I", s)[0] Maybe a little more compact and readable: In [92]: sys.byteorder Out[92]: 'little' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode/UTF-8 confusion
On Sat, 15 Mar 2008 16:33:24 -0400, Tom Stambaugh wrote: > I use a trick to let me pass the information into my browser client > application. The browser requests the server information from a form whose > target is a hidden iframe. The string the server serializes is wrapped in > html that embeds it in an onload handler like this: > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> > http://www.w3.org/1999/xhtml";> http-equiv="content-type" content="text/html; charset=UTF-8" /> type="text/javascript">//<![CDATA[ > function vpage_load() { > var aParent = window.parent; > if (!aParent || !aParent.document || !aParent.document.vpage) { > alert("No parent, parent.document, or parent.document.vpage"); > return;} > var aSerializedObject = '%(jsonString)s'; > if (aParent && aParent._clientApplication) { > aParent._clientApplication.loadObject(aSerializedObject, > window.document, '' + window.document.location, true)} > else { > alert("No parent or no clientApplication")} > } > //]]> > > > > > > > […] > > In order to successfully pass the escapes to the server, I already have to > double any each backslash. At the end of the day, it's easier -- and results > in better performance -- to convert each apostrophe to its unicode > equivalent, as I originally asked. > > I just want to know if there's a faster way to persuade simplejson to > accomplish the feat. So you don't ask for JSON encoded objects but JSON encoded *and* HTML/JavaScript embeddable escaped literal string. That's simply not the job of a JSON encoder. That's another level of encoding/escaping producing something that is not JSON anymore, so why do you want to ask a JSON encoder to deliver it? This is a feature/function you should find in a HTML templating library. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode/UTF-8 confusion
On Sat, 15 Mar 2008 12:09:19 -0400, Tom Stambaugh wrote: > I'm still confused about this, even after days of hacking at it. It's time I > asked for help. I understand that each of you knows more about Python, > Javascript, unicode, and programming than me, and I understand that each of > you has a higher SAT score than me. So please try and be gentle with your > responses. > > I use simplejson to serialize html strings that the server is delivering to > a browser. Since the apostrophe is a string terminator in javascript, I need > to escape any apostrophe embedded in the html. > > Just to be clear, the specific unicode character I'm struggling with is > described in Python as: > u'\N{APOSTROPHE}'}. It has a standardized utf-8 value (according to, for > example, http://www.fileformat.info/info/unicode/char/0027/index.htm) of > 0x27. > > This can be expressed in several common ways: > hex: 0x27 > Python literal: u"\u0027" > > Suppose I start with some test string that contains an embedded > apostrophe -- for example: u" ' ". I believe that the appropriate json > serialization of this is (presented as a list to eliminate notation > ambiguities): > > ['"', ' ', ' ', ' ', '\\', '\\', '0', '0', '2', '7', ' ', ' ', ' ', '"'] > > This is a 14-character utf-8 serialization of the above test string. > > I know I can brute-force this, using something like the following: > def encode(aRawString): > aReplacement = ''.join(['\\', '0', '0', '2', '7']) > aCookedString = aRawString.replace("'", aReplacement) > answer = simplejson.dumps(aCookedString) > return answer > > I can't even make mailers let me *TYPE* a string literal for the replacement > string without trying to turn it into an HTML link! > > Anyway, I know that my "encode" function works, but it pains me to add that > "replace" call before *EVERY* invocation of the simplejson.dumps() method. > The reason I upgraded to 1.7.4 was to get the c-level speedup routine now > offered by simplejson -- yet the need to do this apostrophe escaping seems > to negate this advantage! Is there perhaps some combination of dumps keyword > arguments, python encode()/str() magic, or something similar that > accomplishes this same result? > > What is the highest-performance way to get simplejson to emit the desired > serialization of the given test string? Somehow I don't get what you are after. The ' doesn't have to be escaped at all if " are used to delimit the string. If ' are used as delimiters then \' is a correct escaping. What is the problem with that!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: request for Details about Dictionaries in Python
On Fri, 14 Mar 2008 17:06:00 +, Matt Nordhoff wrote: > Hmm, if Perl's on-disk hash tables are good, maybe someone should port > them to Python, or maybe someone already has. I don't know Perl's on-disk hash tables but there is a `shelve` module in the standard library. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling global variables (Newbie)
On Fri, 14 Mar 2008 12:19:18 -0700, MRAB wrote: > On Mar 13, 4:25 am, "David S" <[EMAIL PROTECTED]> wrote: >> Hi, >> >> I have an error occurring at >> self.build_root = os.path.abspath(os.path.split(__file__)[0]) >> >> The error states 'NameError: global name '__file__' is not defined' >> >> In Python 2.5 I ran my script as a module in IDLE gui. How does _file_ get >> defined? >> > Do you perhaps mean '__name__'? I guess not. It makes more sense to apply path functions to `__file__` than to `__name__`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: List mutation method gotcha - How well known?
On Fri, 14 Mar 2008 11:32:41 -0700, Lie wrote: > No, there is no need for "void" return type, what I meant is that > everything that's not said in the documentation should be assumed to > be an implementation detail, a method or a function that doesn't say > anything about its return type should be assumed to return an > implementation detail (which basically means: Don't rely on this). The > fact that list.append returns none is just a coincidence, you might > encounter another list.append that returns different thing some time > in the future, or the far future, or perhaps at the end of the > galaxy's life. I expect functions with no documentation of what they return to return `None`. Assuming they are documented at all, of course. :-) It's like not writing a ``return`` statement in the code: there's always an implicit ``return None`` at the end of every function. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list