Where can I find string.translate source?
The module string has a function called translate. I tried to find the source code for that function. In: C:\Python24\Lib there is one file called string.py I open it and it says """A collection of string operations (most are no longer used). Warning: most of the code you see here isn't normally used nowadays. Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object. They used to be implemented by a built-in module called strop, but strop is now obsolete itself.""" Inside the file string.py I couldn't find the source code for translate. Where could it be? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
On Sat, 19 Nov 2005 23:30:32 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote: >[EMAIL PROTECTED] writes: >> Thanks Diez and Peter, >> Just what I was looking for. In "Library Reference" heading >> 3.11.1 Types and members >> Running this yields the result >> >> cap(s, n) > >You've now got three solutions. They'll work fine most of the time, >but can't be trusted in general. Binding a name to a function doesn't >change the name that these solutions return, and the name they return >may no longer be bound to said function. Just a warning. > But the one buried in co_name seems to persist (barring byte code munging in the decorator ;-) >>> def fren(newname='newname'): ... def fren(f): ... f.__name__ = newname ... return f ... return fren ... >>> @fren('bar') ... def foo():pass ... Could have done that manually, but just playing. Ok, rebind foo and remove the old name, for grins >>> baz = foo >>> del foo See what we've got >>> dir() ['__builtins__', '__doc__', '__name__', 'baz', 'fren'] Check name(s) ;-) Local binding to the function object first: >>> baz Its outer name: >>> baz.func_name 'bar' Its def name: >>> baz.func_code.co_name 'foo' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: exception raised by nested iterator being ignored by for loop
On Sun, 20 Nov 2005 03:36:43 GMT, james t kirk <[EMAIL PROTECTED]> wrote: >I'm writing a wrapper class to handle the line merging and filtering >for a log file analysis app > >The problem I'm running into is that the StopIteration exception >raised when the wrapped file goes past EOF isn't causing the second >for loop to stop. Wrapping the second for loop in a try/except clause >shows that the exception is being raised though. > >Could someone more familiar with the underlying implementation please >give me a hint as to why this is happening? > > >import gzip >class wrapper : > >def __init__ (self, filename) : >if filename[-3:] == ".gz" : >self.fh = gzip.GzipFile(filename, "r") >else : >self.fh = open(filename, "r") > >def __iter__ (self) : >return self > >def next (self) : >for line in self.fh : # StopIteration raised here when >file exhausted Yes, but that just ends the for loop and that uses up the exception, so either change the above "for ..." to two lines: (untested ;-/ ) while True: line = self.fh.next() # should raise StopIteration without # being caught by for >if line[:1] == "t" :# filter out lines starting with >'t' >continue >return line.rstrip() or otherwise the end of the for will catch the StopIteration and just drop out here. Imagine you were just printing the line in the loop body instead of checking and returning lines. With just a print, you wouldn't expect a StopIteration to escape the for loop, right? If you want to leave the for unchanged, you could just tell the world that the wrapper iteration is done, by using the following line here: raise StopIteration # end of wrapper iteration > >if __name__ == "__main__" : ># using the file handle >fh = open("test.txt") >for line in fh : >print line.rstrip() >fh.close() > ># using the wrapper class >fh = wrapper("test.txt") >for line in fh :# StopIteration ignored here >print line > HTH (and that the untested code works ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Peter Hansen <[EMAIL PROTECTED]> writes: > Steven D'Aprano wrote: >> Dealing with numeric literals with lots of digits is >> a real (if not earth-shattering) human interface problem: it is hard for >> people to parse long numeric strings. > > I'm totally unconvinced that this _is_ a real problem, if we define > "real" as being even enough to jiggle my mouse, let alone shattering the > planet. > > What examples does anyone have of where it is necessary to define a > large number of large numeric literals? Isn't it the case that other > than the odd constants in various programs, defining a large number of > such values would be better done by creating a data file and parsing > it? One example I can think of is a large number of float constants used for some math routine. In that case they usually be a full 16 or 17 digits. It'd be handy in that case to split into smaller groups to make it easier to match with tables where these constants may come from. Ex: def sinxx(x): "computes sin x/x for 0 <= x <= pi/2 to 2e-9" a2 = -0.1 4 a4 = 0.00833 33315 a6 = -0.00019 84090 a8 = 0.0 27526 a10= -0.0 00239 x2 = x**2 return 1. + x2*(a2 + x2*(a4 + x2*(a6 + x2*(a8 + x2*a10 (or least that's what I like to write). Now, if I were going to higher precision, I'd have more digits of course. -- |>|\/|< /--\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
On Sun, 20 Nov 2005 16:10:58 +1100, Steven D'Aprano wrote: > def get_line(filename, token): > """Returns the next line following a token, or None if not found. > Leading and trailing whitespace is ignored when looking for > the token. > """ > fp = file(filename, "r") > for line in fp: > if line.strip() == token: > break > else: > # runs only if we didn't break > print "Token not found" > result = None > result = fp.readline() # read the next line only > fp.close() > return result Correction: checking the Library Reference, I find that this is wrong. The reason is that file objects implement their own read-ahead buffer, and mixing calls to next() and readline() may not work right. See http://docs.python.org/lib/bltin-file-objects.html Replace the fp.readline() with fp.next() and all should be good. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
On Sun, 20 Nov 2005 12:28:07 +0800, Xiao Jianfeng wrote: > Let me introduce my problem I came across last night first. > > I need to read a file(which may be small or very big) and to check line > by line > to find a specific token, then the data on the next line will be what I > want. > > If I use readlines(), it will be a problem when the file is too big. > > If I use "for line in OPENED_FILE:" to read one line each time, how can > I get > the next line when I find the specific token? Here is one solution using a flag: done = False for line in file("myfile", "r"): if done: break done = line == "token\n" # note the newline # we expect Python to close the file when we exit the loop if done: DoSomethingWith(line) # the line *after* the one with the token else: print "Token not found!" Here is another solution, without using a flag: def get_line(filename, token): """Returns the next line following a token, or None if not found. Leading and trailing whitespace is ignored when looking for the token. """ fp = file(filename, "r") for line in fp: if line.strip() == token: break else: # runs only if we didn't break print "Token not found" result = None result = fp.readline() # read the next line only fp.close() return result Here is a third solution that raises an exception instead of printing an error message: def get_line(filename, token): for line in file(filename, "r"): if line.strip() == token: break else: raise ValueError("Token not found") return fp.readline() # we rely on Python to close the file when we are done > And I think reading one line each time is less efficient, am I right? Less efficient than what? Spending hours or days writing more complex code that only saves you a few seconds, or even runs slower? I believe Python will take advantage of your file system's buffering capabilities. Try it and see, you'll be surprised how fast it runs. If you try it and it is too slow, then come back and we'll see what can be done to speed it up. But don't try to speed it up before you know if it is fast enough. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
Xiao Jianfeng wrote: > Steven D'Aprano wrote: > > >>On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote: >> >> >> >> >>>I have some other questions: >>> >>>when "fh" will be closed? >>> >>> >> >>When all references to the file are no longer in scope: >> >>def handle_file(name): >> fp = file(name, "r") >> # reference to file now in scope >> do_stuff(fp) >> return fp >> >> >>f = handle_file("myfile.txt) >># reference to file is now in scope >>f = None >># reference to file is no longer in scope >> >>At this point, Python *may* close the file. CPython currently closes the >>file as soon as all references are out of scope. JPython does not -- it >>will close the file eventually, but you can't guarantee when. >> >> >> >> >>>And what shoud I do if I want to explicitly close the file immediately >>>after reading all data I want? >>> >>> >> >>That is the best practice. >> >>f.close() >> >> >> >> > > Let me introduce my problem I came across last night first. > > I need to read a file(which may be small or very big) and to check line > by line > to find a specific token, then the data on the next line will be what I > want. > > If I use readlines(), it will be a problem when the file is too big. > > If I use "for line in OPENED_FILE:" to read one line each time, how can > I get > the next line when I find the specific token? > And I think reading one line each time is less efficient, am I right? > Not necessarily. Try this: f = file("filename.txt") for line in f: if token in line: # or whatever you need to identify it break else: sys.exit("File does not contain token") line = f.next() Then line will be the one you want. Since this will use code written in C to do the processing you will probably be pleasantly surprised by its speed. Only if this isn't fast enough should you consider anything more complicated. Premature optimizations can waste huge amounts of unnecessary programming time. Don't do it. First try measuring a solution that works! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Delays getting data on sys.stdin.readline() ?
Christian Convey <[EMAIL PROTECTED]> writes: > I've got a program that (ideally) perpetually monitors sys.stdin for > lines of text. As soon as a line comes in, my program takes some > action. > The problem is, it seems like a very large amount of data must > accumulate on sys.stdin before even my first invocation of readline() > returns. This delay prevents my program from being responsive in the > way it must be. readline normally returns as soon as it sees a newline. External conditions may cause this to change, or make it impossible. Without knowing those external conditions, the best we can do is guess as to what might be the problem. > Has anyone else seen this effect? If so, is there a reasonable workaround? Yes, and maybe. Depends on what's causing the problem. Tell us more about the program, and what sys.stdin is connected to, and the platform you're running on, and someone should be able to provide explicit information. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hot to split string literals that will across two or more lines ?
On Sat, 19 Nov 2005 22:51:04 -0500, Mike Meyer wrote: > Steven D'Aprano <[EMAIL PROTECTED]> writes: >> Brackets include: >> >> parentheses or round brackets ( ) >> square brackets [ ] >> braces or curly brackets { } >> chevrons or angle brackets ⩠⪠>> >> The symbols for chevrons are not available on common keyboards, are not >> available in ordinary ASCII, and may not show up correctly in many >> typefaces, so a common alternative is to substitute less than and greater >> than signs < > as brackets. HTML and XML use that convention. > > Hmm. I'm used to seeing "angle brackets" - aka brokets - used to refer > to . That may be the convention you mention leaking across, though. > > You imply that HTML/XML might use chevrons. I don't think that's the > case. They inherit their start/end tag characters from SGML's > default. No! That's not what I said. SGML-derived languages use greater-than and less-than symbols < > as if they were brackets. That's practicality beats purity: true chevrons are not available in ASCII or on common keyboards, making them difficult to use. People commonly call < and > "angle brackets" in the context of HTML etc. but they aren't really, they are mathematical comparison operator signs. Proper chevrons are narrower and taller. The difference between 〈 〉 and < > is *very* obvious in the font I'm using, although of course not all fonts use the proper glyphs. If it helps, the angle on the inside of the chevron is about 120 degrees, compared to maybe 60 degrees for the comparison operators. Again, this depends on the precise glyph being used. True angle brackets are available in Unicode at code points 9001 and 9002, (0x2329 and 0x232A). The less-than and greater-than symbols can be found in both Unicode and ASCII at code points 60 and 62 (0x003C and 0x003E). I did warn in my earlier post that I was being pedantic. In common usage, I'll describe as using angle brackets, just as I'll describe "quote" as using quote marks. They're not actually: they are double-prime marks, and ' is a prime mark not an apostrophe or quote mark. Prime and double-prime marks are also known as foot and inch marks, although *real* pedants would argue that there is a difference between them too. (I think they get separate Unicode points.) It is easy to get confused when it comes to characters, because there are three separate but related things to keep in mind. Firstly, there is the glyph or picture used, which differs according to the font and type-style. Two different glyphs can represent the same symbol, and two identical glyphs can represent different symbols. Secondly, there is the semantic meaning of the character: a dash and a hyphen are both horizontal lines, but they have very different meanings. Dashes -- sometimes faked with two hyphens in a row like this -- are used as separators, and hyphens are used to join compound words like fire-fighting or anti-matter. Thirdly, there is the specific implementation of the character. ASCII defines only 127 characters, a good thirty-plus being invisible control characters. Eight-bit extensions to ASCII unfortunately vary between each other: the character 176 (0xB0) is the degree symbol in the Latin-1 encoding (ISO 8859-1) but the infinity symbol in the MacRoman encoding. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Roy Smith <[EMAIL PROTECTED]> writes: > Mike Meyer <[EMAIL PROTECTED]> wrote: >> I've seen at least one language (forget which one) that allowed such >> separators, but only for groups of three. > That seems a bit silly. Not all numbers are naturally split into groups of > three. Credit card numbers are (typically) split into groups of four. > Account numbers are often split into all sorts of random groupings. True. But how often do you want to add two account numbers, or multiply two credit card numbers? Or display them in hex, or otherwise treat them as something other than a string that happens to be composed of digits? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Delays getting data on sys.stdin.readline() ?
Christian Convey wrote: > Hello, > > I've got a program that (ideally) perpetually monitors sys.stdin for > lines of text. As soon as a line comes in, my program takes some > action. > > The problem is, it seems like a very large amount of data must > accumulate on sys.stdin before even my first invocation of readline() > returns. This delay prevents my program from being responsive in the > way it must be. > > Has anyone else seen this effect? If so, is there a reasonable workaround? > Generally speaking there will be buffering of the output process that's feeding your standard input. You can try to set sys.stdin to be unbuffered (look at the interpreter's -u option), but depending on how the feeding process is organized it might hold data in its buffers before it appears on your process's stdin. You may have noticed the same thing in Unix-like operating systems when running tail -f on a file being fed by an active process: the output appears in chunks ending in partial lines because the feeding process's output buffer has been filled and the operating system has passed it to the tail process. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
[EMAIL PROTECTED] writes: > Thanks Diez and Peter, > Just what I was looking for. In "Library Reference" heading > 3.11.1 Types and members > Running this yields the result > > cap(s, n) You've now got three solutions. They'll work fine most of the time, but can't be trusted in general. Binding a name to a function doesn't change the name that these solutions return, and the name they return may no longer be bound to said function. Just a warning. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Gustav Hållberg wrote: > I tried finding a discussion around adding the possibility to have > optional underscores inside numbers in Python. This is a popular option > available in several "competing" scripting langauges, that I would love > to see in Python. > > Examples: > 1_234_567 > 0xdead_beef > 3.141_592 I suppose it could be done. OTOH, one could argue that most production code has no business hardwiring-in numerical constants greater than 999 ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
Steven D'Aprano wrote: >On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote: > > > >> I have some other questions: >> >> when "fh" will be closed? >> >> > >When all references to the file are no longer in scope: > >def handle_file(name): >fp = file(name, "r") ># reference to file now in scope >do_stuff(fp) >return fp > > >f = handle_file("myfile.txt) ># reference to file is now in scope >f = None ># reference to file is no longer in scope > >At this point, Python *may* close the file. CPython currently closes the >file as soon as all references are out of scope. JPython does not -- it >will close the file eventually, but you can't guarantee when. > > > >> And what shoud I do if I want to explicitly close the file immediately >>after reading all data I want? >> >> > >That is the best practice. > >f.close() > > > > Let me introduce my problem I came across last night first. I need to read a file(which may be small or very big) and to check line by line to find a specific token, then the data on the next line will be what I want. If I use readlines(), it will be a problem when the file is too big. If I use "for line in OPENED_FILE:" to read one line each time, how can I get the next line when I find the specific token? And I think reading one line each time is less efficient, am I right? Regards, xiaojf -- http://mail.python.org/mailman/listinfo/python-list
Re: exception raised by nested iterator being ignored by for loop
james t kirk wrote: > I'm writing a wrapper class to handle the line merging and filtering > for a log file analysis app > > The problem I'm running into is that the StopIteration exception > raised when the wrapped file goes past EOF isn't causing the second > for loop to stop. Admiral Kirk, The innermost for-loop is catching its own StopIteration. You need to explicitly raise StopIteration in your next() method when there are no more lines in the file (hint, add an else-clause to the for-loop). Alternatively, you could simplify your life by writing the whole wrapper as a generator: import gzip def wrapper(filename) : if filename[-3:] == ".gz" : fh = gzip.GzipFile(filename, "r") else : fh = open(filename, "r") for line in fh: if line[:1] != "t": # filter out lines starting with 't' yield line.rstrip() fh.close() Raymond Hettinger Starfleet Command -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie-question about a list
[EMAIL PROTECTED] writes: > I've seen this construct in a script [x.capitalize() for x in ['a','b', 'c']] > ['A', 'B', 'C'] > I tried to find a description of this in "Library Reference" but > couldn't find it. Could somebody direct me where this type of construct > is described. As others have pointed out, it's called a "list comprehension". But it's syntax, so the proper place to look for it is the "Language Reference", not the "Library Reference". Except in this case, the language reference is fairly opaque, so you're better off using the google references others have already provided. You might also look for the related construct, "generator expressions". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Mike Meyer <[EMAIL PROTECTED]> wrote: > I've seen at least one language (forget which one) that allowed such > separators, but only for groups of three. That seems a bit silly. Not all numbers are naturally split into groups of three. Credit card numbers are (typically) split into groups of four. Account numbers are often split into all sorts of random groupings. -- http://mail.python.org/mailman/listinfo/python-list
Delays getting data on sys.stdin.readline() ?
Hello, I've got a program that (ideally) perpetually monitors sys.stdin for lines of text. As soon as a line comes in, my program takes some action. The problem is, it seems like a very large amount of data must accumulate on sys.stdin before even my first invocation of readline() returns. This delay prevents my program from being responsive in the way it must be. Has anyone else seen this effect? If so, is there a reasonable workaround? Thanks very much, Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Steven D'Aprano <[EMAIL PROTECTED]> writes: > On Sat, 19 Nov 2005 13:08:57 -0500, Peter Hansen wrote: >> Umm... in other words, "the underscore is under-used so let's assign >> some arbitrary meaning to it" (to make the language more like Perl >> perhaps?). > > +1 > > I *really* don't like the idea of allowing underscores in numeric > literals. Firstly, for aesthetic reasons: I think 123_456 is seriously > ugly. Secondly, for pragmatic reasons, I think it is too easy to mistype > as 123-456. I know that Python can't protect you from typing 9-1 instead > of 901, but why add special syntax that makes that sort of error MORE > common?) I've seen at least one language (forget which one) that allowed such separators, but only for groups of three. So 123_456 would be valid, but 9_1 would be a syntax error. This kind of thing might help with the detecting typos issue, and probably won't be noticed by most users. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote: > I have some other questions: > > when "fh" will be closed? When all references to the file are no longer in scope: def handle_file(name): fp = file(name, "r") # reference to file now in scope do_stuff(fp) return fp f = handle_file("myfile.txt) # reference to file is now in scope f = None # reference to file is no longer in scope At this point, Python *may* close the file. CPython currently closes the file as soon as all references are out of scope. JPython does not -- it will close the file eventually, but you can't guarantee when. > And what shoud I do if I want to explicitly close the file immediately > after reading all data I want? That is the best practice. f.close() -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hot to split string literals that will across two or more lines ?
Steven D'Aprano <[EMAIL PROTECTED]> writes: > Brackets include: > > parentheses or round brackets ( ) > square brackets [ ] > braces or curly brackets { } > chevrons or angle brackets ⩠⪠> > The symbols for chevrons are not available on common keyboards, are not > available in ordinary ASCII, and may not show up correctly in many > typefaces, so a common alternative is to substitute less than and greater > than signs < > as brackets. HTML and XML use that convention. Hmm. I'm used to seeing "angle brackets" - aka brokets - used to refer to . That may be the convention you mention leaking across, though. You imply that HTML/XML might use chevrons. I don't think that's the case. They inherit their start/end tag characters from SGML's default. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
query domain registry from python?
hi, does anyone know of a library that can query domain registry or any site that provide information to such an activity? as i want to build a simple domain name searching program for my own benefit.. thanks alot :D -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
Decorate any function with @aboutme(), which will print the function name each time the function is called. All the 'hello' stuff is in the aboutme() decorator code. There is no code in the decorated functions themselves doing anything to telling us the function name. # The decorator def aboutme(): def thecall(f, *args, **kwargs): # Gets to here during module load of each decorated function def wrapper( *args, **kwargs): # Our closure, executed when the decorated function is called print "Hello\nthe name of this function is '%s'\n" \ % f.func_name return f(*args, **kwargs) return wrapper return thecall @aboutme() def testing(s): print "string '%s' is argument for function" % s @aboutme() def truing(): return True # Try these testing('x') testing('again') truing() -- http://mail.python.org/mailman/listinfo/python-list
exception raised by nested iterator being ignored by for loop
I'm writing a wrapper class to handle the line merging and filtering for a log file analysis app The problem I'm running into is that the StopIteration exception raised when the wrapped file goes past EOF isn't causing the second for loop to stop. Wrapping the second for loop in a try/except clause shows that the exception is being raised though. Could someone more familiar with the underlying implementation please give me a hint as to why this is happening? import gzip class wrapper : def __init__ (self, filename) : if filename[-3:] == ".gz" : self.fh = gzip.GzipFile(filename, "r") else : self.fh = open(filename, "r") def __iter__ (self) : return self def next (self) : for line in self.fh : # StopIteration raised here when file exhausted if line[:1] == "t" :# filter out lines starting with 't' continue return line.rstrip() if __name__ == "__main__" : # using the file handle fh = open("test.txt") for line in fh : print line.rstrip() fh.close() # using the wrapper class fh = wrapper("test.txt") for line in fh :# StopIteration ignored here print line -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Steven D'Aprano <[EMAIL PROTECTED]> wrote: > That's a tad unfair. Dealing with numeric literals with lots of digits is > a real (if not earth-shattering) human interface problem: it is hard for > people to parse long numeric strings. There are plenty of ways to make numeric literals easier to read without resorting to built-in language support. One way is: sixTrillion = 6 * 1000 * 1000 * 1000 * 1000 Or, a more general solution might be to write a little factory function which took a string, stripped out the underscores (or spaces, or commas, or whatever bit of punctuation turned you on), and then converted the remaining digit string to an integer. You could then write: creditCardNumber = myInt ("1234 5678 9012 3456 789") Perhaps not as convenient as having it built into the language, but workable in those cases which justify the effort. -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
[EMAIL PROTECTED] wrote: >newer python should use "for x in fh:", according to the doc : > >fh = open("your file") >for x in fh: print x > >which would only read one line at a time. > > > I have some other questions: when "fh" will be closed? And what shoud I do if I want to explicitly close the file immediately after reading all data I want? >Ross Reyes wrote: > > >>HI - >>Sorry for maybe a too simple a question but I googled and also checked my >>reference O'Reilly Learning Python >>book and I did not find a satisfactory answer. >> >>When I use readlines, what happens if the number of lines is huge?I have >>a very big file (4GB) I want to >>read in, but I'm sure there must be some limitation to readlines and I'd >>like to know how it is handled by python. >>I am using it like this: >>slines = infile.readlines() # reads all lines into a list of strings called >>"slines" >> >>Thanks for anyone who knows the answer to this one. >> >> > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused about namespaces
KvS <[EMAIL PROTECTED]> wrote: > Thanks a lot for all the answers. After rereading everything said here > today it's become more clear to me what you guys are telling me and > I'll actively try to forget about "from ... import *" ;). I commend you for your decision. It's a construct that I sometimes find quite handy in an experimentation session in the interactive interpreter, but just has no really good place in 'true' code;-0. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write an API for a Python application?
Cameron Laird <[EMAIL PROTECTED]> wrote: > In article <[EMAIL PROTECTED]>, I mumbled: > . > . > . > >Pyro might be perfect. My own instinct is to start even more > >primitively, with a minimal asynchat client and server. I've > >looked through the *Cookbook*, and see that it doesn't have > >what I want. Maybe it's time Phaseit donate one of the > >little models we use ... > > Ah-ha! See Example 19-7, on page 447 of *Python in a Nutshell*: > under two dozen lines that provide an echo server which correctly > handles multiple concurrent clients. Note also that you can freely download all of the code in my book as http://examples.oreilly.com/pythonian/pythonian-examples.zip (it's just 36 KB). In that same chapter you will find several implementations of mutually compatible clients and servers for that same echo-oid "protocol" (as well as one incompatible one using UDP -- all the others use TCP). I hope they can be useful to anybody wanting to kludge together some simple TCP/IP thingy (though, for the problem being discussed in this thread, I'd rather recommend Corba;-). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: path module / class
Neil Hodgson wrote: >To me, most uses of path.py are small incremental improvements over > os.path rather than being compelling. Do a number of small improvements > add up to be large enough to make this change? If the number of small improvements is large enough then, as with other such situations in the world, the overall change can definitely become qualitative. For me that's the case with using path.py. > There is a cost to the > change as there will be two libraries that have to be known to > understand code. Could you please clarify? Which two do you mean? > Does someone have an example application that moved to > path.py with a decrease in errors or noticeable decrease in complexity? We've mandated use of path.py internally for all projects because we've noticed (especially with non-expert Python programmers... i.e. junior and intermediate types, and senior types new to Python) a decrease in errors. Adoption of the appropriate methods in path.py (e.g. joinpath(), .name and .ext, .files()) is higher than the use of the equivalent methods or idioms with the standard libraries. How to do something, if not immediately obvious, is easier to discover because the docs and code are all in one place (for path.py). There's certainly a noticeable decrease in complexity. I could elaborate, but I honestly believe that this should be obvious to anyone who has seen almost any of the examples that have been posted, where a dozen lines of regular Python collapse to half that with path.py. Just removing imports of os, shutil, fnmatch, and glob in favour of a single one makes things "noticeably" (though admittedly not hugely) less complex. > Could all path manipulation code be switched or is coverage incomplete? As far as I can tell with our own usage, it is complete. We have not yet written code that required falling back to one of the existing modules, though I certainly wouldn't be shocked if someone had examples. >The duplication argument should be answered by looking at all the > relevant modules and finding a coherent set of features that work with > path.py without overlap so that the obsolete methods can be deprecated. > If adding path.py leads to a fuzzy overlapping situation where os.path > is occasionally useful then we are complicating the user's life rather > than simplifying it. I agree with that, but don't believe it is the case. And if one or two minor examples exist, fixing those cases would make more sense to me than abandoning the entire idea. For the record, though, if I haven't said it before, it doesn't really bother me that this isn't part of the standard library. I find it trivial to install in site-packages for all our workstations, and as we deliver code with py2exe it comes along for the ride. (And I feel no particular personal need to make things a lot simpler for newcomers to the language (other than those who work with me), though for people who do feel that need I definitely promote the idea of path.py becoming standard.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Anton Vredegoor <[EMAIL PROTECTED]> wrote: ... > Suppose I grant all your theories about optimal marketing strategies. > This still doesn't account for the way the market is behaving *now*. It > isn't in any way logical or optimal. For example in Holland (where I > live) complete governmental departments are dedicated to make life What makes you think that governmental departments are part of the *market*?! Government behavior is controlled by laws that are vastly different from those controlling market behavior; if you're interested, you could study the "theory of public choice". Studying "perfect" markets (which can be mathematically proven to be optimal in some senses -- the Arrow-Debreu Model, for example) is parallel to studying physical systems that do not have attrition or other such complications -- it's mathematically sharp (not easy, but WAY easier than taking account of all the complications of the real world), intellectually fascinating, AND practically useful in many (not all) cases, since many real systems can be usefully modeled as "perfect" ones with "perturbations" (second-order effects) considered separately. If Galileo had tried to START physics by studying real-world systems in all of their complexity, we'd still be at square zero; fortunately, he was able to identify systems "close enough to perfect" (e.g., heavy weights faling to the ground, compact enough to ignore air resistance, etc) to get the ball rolling. Physics still faces a lot of challenges after many centuries in areas where the "perturbations" are much stronger than "second-order" -- I'm told our physical modeling of cloud systems or such everyday phenomena as welding is still way from perfect, for example (forget quantum and relativistic effects... I'm talking of everyday observations!-), and of course so does the much younger discipline of mathematical economics. Nevertheless the study of the "perturbations" is well under way, with Nobel memorial prizes having already been awarded in such fields as "bounded rationality" and asymmetric-information markets. Just like a gunner in the mid-19th century had to know fundamental physics pretty well, but also developed experience-based heuristics to compensate for all of the "perturbations" in his system, so the practicing economic actor today needs a mix of science and art (in the original meaning of "art", of course). > You seem to tackle the problem of python obfuscation by first proving > that it isn't feasible and then giving some kind of solution that will > work and give the desired result: webservices. However when I look at That seems to me to be a practicable technical approach, yes. > obfuscation techniques I see a desire to profit from giving some person > the idea that he or she is superior to someone else because he has a > better product. In order to avoid copying we now need obfuscation. The You're discussing the *motivation* for obfuscating, while what I was giving was a possible way of *implementing* similar effects. > difficulty to copy the thing (whether it is a swiss watch, a sportscar, > designer clothes, the latest computer game, an ipod, a computer > program) is part of the advertising game and is the basis for > associating it with a certain status. If you look for a few minutes at Yes, this is close to the theory of luxury goods (which is WAY underdeveloped, by the way: if you're a post-doctoral student in economics and are wondering where best to direct your research in order to stand a chance to gain a Nobel memorial prize some day, you could do worse than turn your efforts to this field). The maths are complicated, in the theory of luxury goods, because utility is RELATIVE: buyer's advantage cannot be computed, even theoretically, from knowing just the buyer's utility curve and the amount of good supplied to that buyer, because the curve depends on the *relative* amounts supplied to that buyer versus other buyers. Throw asymmetric information into the mix, and, besides a mathematically unmanageable mess, you get the famous anomaly whereby an INCREASE i the price may locally result in an INCREASE in demand (backwards-sloping price-demand curve) -- each buyer, lacking information about other buyers, infers it from price signals, and *assumes* (as is normally the case) that higher price means fewer buyers; since fewer buyers means a higher relative advantage, this assumption increases each buyer's appetite and thus, in the aggregate, raises demand. While this is fascinating as an open research topic, AND crucial to economic survival for purveyors of luxury good, I dispute the wisdom of trying to model MOST markets of interest as subject to the fascinating complications of "luxury goods theory". Take, again, the specific example of the sawmill with NC saws, doing custom work by cutting customer-specified shapes out of standard planks of wood. If things can be optimized, so that six such shapes can be cut out of each plant rather than
Re: Underscores in Python numbers
Steven D'Aprano wrote: > Dealing with numeric literals with lots of digits is > a real (if not earth-shattering) human interface problem: it is hard for > people to parse long numeric strings. I'm totally unconvinced that this _is_ a real problem, if we define "real" as being even enough to jiggle my mouse, let alone shattering the planet. What examples does anyone have of where it is necessary to define a large number of large numeric literals? Isn't it the case that other than the odd constants in various programs, defining a large number of such values would be better done by creating a data file and parsing it? And if that's the case, one could easily define any convention one desired for formatting the raw data. And for the odd constant, either take a moment to verify the value, or define it in parts (e.g. 24*60*60*1000*1000 microseconds per day), or write a nice little variant on int() that can do exactly what you would have done for the external data file if you had more values. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write an API for a Python application?
In article <[EMAIL PROTECTED]>, I mumbled: . . . >Pyro might be perfect. My own instinct is to start even more >primitively, with a minimal asynchat client and server. I've >looked through the *Cookbook*, and see that it doesn't have >what I want. Maybe it's time Phaseit donate one of the >little models we use ... Ah-ha! See Example 19-7, on page 447 of *Python in a Nutshell*: under two dozen lines that provide an echo server which correctly handles multiple concurrent clients. But that's also about as much as I've found publicly in that direction. The original questioner wanted, or thought he wanted, an object-capable protocol, so he could invoke methods remotely; for that, I return to Paul Boddie's correct observation that folks can use CORBA, or imitate CORBA badly (as much of this season's "SOA" does). What I don't see, though, is a nice client- server pair that are minimal, and exhibit *symmetric* event-oriented performance and scalability. Some people mistakenly regard this "peering" architecture as a dark secret. I think I'll write a model in under fifty lines of Python this week ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Behaviour of enumerated types
On Sun, 20 Nov 2005 08:42:48 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> wrote: >Bengt Richter <[EMAIL PROTECTED]> wrote: >> On Sat, 19 Nov 2005 11:10:42 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> >> wrote: >> >Bengt Richter <[EMAIL PROTECTED]> wrote: >> >> If [an enumeration has a fixed sequence], what is more natural >> >> than using their index values as keys to other ordered info? >> >I don't see why. If you want sequence numbers, use enumerate(). If >> >not, the enum object itself can be used directly as an iterable. >> >> I changed mine so the enum _class_ is iterable, but enum instances >> are not. > >I'm not really understanding your design. > >In my enum package, an enumeration is an instance of Enum. Those >instances are iterable, producing EnumValue instances; the EnumValue >instances are also available as named attributes of the Enum instance. I have a similar situation, except I have an enum factory function makeEnum instead of a class Enum, and the factory returns not an instance of Enum, but an enum as a unique type, i.e., a class. But it is functionally analogous, except I differentiate by > >>>> from enum import Enum >>>> colours = Enum('red', 'blue', 'green') >>>> for val in colours: >... print str(val) >... >red >blue >green > That corresponds to >>> from makeenum import makeEnum >>> Colours = makeEnum('Colours', 'red blue green') >>> for val in Colours: ... print str(val),'-(repr)->', repr(val) ... red -(repr)-> Colours.red blue -(repr)-> Colours.blue green -(repr)-> Colours.green I added the repr to show that the vals were instances of something, and they are actuall instances of the Colours type, which was uniquely created to represent the enumeration, along with its fixed set of internally cached immutable instances, references to which are returned by the Colours constructor (__new__) instead of creating potentially duplicate instances. So these instances can serve as sentinels too. The id's don't change, no matter how many you construct (of a given member of the instance set). Of course there are len(Colours) fixed (once created and cached) instances of Colours in all. >>> list(Colours) [Colours.red, Colours.blue, Colours.green] >>> map(str, Colours) ['red', 'blue', 'green'] >>> map(int, Colours) [0, 1, 2] >>> int(Colours.blue) 1 >>> Colours[1] Colours.blue >Why would the Enum *class* be iterable? That corresponds to asking why my makeEnum should be iterable, and the it is not. What makeEnum makes functionally corresponds to your Enum instance, except my "instance" is a unique manufactured class. > >> >> OTOH, the index values (and hence my enums) are[1] not very good >> >> as unique dict keys, since they compare[2] promiscuously with >> >> each other and other number types. >> >Indeed, that's why (in my design) the values from the enum are only >> >useful for comparing with each other. This, to me, seems to be the >> >purpose of an enumerated type. >> >> Have you tried yet to use two different enum instances as keys in >> the same dict? > >What do you mean by "enum instances"? I presume you mean "values from >a single enum". Yes, by analogy to your functionality, but since my "single enum" is actually a class returned by makeEnum, not an instance of Enum, i.e., >>> Colours and the "values" are immutable singleton instances that you can access via the class (which I gave some unusual capabilities -- i.e., some methods that apply to it as an ordered collection of immutable instances, and which aren't accessible as methods of the instances (though the instances have special methods of their own, and inherit methods from int). > >>>> colour_german = { colours.red: "rot", colours.green: "grün", >>>> colours.blue: "blau" } >>>> for val in colours: >... print colour_german[val] >... >rot >blau >grün That's a plain dict with colour "values" as keys. Same as (checking the order first to get the zip correspondence right ;-) >>> list(Colours) [Colours.red, Colours.blue, Colours.green] >>> colour_german = dict(zip(Colours, ('rot', 'blau', 'grün'))) >>> for val in Colours: ... print 'colour_german[%r] => %s' %(val, colour_german[val]) ... colour_german[Colours.red] => rot colour_german[Colours.blue] => blau colour_german[Colours.green] => grün > >> Then try to sort the keys(or items is the values are misc different >> enums). > >Oh, perhaps you mean "enum values from different enum instances". No, Yes, again by analogy. >those won't compare against each other; there's no meaningful >relationship, since different enum instances are conceptually >different types. Well, yes, I made that the strict default cmp, but I can optionally make "Enum instances" (makeEnum returned classes) whose values cmp differently. But now that I think of it, sorting is pretty controllable anyway, e.g, suppose we had a Coins enum: >>> Coins = makeEnum('Coins', 'penny nickel dime quarter')
Re: Underscores in Python numbers
On Sun, 20 Nov 2005 01:39:04 +, Steve Holden wrote: > Steven D'Aprano wrote: > [...] >> Likewise, base conversion into arbitrary bases is not, in my opinion, >> common enough a task that support for it needs to be built into the syntax >> for literals. If somebody cares enough about it, write a module to handle >> it and try to get it included with the Python standard modules. >> > In fact Icon managed to offer a syntax that allowed every base up to 36 > to be used: an "r" was used to indicate the radix of the literal, so hex > 453FF would be represented as "16r453FF". This worked fine. Upper- and > lower-case letters werw regarded as equivalent. Forth goes significantly further than that: you can tell the Forth interpreter what base you are using, and all numbers are then read and displayed using that base. Numbers were case sensitive, which meant Forth understood bases to at least 62. I don't remember whether it allows non-alphanumeric digits, and therefore higher bases -- I think it does, but am not sure. Nevertheless, I don't believe that sort of functionality belongs in the language itself. It is all well and good to be able to write 32r37gm, but how often do you really need to write numbers in base 32? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
PATH environment variable
O/S: Win2K Vsn of Python:2.4 Based on a search of other posts in this group, it appears as though os.environ['PATH'] is one way to obtain the PATH environment variable. My questions: 1) is it correct that os.environ['PATH'] contains the PATH environment variable? 2) are there other ways to obtain the PATH environment variable? if so, is one way of obtaining the PATH environment variable preferable to another way? -- http://mail.python.org/mailman/listinfo/python-list
Re: Immutable instances, constant values
On Sun, 20 Nov 2005 08:56:33 +1100, Ben Finney wrote: > Steven D'Aprano <[EMAIL PROTECTED]> wrote: >> On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote: >> > Is there any difference between a Python immutable value, and a >> > constant? I suppose "constant" also implies that the *name* binds >> > unchangeably to a particular value. Is that meaningful? >> >> That's precisely how I understand "constant" to be useful. > > The Python docs don't really talk about such a thing. However, the > None name cannot be re-bound. Is that all that's required to have a > "constant" in Python? I think None is a special case. The docs have said that None will become a keyword in the future. > If so, it's part of the assignment statement, and not something the > object itself can decide. True? Yes, that would be how I interpret constants: You want a name which can't be re-bound to something else. One work-around is to use the convention of writing the name in all caps: CONSTANT = some_value and then trust that your module user doesn't rebind CONSTANT. I'd like to see support for something a little stronger than just "cross your fingers and hope", without necessarily going all the way to Pascal's full enforcement of constants. "We're all adults here" -- if somebody *really* wants to rebind CONSTANT, I'm not going to stop them, but I want them to jump through a hoop to do it, as a reminder that the module creator thinks they shouldn't be doing it. The obvious analogy is with name mangling of __private attributes in classes. >> > How does one actually ensure an object is immutable? Is it a matter >> > of overriding a bunch of methods, or is ther a neater way? > > Really hoping someone can come up with an answer for this. So am I :-) Have you looked at the source for Frozenset? It was a pure Python module in Python 2.3, before becoming a built-in in 2.4. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Steven D'Aprano wrote: > That's a tad unfair. Dealing with numeric literals with lots of digits is > a real (if not earth-shattering) human interface problem: it is hard for > people to parse long numeric strings. In the wider world outside of IT, > people deal with long numeric digits by grouping. This is *exceedingly* > common: mathematicians do it, economists do it, everybody who handles long > numeric literals does it *except* computer language designers. However, what is the percentage of these big number literals appears in source code ? I believe most of them either appears in some data file(thus is nothing but string) or during data input(again string). Why change the language when we just want a smarter string converter ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Steve Holden wrote: > Being European myself I am well aware of the notational differences of > the different locales, and I am perfectly happy that users can enter > numbers in their preferred format when they execute a program. > > However, I am not happy about the idea that a program source would need > to be edited before it would work after being moved to another locale. > Huh ? Up to now, all I am talking about is making the three init function(int/float/decimal) to be smarter on coverting string to their type. It doesn't affect the code in anyway if you don't need it or want to use it. It is more like a helper function for the issue of people are so concern about the seperators in big numbers. It introduce no new syntax to the language at all. And should you say use the imaginary format "E500.000,23", it still works no matter where your program is running or what the hosting locale is. Don't understand what changes you are referring to. We are facing similar issue today. A typical case is MM/DD/ date format. Or may be I need to import text file(csv for example) which may already contain numbers in this format. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Steven D'Aprano wrote: [...] > Likewise, base conversion into arbitrary bases is not, in my opinion, > common enough a task that support for it needs to be built into the syntax > for literals. If somebody cares enough about it, write a module to handle > it and try to get it included with the Python standard modules. > In fact Icon managed to offer a syntax that allowed every base up to 36 to be used: an "r" was used to indicate the radix of the literal, so hex 453FF would be represented as "16r453FF". This worked fine. Upper- and lower-case letters werw regarded as equivalent. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
On Sat, 19 Nov 2005 13:08:57 -0500, Peter Hansen wrote: > Umm... in other words, "the underscore is under-used so let's assign > some arbitrary meaning to it" (to make the language more like Perl > perhaps?). +1 I *really* don't like the idea of allowing underscores in numeric literals. Firstly, for aesthetic reasons: I think 123_456 is seriously ugly. Secondly, for pragmatic reasons, I think it is too easy to mistype as 123-456. I know that Python can't protect you from typing 9-1 instead of 901, but why add special syntax that makes that sort of error MORE common?) > Or maybe one should instead interpret this as "numeric literals need > more bells and whistles, and I don't care which of these two we add, but > we have to do *something*!". :-) -1 That's a tad unfair. Dealing with numeric literals with lots of digits is a real (if not earth-shattering) human interface problem: it is hard for people to parse long numeric strings. In the wider world outside of IT, people deal with long numeric digits by grouping. This is *exceedingly* common: mathematicians do it, economists do it, everybody who handles long numeric literals does it *except* computer language designers. Depending on personal preference and context, we use any of comma, period, dash or space as a separator. Underscore is never used. Of these, the comma clashes with tuples, the period opens a rather large can of worms vis-a-vis internationalisation, and the dash clashes with the minus sign. Allowing spaces to group digits is subtle but effective, doesn't clash with other syntax, and is analogous to string concatenation. I don't believe it is either practical or desirable for a computer language to accept every conceivable digit separator in literals. If you need full support for internationalised numbers, that should go into a function. But the question of including a digit separator for numeric literals does solve a real problem, it isn't just meaningless bells and whistles. Likewise, base conversion into arbitrary bases is not, in my opinion, common enough a task that support for it needs to be built into the syntax for literals. If somebody cares enough about it, write a module to handle it and try to get it included with the Python standard modules. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: path module / class
Peter Hansen: > Compelling to whom? I wonder if it's even possible for Guido to find > compelling anything which obsoletes much of os.path and shutil and > friends (modules which Guido probably added first and has used the most > and feels most comfortable with). To me, most uses of path.py are small incremental improvements over os.path rather than being compelling. Do a number of small improvements add up to be large enough to make this change? There is a cost to the change as there will be two libraries that have to be known to understand code. Does someone have an example application that moved to path.py with a decrease in errors or noticeable decrease in complexity? Could all path manipulation code be switched or is coverage incomplete? The duplication argument should be answered by looking at all the relevant modules and finding a coherent set of features that work with path.py without overlap so that the obsolete methods can be deprecated. If adding path.py leads to a fuzzy overlapping situation where os.path is occasionally useful then we are complicating the user's life rather than simplifying it. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML generation vs PSP vs Templating Engines
[EMAIL PROTECTED] wrote: > I dislike embedding code or html in each other, apart from the > 'impurity' of mixing code and user interface it makes them inseparable. > > Using templates means that the code can work with different templates, > and this should be seamless, it also means that different code can be > used with the templates, for example if different languages are used. This seems to contradict your statement that you dislike 'embedding code or html in each other', since the scenarios you describe still involve embedding presentation logic in markup. (The only templating systems that *completely* separate logic from markup are the DOM-style ones.) I assume what you really meant is that you don't like embedding *model* logic in markup, which is generally good design practice. However, templating systems that use Python for presentation logic (Karrigell, PSP, Nevow, HTMLTemplate, etc) certainly don't force you to put model logic into the template; you are quite entitled to keep that separate as per MVC. They just don't *enforce* the model logic/presentation logic separation as some authoritarian custom language-based systems do. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to create a button in either pygame or livewires?
> Is there a way to create a button in either pygame or livewires, that is > able to be clicked and when clicked sends a command to restart the program? > You could try something like this using pygsear (http://www.nongnu.org/pygsear/) The button can call either start() which just makes a new Game instance in the same process, or full_restart() which starts a new process and quits the current one. from pygsear import Game, Widget from pygsear.locals import RED class G(Game.Game): def initialize(self): print 'starting up...' self.button = Widget.SpriteTextButton(self.window, "Restart", size=40, color=RED, padding=20) self.events.add(self.button.events) self.button.set_callback(self.restart) self.button.set_position((200, 100)) self.sprites.add(self.button) def restart(self, ev): print 'restarting...' #start() full_restart() self.quit = True def start(): g = G() g.mainloop() def full_restart(): import os import sys cmd = 'python %s &' % sys.argv[0] os.system(cmd) if __name__ == '__main__': start() -- http://mail.python.org/mailman/listinfo/python-list
Re: searching for files on Windows with Python
Peter Hansen wrote: > Kent Johnson wrote: >> import path >> files = path.path(pathToSearch).walkfiles(filename) > > A minor enhancement (IMHO) (though I certainly agree with Kent's > recommendation here): since there is nothing else of interest in the > "path" module, it seems to be a fairly common idiom to do "from path > import path" and skip the doubled "path.path" bit. Certainly it's your choice. I find most programs using path only reference path.path once, to create a starting path; other paths are created from that using files() or / etc. In this case it is less typing to say import path basePath = path.path(...) instead of from path import path basePath = path(...) from path import path only wins on number of chars if you reference path *three* times. YMMV :-) Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML generation vs PSP vs Templating Engines
I meant that it is not strictly necessary to use templates in Karrigell, although you can use Cheetah if you want. I'm not used to templates mainly because I'm familiar with the way PHP works and, for simple dynamic sites like those I work on, this is the simpliest approach. Another reason is that I'm a little bit lazy for learning yet another language, be it a python-like one or a template one. Also, I feel that Python is easy enough for having to resort to another language. I usually create my pages with Dreamweaver or any other visual tool, and once the design is ready, I add a few python lines to it which, combined with modules that are separated from the html code, work wonders on my sites. -- http://mail.python.org/mailman/listinfo/python-list
Re: textwrap.dedent() drops tabs - bug or feature?
Steven Bethard wrote: > Thanks for double-checking this for me. I looked at expand_tabs, and > it's part of the definition of the TextWrapper class, which is not > actually used by textwrap.dedent(). So I think the textwrap.dedent() > expanding-of-tabs behavior is still basically undocumented. Ah, good point. I saw dedent() in there with the wrap() and fill() convenience functions which use a TextWrapper internally, but you're quite right that dedent() is different, and in fact merely uses the expandtabs() functionality of the standard string class, so this has nothing to do with the expand_tabs attribute I pointed out. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Immutable instances, constant values
Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote: > > Is there any difference between a Python immutable value, and a > > constant? I suppose "constant" also implies that the *name* binds > > unchangeably to a particular value. Is that meaningful? > > That's precisely how I understand "constant" to be useful. The Python docs don't really talk about such a thing. However, the None name cannot be re-bound. Is that all that's required to have a "constant" in Python? If so, it's part of the assignment statement, and not something the object itself can decide. True? > > How does one actually ensure an object is immutable? Is it a > > matter of overriding a bunch of methods, or is ther a neater way? Really hoping someone can come up with an answer for this. > > Is it bad style to make a user-defined class that creates > > immutable objects? Why? > > I can't see why it would be bad style. That's what FrozenSet does. "from foo import *" is supported in the language, but is still bad style. FrozenSet was *added* to the language (2.2), so that's evidence that Guido thinks it's a good idea. But I'd still like direct discussion: is making one's class instances immutable bad style? -- \ "Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them." -- Henry L. Mencken | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
[EMAIL PROTECTED] wrote: > Steve Holden wrote: [...] >>I really wouldn't want it to become possible to write Python code in one >>locale that had to be edited before the numeric literals were valid in >>another locale. That way madness lies. > > That is the fact, from the very beginning. 1.234 striaightly speaking > can have different meaning,. So if you don't want, don't support it and > always use the non-European notation. > Being European myself I am well aware of the notational differences of the different locales, and I am perfectly happy that users can enter numbers in their preferred format when they execute a program. However, I am not happy about the idea that a program source would need to be edited before it would work after being moved to another locale. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Behaviour of enumerated types
Bengt Richter <[EMAIL PROTECTED]> wrote: > On Sat, 19 Nov 2005 11:10:42 +1100 (EST), Ben Finney <[EMAIL PROTECTED]> > wrote: > >Bengt Richter <[EMAIL PROTECTED]> wrote: > >> If [an enumeration has a fixed sequence], what is more natural > >> than using their index values as keys to other ordered info? > >I don't see why. If you want sequence numbers, use enumerate(). If > >not, the enum object itself can be used directly as an iterable. > > I changed mine so the enum _class_ is iterable, but enum instances > are not. I'm not really understanding your design. In my enum package, an enumeration is an instance of Enum. Those instances are iterable, producing EnumValue instances; the EnumValue instances are also available as named attributes of the Enum instance. >>> from enum import Enum >>> colours = Enum('red', 'blue', 'green') >>> for val in colours: ... print str(val) ... red blue green Why would the Enum *class* be iterable? > >> OTOH, the index values (and hence my enums) are[1] not very good > >> as unique dict keys, since they compare[2] promiscuously with > >> each other and other number types. > >Indeed, that's why (in my design) the values from the enum are only > >useful for comparing with each other. This, to me, seems to be the > >purpose of an enumerated type. > > Have you tried yet to use two different enum instances as keys in > the same dict? What do you mean by "enum instances"? I presume you mean "values from a single enum". >>> colour_german = { colours.red: "rot", colours.green: "grün", >>> colours.blue: "blau" } >>> for val in colours: ... print colour_german[val] ... rot blau grün > Then try to sort the keys(or items is the values are misc different > enums). Oh, perhaps you mean "enum values from different enum instances". No, those won't compare against each other; there's no meaningful relationship, since different enum instances are conceptually different types. > I hit that, and changed __cmp__ to compare (typename, other if not int subtype>) tuples. I think this is a flaw, based on expecting too strong a relationship between the enum value instance, and an integer value. > That sorts items grouped by enum type if they're keys. Why should colours.blue compare before fruits.orange? How is that meaningful? > >I think I've addressed all your current concerns; I don't believe > >an inherent correlation to integers is necessary at all. > > Necessary wasn't the question for me. It's whether it's desirable. > YMMV ;-) I'm still trying to understand what is served by having some exposed relationship between an enum value instance and an integer value. > >It's no more necessary than saying that ["a", "b", "c"] requires > >that there be some specific correlation between the values of that > >list and the integers 0, 1, 2. If you *want* such a correlation, in > >some particular case, use enumerate() to get it; but there's > >nothing about the values themselves that requires that > >correspondence. > > Yet it is comforting to know that ['a', 'b', 'c'][0] will interpret > the [0] to mean the first in the sequence (unless someone is doing a > list-like repr trick based on some other type ;-). Again, you're only talking about *sequence*, not correspondence to integers. Your case above isn't an argument in favour of "the 'a' value should coerce to the 0 value". Why then should an enum value instance coerce to any particular integer value? > The class methods are introduced via metaclass in the makeEnum factory > and it's a very hacky workaround for the fact that execution of a > class definition body only has local and module global namespace, so > you can't directly reference anything local to the factory function. Here you've lost me, since I don't understand why you want enumerations to be classes at all. Are you going to be making instances of an entire enumeration? If not, why make classes instead of objects? -- \ "The illiterate of the future will not be the person who cannot | `\ read. It will be the person who does not know how to learn." | _o__) -- Alvin Toffler | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML generation vs PSP vs Templating Engines
> No templates, no python-like or special languages, only pure and simple > python. > You can embedd python into html or, if it better suits your programming > style, you can embed html into python. Why don't you give it a try? I dislike embedding code or html in each other, apart from the 'impurity' of mixing code and user interface it makes them inseparable. Using templates means that the code can work with different templates, and this should be seamless, it also means that different code can be used with the templates, for example if different languages are used. The main advantage, for me, is that different outputs formats can be created without changing the code. If the user wants a set of data in a table then the html template is used, if they want a csv file of the data, that is just a different template name. A printed report: same code just a different template name. XML, simple text, postscript, EDIFACT file, all done with same code, different template. Just arrange for the name of the template file to be a parameter on the URL and the various outputs can be selected by the user. I did, however, write my own templating module, they are quite easy to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using win32ui.CreateFileDialog() to get the name of a file.
Okay, thank you. This worked very well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Speeding up multiple regex matches
OK that worked really well. In particular, the "lastindex" property of the match object can be used to tell exactly which group matched, without having to sequentially search the list of groups. In fact, I was able to use your idea to cobble together a poor man's lexer which I am calling "reflex" (Regular Expressions For Lexing). Here's an example of how it's used: # Define the states using an enumeration State = Enum( 'Default', 'Comment', 'String' ) # Create a scanner scanner = reflex.scanner( State.Default ) scanner.rule( "\s+" ) scanner.rule( "/\*", reflex.set_state( State.Comment ) ) scanner.rule( "[a-zA-Z_][\w_]*", KeywordOrIdent ) scanner.rule( "0x[\da-fA-F]+|\d+", token=TokenType.Integer ) scanner.rule( "(?:\d+\.\d*|\.\d+)(?:[eE]?[+-]?\d+)|\d+[eE]?[+-]?\d+", token=TokenType.Real ) # Multi-line comment state scanner.state( State.Comment ) scanner.rule( "\*/", reflex.set_state( State.Default ) ) scanner.rule( "(?:[^*]|\*(?!/))+" ) # Now, create an instance of the scanner token_stream = scanner( input_file_iter ) for token in token_stream: print token Internally, it creates an array of patterns and actions for each state. Then when you ask it to create a scanner instance, it combines all of the patterns into a large regular expression. Input lines are marched vs. this regex, and if a match succeeds, then the match object's 'lastindenx' property is used to look up the actions to perform in the array. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems returning/attaching cookies
NEVERMIND. My friend pointed out that I am simply hitting the wrong URL when trying to "test" whether I am logged in or not. The correct one is: http://www.dpreview.com/forums/editprofile.asp But I still have one question, if anyone knows -- why is it that when I print out the headers on my request object, they are empty? I thought that I should find the cookies there which are being sent back. This is what I thought the problem was. Thanks if anyone can explain how that works. John (PS i have stopped attacking the cookies now) [EMAIL PROTECTED] wrote: > Attacked is a piece of code which first hits the login page > successfully and receives back login cookies. But then when I attempt > to hit a page which is restricted to logged in users only, I fail. > > That seems to be because I am not successfully re-attaching the cookies > to the header portion of the this request. I have tried 2 methods > which should both work I think. The first was to use install_opener to > attach the cookie handler back to urlopen. The second method was to > use the cookiehandler method add_cookie_header. But in both cases, > before sending out the 2nd request, it seems to have empty headers -- > which indicates to me that the necessary cookies have not been > attacked. > > I also tryed messing with the policy quite a bit, thinking that might > be causing the cookies not to be returned. First I used the default, > then set some flags on the default, then even overrode methods on the > default to make it as lenient as possible. This had no apparent > effect. > > Thanks a lot! > > Below I have pasted the most relevant code section, as well as my full > code file. Apologies for all the comments, but I wanted to show what I > had tried. > - > RELEVANT CODE (snipped from full code) > > # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE > the_url = > "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp"; > req = urllib2.Request(the_url) > #print "headers:", req.headers > #cj.add_cookie_header(req) > > # EXPECT THESE HEADERS TO BE NON-EMPTY - BUT THEY ARE EMPTY, > # NO COOKIES RETURNED? > print "headers:", req.headers > > # THIS OPEN FAILS - I GET - "NEED TO LOGIN" PAGE > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > - > FULL CODE > > #!/usr/bin/python > > import urllib > import urllib2 > import re > import os > from cookielib import * > > class MyCookiePolicy(DefaultCookiePolicy): > def __init__(self): > DefaultCookiePolicy.__init__(self, rfc2965=True, > hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) > def set_ok(self, cookie, request): > return True > def return_ok(self, cookie, request): > return True > def domain_return_ok(self, cookie, request): > return True > def path_return_ok(self, cookie, request): > return True > > the_url = 'http://www.dpreview.com/forums/login_post.asp' > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values = { > 'email' : '', > 'password' : '', > #"remember" : "checked", # <- create permanent cookie > 'jump' : "/forums/" > } > # also "remember" : "remember" > > # INITIAL REQUEST WITH USER INFO > headers = { 'User-Agent' : user_agent } > data = urllib.urlencode(values) > req = urllib2.Request(the_url, data, headers) > > # COOKIE POLICY > # tried using several configurations of the default cookie policy > #policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False, > strict_ns_domain=DefaultCookiePolicy.DomainLiberal) > # tried using my own custom cookie policy > #policy = MyCookiePolicy() > policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False) > > # CREATE COOKIE JAR WITH POLICY > cj = MozillaCookieJar() > cj.set_policy(policy) > > # CREATE OPENER, AND OPEN PAGE > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > # SHOW COOKIES COLLECTED - LOOKS GOOD HERE > for c in cj: > print "COOKIE:", c > print "URL:", handle.geturl() > print "INFO:", handle.info() > > #DEMONSTRATE WE'RE LOGGED IN > for line in the_page.split('\n'): > line = line.strip() > if re.search("Welcome to the", line): > print "MESSAGE:", line > > # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE > # - tried using the install_opener above > # - tried using add_cookie_header > # - either way, can't seem to get cookies in the header of this request > the_url = > "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp"; > req = urllib2.Request(the_url) > #print "headers:", req.headers > #cj.add_cookie_header(req) > > # EXPECT THESE HEADERS TO BE NON-EMPTY > print "headers:", req.headers > #handle = opener.open(req) > handle = urllib2.urlopen(req) > the_page = handle.read() > > # THIS ALSO PROVES LOGIN-STATE WAS LOST > for line in the_page.split('\n
Re: Underscores in Python numbers
Steve Holden wrote: > [EMAIL PROTECTED] wrote: > > Stefan Rank wrote: > > > >>The other idea of teaching int() about separator characters has > >>internationalis/zation issues: > >>In many European countries, one would naturally try:: > >> > >> int('500.000,23') > >> > >>instead of:: > >> > >> int('500,000.23') > > > > > > That is why I said > > > > "Of course, also support the locale variant where the meaning of "," > > and > > "." is swapped in most European countries. " > > > > We are seeing the same about base 2, 8, 10, 16. > > > > May be : > > > > int("E500.000,23") > > > > as we are using : > > > > 0x > > > > already for hex number > > > I really wouldn't want it to become possible to write Python code in one > locale that had to be edited before the numeric literals were valid in > another locale. That way madness lies. That is the fact, from the very beginning. 1.234 striaightly speaking can have different meaning,. So if you don't want, don't support it and always use the non-European notation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
Thanks Diez and Peter, Just what I was looking for. In "Library Reference" heading 3.11.1 Types and members I found the info about the method you described. I also made a little function to print out not just the name of the function but also the parameter list. Here it is # fname.py import sys, string def cap(s, n): print string.replace("".join([sys._getframe().f_code.co_name, \ repr(sys._getframe().f_code.co_varnames)]), "\'", "") cap('Hello', 'Bob') Running this yields the result cap(s, n) -- http://mail.python.org/mailman/listinfo/python-list
Re: textwrap.dedent() drops tabs - bug or feature?
Peter Hansen wrote: > Steven Bethard wrote: > >> Note that even though the tabs are internal, they are still removed by >> textwrap.dedent(). The documentation[1] says: > > ... > >> So it looks to me like even if this is a "feature" it is undocumented. >> I'm planning on filing a bug report, but I wanted to check here first >> in case I'm just smoking something. > > While I wouldn't say it's obvious, I believe it is (indirectly?) > documented and deliberate. > > Search for this in the docs: > """ > expand_tabs > (default: True) If true, then all tab characters in text will be > expanded to spaces using the expandtabs() method of text. > """ Thanks for double-checking this for me. I looked at expand_tabs, and it's part of the definition of the TextWrapper class, which is not actually used by textwrap.dedent(). So I think the textwrap.dedent() expanding-of-tabs behavior is still basically undocumented. I looked at the source code, and the culprit is the first line of the function definition: lines = text.expandtabs().split('\n') I filed a bug_ report, but left the Category unassigned so that someone else can decide whether it's a doc bug or a code bug. STeVe .. _bug: http://python.org/sf/1361643 -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter from Vis. BASIC
[EMAIL PROTECTED] wrote: >>I want to do the same thing in Python/Tkinter: >> >> # Wait for network to recognize the workstation: >> while os.system("slist") != 0: >> self.notify["fg"] = randcolor() >> # how do I refresh label l3 at this point? >> time.sleep(3) > I know of an update_idletask() method, look it up in the tkinter doc to > see if that's what you need! > Thanks. I did a dir(label_object) and saw update() and update_idletasks(). updeate() seems to do the trick. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you set a class instance's attributes to zero by setting the instance to zero?
On 19 Nov 2005 05:29:07 -0800 "Gerard Flanagan" <[EMAIL PROTECTED]> wrote: > If I have the Vector class below, is there a means by > which I can have the following behaviour > > > >>>A = Vector(1, 2) > >>>print A > (1, 2) > >>>A = 0 > >>>print A > (0, 0) As has already been mentioned, "A = 0" rebinds the name "A" to the object "0" so there's no way it can mutate the object A. However, you could create an object "Origin" to use as a vector zero: Origin = Vector(0,0) Or if you want to be shorter, more poetic, and make future maintainers curse you, you can call it "O": O = Vector(0,0) ;-) -- Terry Hancock ([EMAIL PROTECTED]) Anansi Spaceworks http://www.AnansiSpaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
[EMAIL PROTECTED] wrote: [edited slightly] > def cap(): > print "the name of this function is " + "???" > cap () sys._getframe() would help you here: >>> import sys >>> sys._getframe() >>> def f(): ... global x ... x = sys._getframe() ... >>> f() >>> x >>> dir(x) [..., 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', ...] >>> dir(x.f_code) [...'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] >>> x.f_code.co_name 'f' So your function could be: >>> import sys >>> def cap(): ... print 'function name is', sys._getframe().f_code.co_name ... >>> cap() function name is cap -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Can a function access its own name?
[EMAIL PROTECTED] wrote: > Look at the code below: > > # mystringfunctions.py > > def cap(s): > print s > print "the name of this function is " + "???" > > cap ("hello") > > > Running the code above gives the following output > > >>> > hello > the name of this function is ??? > >>> > > I would like the output to be > > >>> > hello > the name of this function is cap > >>> > > Is that possible ? Yes, use the moduloe inspect to access the current stack frame: def handle_stackframe_without_leak(): frame = inspect.currentframe() try: print inspect.getframeinfo(frame)[2] finally: del frame Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
[EMAIL PROTECTED] wrote: > Steven D'Aprano: >>Perhaps Python should concatenate numeric literals at compile time: >>123 456 is the same as 123456. > > I think using the underscore it is more explicit: > n = 123_456 > > Alternatively the underscore syntax may be used to separate the number > from its base: > 22875 == 22875_10 == 595b_16 == 123456_7 > But probably this is less commonly useful (and not much explicit). Umm... in other words, "the underscore is under-used so let's assign some arbitrary meaning to it" (to make the language more like Perl perhaps?). Or maybe one should instead interpret this as "numeric literals need more bells and whistles, and I don't care which of these two we add, but we have to do *something*!". :-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Roy Smith>We already have a perfectly good syntax for entering octal and hex integers, There is this syntax: 1536 == int("600", 16) that accepts strings only, up to a base of 36. There are the hex() and oct() functions. There is the %x and %o sintax, that isn't easy to remember. There are the 0x600 and 0600 syntaxes that probably look good only from the point of view of a C programmer. I think some cleaning up, with a simpler and more consistent and general way of converting bases, can be positive. But probably no one shares this point of view, and compatibility with C syntax is probably positive, so you are right. I am still learning the correct way of thinking in python. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Using win32ui.CreateFileDialog() to get the name of a file.
Joey C. wrote: > Hello. > I'm writing a program that creates a series of batch operations to > convert movies to be used on iPodLinux. The programs that do the > encoding and conversions are seperate from mine and all mine does is > use os.system() to call the program. > > However, it needs to get an input file and an output file. Originally > I was using just raw input, but I got adventuresome and decided to try > win32ui.CreateFileDialog(). But this will only open or save a file and > its output will be either 1 or a failure. How might I go about using > it to get the _file name_ of a file. > For example. > Box appears asking user to find a file they want. They double click on > the file. Let's call it C:\Video.avi > Then another dialog box appears asking them where to save it. They > save it at C:\iPodVideo.avi. > > Now the Python program extracts the name of these files and then uses > os.system() to run: > mencoder.exe -[parameters] C:\Video.avi -o C:\iPodVideo.avi > > Note that I'm not actually inputting the contents of the file, I'm just > passing the file name along. > > How might I do this? Thanks. > After you've had the user interact with the dialog you should call its GetFileName() method. The interactive interpreter can be useful in finding things like this out (though many details of objects can remain hidden in the Windows environment): >>> dir(d) ['GetFileExt', 'GetFileName', 'GetFileTitle', 'GetPathName', 'GetPathNames', 'GetReadOnlyPref', 'SetOFNInitialDir', 'SetOFNTitle'] >>> d.Show() regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Can a function access its own name?
Look at the code below: # mystringfunctions.py def cap(s): print s print "the name of this function is " + "???" cap ("hello") Running the code above gives the following output >>> hello the name of this function is ??? >>> I would like the output to be >>> hello the name of this function is cap >>> Is that possible ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python weak on the web side?
Tony wrote: > If I'd like to learn Python for web-development, what are the options > available? > > Thanks. tony Nov 18th: http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/c23b12dc0edf8af0/19f859dc43c77ac1#19f859dc43c77ac1 Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: termios.tcgetattr(fd) error: (22, 'Invalid argument')
To provide some feedback: As Grant Edwards posted in this list, I was running my code inside of IDE that replaces sys.stdin with some other. While running the program from a shell prompt, everything goes fine. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python weak on the web side?
On Sunday 20 November 2005 00:24, Tony wrote: > If I'd like to learn Python for web-development, what are the options > available? > > Thanks. tony A nice framework is CherryPy: http://www.cherrypy.org or Turbogears, which is based on CherryPy: http://www.turbogears.org/ Michael. -- http://mail.python.org/mailman/listinfo/python-list
Is Python weak on the web side?
If I'd like to learn Python for web-development, what are the options available? Thanks. tony -- http://mail.python.org/mailman/listinfo/python-list
Re: deleting registry keys and value
Looks OK to me. Just tried on my network - works with no exceptions -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
Thanks for the feedback, people. I actually only need the "bar" part (instance methods). I added the "foo" part to generalize the question without really thinking it through first. Still, it has gotten me more information than I ever imagined. So thanks again. g -- http://mail.python.org/mailman/listinfo/python-list
Using win32ui.CreateFileDialog() to get the name of a file.
Hello. I'm writing a program that creates a series of batch operations to convert movies to be used on iPodLinux. The programs that do the encoding and conversions are seperate from mine and all mine does is use os.system() to call the program. However, it needs to get an input file and an output file. Originally I was using just raw input, but I got adventuresome and decided to try win32ui.CreateFileDialog(). But this will only open or save a file and its output will be either 1 or a failure. How might I go about using it to get the _file name_ of a file. For example. Box appears asking user to find a file they want. They double click on the file. Let's call it C:\Video.avi Then another dialog box appears asking them where to save it. They save it at C:\iPodVideo.avi. Now the Python program extracts the name of these files and then uses os.system() to run: mencoder.exe -[parameters] C:\Video.avi -o C:\iPodVideo.avi Note that I'm not actually inputting the contents of the file, I'm just passing the file name along. How might I do this? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Problems returning/attaching cookies
Attacked is a piece of code which first hits the login page successfully and receives back login cookies. But then when I attempt to hit a page which is restricted to logged in users only, I fail. That seems to be because I am not successfully re-attaching the cookies to the header portion of the this request. I have tried 2 methods which should both work I think. The first was to use install_opener to attach the cookie handler back to urlopen. The second method was to use the cookiehandler method add_cookie_header. But in both cases, before sending out the 2nd request, it seems to have empty headers -- which indicates to me that the necessary cookies have not been attacked. I also tryed messing with the policy quite a bit, thinking that might be causing the cookies not to be returned. First I used the default, then set some flags on the default, then even overrode methods on the default to make it as lenient as possible. This had no apparent effect. Thanks a lot! Below I have pasted the most relevant code section, as well as my full code file. Apologies for all the comments, but I wanted to show what I had tried. - RELEVANT CODE (snipped from full code) # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE the_url = "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp"; req = urllib2.Request(the_url) #print "headers:", req.headers #cj.add_cookie_header(req) # EXPECT THESE HEADERS TO BE NON-EMPTY - BUT THEY ARE EMPTY, # NO COOKIES RETURNED? print "headers:", req.headers # THIS OPEN FAILS - I GET - "NEED TO LOGIN" PAGE #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() - FULL CODE #!/usr/bin/python import urllib import urllib2 import re import os from cookielib import * class MyCookiePolicy(DefaultCookiePolicy): def __init__(self): DefaultCookiePolicy.__init__(self, rfc2965=True, hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) def set_ok(self, cookie, request): return True def return_ok(self, cookie, request): return True def domain_return_ok(self, cookie, request): return True def path_return_ok(self, cookie, request): return True the_url = 'http://www.dpreview.com/forums/login_post.asp' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = { 'email' : '', 'password' : '', #"remember" : "checked", # <- create permanent cookie 'jump' : "/forums/" } # also "remember" : "remember" # INITIAL REQUEST WITH USER INFO headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values) req = urllib2.Request(the_url, data, headers) # COOKIE POLICY # tried using several configurations of the default cookie policy #policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal) # tried using my own custom cookie policy #policy = MyCookiePolicy() policy = DefaultCookiePolicy(rfc2965=True, hide_cookie2=False) # CREATE COOKIE JAR WITH POLICY cj = MozillaCookieJar() cj.set_policy(policy) # CREATE OPENER, AND OPEN PAGE opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() # SHOW COOKIES COLLECTED - LOOKS GOOD HERE for c in cj: print "COOKIE:", c print "URL:", handle.geturl() print "INFO:", handle.info() #DEMONSTRATE WE'RE LOGGED IN for line in the_page.split('\n'): line = line.strip() if re.search("Welcome to the", line): print "MESSAGE:", line # NOW GO TO PAGE RESTRICTED TO LOGGED IN PEOPLE # - tried using the install_opener above # - tried using add_cookie_header # - either way, can't seem to get cookies in the header of this request the_url = "http://www.dpreview.com/forums/login.asp?jump=editprofile.asp"; req = urllib2.Request(the_url) #print "headers:", req.headers #cj.add_cookie_header(req) # EXPECT THESE HEADERS TO BE NON-EMPTY print "headers:", req.headers #handle = opener.open(req) handle = urllib2.urlopen(req) the_page = handle.read() # THIS ALSO PROVES LOGIN-STATE WAS LOST for line in the_page.split('\n'): line = line.strip() if re.search("To access", line): print "MESSAGE:", line print "URL:", handle.geturl() print "INFO:", handle.info() -- http://mail.python.org/mailman/listinfo/python-list
Re: what happens when the file begin read is too big for all lines to be read with "readlines()"
Just try it, it is not that hard ... ;-) /Jean Brouwers PS) Here is what happens on Linux: $ limit vmemory 1 $ python ... >>> s = file().readlines() Traceback (most recent call last): File "", line 1 in ? MemoryError >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie-question about a list
On 19 Nov 2005 07:06:30 -0800, [EMAIL PROTECTED] wrote: >I've seen this construct in a script > [x.capitalize() for x in ['a','b', 'c']] >['A', 'B', 'C'] > >I tried another myself > [x+1 for x in [1,2,3]] >[2, 3, 4] > >Apparently you can do >[function(x) for x in list] > >I tried to find a description of this in "Library Reference" but >couldn't find it. Could somebody direct me where this type of construct >is described. > It's called a list comprehension. You can find that term in various indices of the various docs. In a minute I found these. I'm sure there's more if you google. http://docs.python.org/ http://docs.python.org/tut/node18.html#l2h-61 http://docs.python.org/ref/lists.html#l2h-345 Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
[EMAIL PROTECTED] wrote: > Stefan Rank wrote: > >>The other idea of teaching int() about separator characters has >>internationalis/zation issues: >>In many European countries, one would naturally try:: >> >> int('500.000,23') >> >>instead of:: >> >> int('500,000.23') > > > That is why I said > > "Of course, also support the locale variant where the meaning of "," > and > "." is swapped in most European countries. " > > We are seeing the same about base 2, 8, 10, 16. > > May be : > > int("E500.000,23") > > as we are using : > > 0x > > already for hex number > I really wouldn't want it to become possible to write Python code in one locale that had to be edited before the numeric literals were valid in another locale. That way madness lies. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <[EMAIL PROTECTED]> wrote: >Hi all, > >Suppose you have this class: > >class foo: >def bar(): > >Suppose you also have the strings "foo" and "bar". How can you obtain the >function foo.bar()? > >Surely somebody knows.. > Sorry, clean forgot about the strings. >>> class foo: ... def bar(self): return self, 'bar is the name' ... >>> # The definition is at global scope, so 'foo' will show up ... # in the globals() directory, which we can access with appended ['foo'] ... >>> globals()['foo'] >>> #if you want the 'bar' attribute using the string ... getattr(globals()['foo'], 'bar') >>> foo.bar Note that getting an attribute does some "binding" magic if the attribute has certain qualitites. In this case the bar function is associated with the foo class to become an "unbound method" Nit: usual convention is to spell class names with leading upper case. Then you can e.g. use the lower case same name for an instance of the class without confusions. Nit2: using new-style classes, which derive from object (or also other bases, but at least object or type) is now recommended, so you get the full-fledged attribute machinery that supports much of the latest magic. So write the above more like class Foo(object): def bar(self): return self, 'bar is the name' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
guy lateur wrote: > Hi all, > > Suppose you have this class: > > class foo: > def bar(): > > Suppose you also have the strings "foo" and "bar". How can you obtain the > function foo.bar()? > > Surely somebody knows.. > > TIA, > g > > Would that do? >>> class foo: @staticmethod def bar(): pass >>> foo.bar >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter from Vis. BASIC
Terrance N. Phillip wrote: > In VB, an easy way I indicate progress is something like > do while > lblNotify.foreground = randomcolor > lblNotify.refresh <--- > > loop > > I want to do the same thing in Python/Tkinter: > > # Wait for network to recognize the workstation: > while os.system("slist") != 0: > self.notify["fg"] = randcolor() > # how do I refresh label l3 at this point? > time.sleep(3) > > I've tried self.notify.grid() (I'm using the grid geometry manager > throughout), but that didn't work, and there is no redraw() or refresh() > method that I can see. I know of an update_idletask() method, look it up in the tkinter doc to see if that's what you need! -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
[EMAIL PROTECTED] wrote: > Alternatively the underscore syntax may be used to separate the number > from its base: > 22875 == 22875_10 == 595b_16 == 123456_7 > But probably this is less commonly useful (and not much explicit). We already have a perfectly good syntax for entering octal and hex integers, because those are commonly used in many applications. There are, on occasion, need for other bases, but they are so rare, specialized, and non-standard (RFC-1924, for example, uses an interesting flavor of base-85) that having syntax built into the language to support them would be completely unjustified. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie-question about a list
This type of construct seems to be called "list comprehension". Googling for Python "list comprehension" gives a lot of hints that describe the construct. -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <[EMAIL PROTECTED]> wrote: >Hi all, > >Suppose you have this class: > >class foo: >def bar(): > >Suppose you also have the strings "foo" and "bar". How can you obtain the >function foo.bar()? Why don't you type these things into an interactive python session and see what happens? Also, foo.bar will be an unbound method of foo, not a function per se. You could experiment a little, e.g., >>> class foo: ... def bar(): ... File "", line 3 ^ IndentationError: expected an indented block >>> class foo: ... def bar(): return 'bar is the name' # you could have done this ... >>> foo.bar() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead) >>> foo() <__main__.foo instance at 0x02EF3D8C> >>> foo.bar(foo()) Traceback (most recent call last): File "", line 1, in ? TypeError: bar() takes no arguments (1 given) >>> class foo: ... def bar(self): return self, 'bar is the name' # you could have done this ... >>> fooinst = foo() >>> fooinst <__main__.foo instance at 0x02EF756C> >>> foo.bar(fooinst) (<__main__.foo instance at 0x02EF756C>, 'bar is the name') >>> fooinst.bar > >>> fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') >>> foo.bar.im_func >>> foo.bar.im_func('first arg') ('first arg', 'bar is the name') >>> fooinst.bar > >>> fooinst.bar.im_func >>> fooinst.bar.im_func(1234) (1234, 'bar is the name') >>> fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') >>> foo.bar(333) Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method bar() must be called with foo instance as first argument (got int inst ance instead) >>> foo.bar(fooinst) (<__main__.foo instance at 0x02EF756C>, 'bar is the name') Someone can explain. If you do some of your own work, it will help even the load. Have you looked at any documentation? Start at http://www.python.org/ and click a few things. There seems to be a beginners guide link under documentation in the sidebar to the left ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: examining python objects
Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a écrit : > > Is there a function/class/module/whatever I can use to > > look at objects? I want something that will print the object's > > value (if any) in pretty-printed form, and list all it's attributes > > and their values. And do all that recursively. > > I want to be able to find out everything about an object that > > Python can introspectively find out. > > Then check the inspect module I want a callable, ready-to-use class or function. Inspect provides soime funtions that would be useful for wrinting such a class or function, but does not provide one. I seems that nobody who has written or used such a tool reads this group, or feels like responding. FWIW, (for anyone looking for something similar in the future) I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951 which will format and print an object's attributes. By combining that and pprint in the Python distrib, I think can coble up what I am looking for. Still, it is discouraging that such a basic thing is not provided with python, or at lleast easily available in some library. -- http://mail.python.org/mailman/listinfo/python-list
Re: examining python objects
Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a écrit : > > Is there a function/class/module/whatever I can use to > > look at objects? I want something that will print the object's > > value (if any) in pretty-printed form, and list all it's attributes > > and their values. And do all that recursively. > > I want to be able to find out everything about an object that > > Python can introspectively find out. > > Then check the inspect module I want a callable, ready-to-use class or function. Inspect provides soime funtions that would be useful for wrinting such a class or function, but does not provide one. I seems that nobody who has written or used such a tool reads this group, or feels like responding. FWIW, (for anyone looking for something similar in the future) I found http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/137951 which will format and print an object's attributes. By combining that and pprint in the Python distrib, I think can coble up what I am looking for. Still, it is discouraging that such a basic thing is not provided with python, or at lleast easily available in some library. -- http://mail.python.org/mailman/listinfo/python-list
newbie-question about a list
I've seen this construct in a script >>> [x.capitalize() for x in ['a','b', 'c']] ['A', 'B', 'C'] I tried another myself >>> [x+1 for x in [1,2,3]] [2, 3, 4] >>> Apparently you can do [function(x) for x in list] I tried to find a description of this in "Library Reference" but couldn't find it. Could somebody direct me where this type of construct is described. Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt layout question: QScrollView and QGridLayout?
Thank you Don, thank you David, I was convinced that there must be a simple solution at hand. A dummy widget! It does work to my needs. Don's ScrollToolView is very interesting though not yet the right tool for my actual application, but I've got some more ideas for long winter nights ... All the best Volker -- http://mail.python.org/mailman/listinfo/python-list
Tkinter from Vis. BASIC
In VB, an easy way I indicate progress is something like do while lblNotify.foreground = randomcolor lblNotify.refresh <--- loop I want to do the same thing in Python/Tkinter: # Wait for network to recognize the workstation: while os.system("slist") != 0: self.notify["fg"] = randcolor() # how do I refresh label l3 at this point? time.sleep(3) I've tried self.notify.grid() (I'm using the grid geometry manager throughout), but that didn't work, and there is no redraw() or refresh() method that I can see. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
Sybren Stuvel wrote: > [EMAIL PROTECTED] enlightened us with: > > Of course, also support the locale variant where the meaning of "," > > and "." is swapped in most European countries. > > This is exactly why I wouldn't use that notation. What happens if it > is hardcoded into the source? I mean, that's what we're talking about. > Then the program would have to have an indication of which locale is > used for which source file. Without that, a program would be > interpreted in a different way on different computers. I think that > would be rather messy. > As mentioned in another post, we have that situation in all other places. Such as mm/dd/ vs dd/mm/ decimal("10.23") - would european people expect decimal("10,23") to work ? 0x - a notation for base 16 why can't I have "E100.000,23" to mean "100,000.23" ? Nothing but notation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Underscores in Python numbers
[EMAIL PROTECTED] enlightened us with: > Of course, also support the locale variant where the meaning of "," > and "." is swapped in most European countries. This is exactly why I wouldn't use that notation. What happens if it is hardcoded into the source? I mean, that's what we're talking about. Then the program would have to have an indication of which locale is used for which source file. Without that, a program would be interpreted in a different way on different computers. I think that would be rather messy. I'm in favour of using spaces or underscores. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
guy lateur wrote: > Hi all, > > Suppose you have this class: > > class foo: > def bar(): > > Suppose you also have the strings "foo" and "bar". How can you obtain the > function foo.bar()? > > Surely somebody knows.. getattr helps. However, your example won't work: it misses either a staticmethod-declaration, or a self-argument, or a classmethod and cls-argument. So unless we know if bar shall be an instance.method or not, it's hard to tell what exactly you want. Because you could want getattr(getattr(mymodule, "foo"), "bar") Or getattr(getattr(mymodule, "foo")(), "bar") (notice the parentheses) or getattr(getattr(locals(), "foo"), "bar") or getattr(getattr(globals(), "foo"), "bar") Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: about try and exception
Bruno Desthuilliers enlightened us with: > (Carl's top-post corrrected. Carl, please do not top-post) If you correct people and ask them to alter their posting style, at least make sure you post in a proper way. Snip what you're not directly referring to, so people don't have to scroll in order to start reading your post. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining an member function by name
f = getattr(obj,"bar") f() guy lateur wrote: > Hi all, > > Suppose you have this class: > > class foo: > def bar(): > > Suppose you also have the strings "foo" and "bar". How can you obtain the > function foo.bar()? > > Surely somebody knows.. > > TIA, > g -- http://mail.python.org/mailman/listinfo/python-list
Obtaining an member function by name
Hi all, Suppose you have this class: class foo: def bar(): Suppose you also have the strings "foo" and "bar". How can you obtain the function foo.bar()? Surely somebody knows.. TIA, g -- http://mail.python.org/mailman/listinfo/python-list
Re: Immutable instances, constant values
On Sat, 19 Nov 2005 21:45:40 +1100, Steven D'Aprano <[EMAIL PROTECTED]> wrote: >On Fri, 18 Nov 2005 14:32:46 +1100, Ben Finney wrote: > >> Is there any difference between a Python immutable value, and a >> constant? I suppose "constant" also implies that the *name* binds >> unchangeably to a particular value. Is that meaningful? > >That's precisely how I understand "constant" to be useful. Consider: > >c = 2.9979246e+08 # speed of light in metres per second > >def energy(mass): >"""Converts mass in kilograms to energy in joules""" >return mass*c**2 > >That works fine until the name c is rebound to some other value. The fact >that the float object 2.9979246e+08 is immutable is necessary but not >sufficient. > > >> How does one actually ensure an object is immutable? Is it a matter of >> overriding a bunch of methods, or is ther a neater way? >> >> Is it bad style to make a user-defined class that creates immutable >> objects? Why? > >I can't see why it would be bad style. That's what FrozenSet does. > >> In the case of 'enum', can anyone argue for or against an enumerated >> type being immutable? Its values being constant? > >According to Gary Larson, there are four fundamental types of people. You >can tell them apart from their reaction to being given a half-filled glass: > >"The glass is half full." > >"The glass is half empty." > >"Half full. No, half empty! No, half full. Wait... what was the question?" > >"Hey! I ordered a cheeseburger!" > >We might handle this with: > >states = Enum("full", "empty", "indeterminate", "cheeseburger") > >which then get referred to with: > >states.full >states.empty >states.indeterminate >states.cheeseburger > >I might decide that "argumentative" is a better label than "cheeseburger", >and mutate the appropriate enum value. What should happen? I see three >possibilities: > >(1) states.cheeseburger still hangs around, but is not equivalent to >states.argumentative, in much the same way that reloading a module can >leave obsolete objects in your namespace (reloading doesn't automatically >cause names that point to objects from a module to rebind to new objects). > >(2) references to states.cheeseburger raise an exception > >(3) references to states.cheeseburger are equivalent to >states.argumentative. A rose by any other name. It shouldn't matter what >label we put on the enums, in principle. > >Possibility (1) is obviously Bad with a Capital B, and should be avoided. > >Possibility (2) has the saving grace that it is no different to what >happens if you rebind class attributes. There is an argument that if you >can rebind class attributes, you should be able to rebind enums and face >the consequences (good bad or indifferent) as best you can. > >Possibility (3) is the logical solution. It shouldn't matter what labels >we put on the enums. But I fear not practical unless the enums are >implemented as Singletons (multitons?), and perhaps not even then. > >Alternatively, you could bypass the whole problem by making enums >immutable. > as in >>> from makeenum import makeEnum >>> states = makeEnum('states', 'full empty indeterminate cheeseburger') >>> for state in states: print repr(state) ... states.full states.empty states.indeterminate states.cheeseburger >>> for state in states: print state ... full empty indeterminate cheeseburger >>> states >>> states[1] states.empty >>> states['empty'] states.empty >>> states[states.empty] states.empty >>> list(states) [states.full, states.empty, states.indeterminate, states.cheeseburger] >>> map(str, states) ['full', 'empty', 'indeterminate', 'cheeseburger'] >>> len(states) 4 >>> states.full in states True >>> int(states.full) 0 >>> map(int, states) [0, 1, 2, 3] >>> 'ABC'[states.empty] 'B' >>> states.empty == 1 Traceback (most recent call last): File "", line 1, in ? File "makeenum.py", line 80, in __cmp__ assert type(self)==type(other), ( AssertionError: incompatible cmp types: states vs int We can optionally make cmp work on int(self), int(other) for the enum... >>> states = makeEnum('states', 'full empty indeterminate cheeseburger', >>> strict=int) >>> 'ABC'[states.empty] 'B' >>> states.empty == 1 True >>> type(states.empty) >>> a = list(states) >>> b = list(states) >>> [x is y for x,y in zip(a,b)] [True, True, True, True] >>> [x is y for x,y in zip(a,states)] [True, True, True, True] (all the states are effectively singleton instances of the states class) and immutable: >>> states.full = 'topped_off' Traceback (most recent call last): File "", line 1, in ? File "makeenum.py", line 34, in __setattr__ raise AttributeError, '%s attributes may not be modified'%cls.__name__ AttributeError: states attributes may not be modified >>> states.full.foo = 'trick' Traceback (most recent call last): File "", line 1, in ? File "makeenum.py", line 103, in __setattr__ raise AttributeError, '%s instance attributes may not be set'% type(self)
Re: what happens when the file begin read is too big for all lines to beread with "readlines()"
Ross Reyes wrote: > When I use readlines, what happens if the number of lines is huge?I have > a very big file (4GB) I want to read in, but I'm sure there must be some > limitation to readlines and I'd like to know how it is handled by python. readlines itself has no limitation, but it reads all the lines into memory, so you'll probably run out of memory before the call returns. Python raises a MemoryError exception when this happens. > I am using it like this: > slines = infile.readlines() # reads all lines into a list of strings called > "slines" as others have pointed out, an iterator is the best way to solve this. the iterator code will read blocks of data from the file, and return the lines one by one. if you need to support older versions of Python, xreadlines or repeated calls to readlines(N) can be useful (see the third example on this page for an example: http://effbot.org/zone/readline-performance.htm ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you set a class instance's attributes to zero by setting theinstance to zero?
Gerard Flanagan wrote: > If I have the Vector class below, is there a means by which I can have > the following behaviour > A = Vector(1, 2) print A > (1, 2) A = 0 that operation rebinds A; it doesn't affect the Vector instance in any way. more here: http://effbot.org/zone/python-objects.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you set a class instance's attributes to zero by setting the instance to zero?
Gerard Flanagan wrote: > Hello > > If I have the Vector class below, is there a means by which I can have > the following behaviour > > > A = Vector(1, 2) print A > > (1, 2) > A = 0 print A > > (0, 0) > > If there is such a means, will it still work with the __slots__ > attribution uncommented? No, you can't. The reason is that python doesn't have an assignment operator as e.g. C++ has. The "=" just binds the name A to some object - without the object knowing it. What's wrong with class A: def clear(): pass ... A.clear() ? Alternatively, you could try and abuse one of the seldom used in-place operator like __ior__: A |= 0 But I wouldn't recommend that. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Can you set a class instance's attributes to zero by setting the instance to zero?
Hello If I have the Vector class below, is there a means by which I can have the following behaviour >>>A = Vector(1, 2) >>>print A (1, 2) >>>A = 0 >>>print A (0, 0) If there is such a means, will it still work with the __slots__ attribution uncommented? Thanks class Vector(object): #__slots__ = ('x', 'y') def __init__(self, a=0, b=0 ): self.x = a self.y = b def __repr__(self): return '(%s, %s)' % (self.x, self.y) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python obfuscation
Alex Martelli wrote: > Money is made in many ways, essentially by creating (perceived) buyer > advantage and capturing some part of it -- but market segmentation is > just one of many ways. IF your predictions are ENORMOUSLY better than > those the competition can make, then offering for free "slightly > damaged" predictions, that are still better than the competition's > despite the damage, MIGHT be a way to market your wares -- under a lot > of other assumptions, e.g., that there is actual demand for the best > predictions you can make, the ones you get paid for, so that your free > service doesn't undermine your for-pay one. It just seems unlikely that > all of these preconditions would be satisfied at the same time; better > to limit your "free" predictions along other axes, such as duration or > location, which doesn't require your predictions' accuracy advantage to > be ENORMOUS _and_ gives you a lot of control on "usefulness" of what > you're supplying for free -- damaging the quality by randomization just > seems to be unlikely to be the optimal strategy here, even if you had > determined (or were willing to bet the firm that) marked segmentation is > really the way to go here. Suppose I grant all your theories about optimal marketing strategies. This still doesn't account for the way the market is behaving *now*. It isn't in any way logical or optimal. For example in Holland (where I live) complete governmental departments are dedicated to make life miserable for the unemployed, for asylum seekers, for people that disagree with any official policy. If looking at the recent developments in France I find it hard to believe that such social inequality an injustice develops naturally. To me it looks more like it's caused by organized crime, where *official* legal governmental organizations are either crimimal organizations themselves or are cooperating with such organizations. You seem to tackle the problem of python obfuscation by first proving that it isn't feasible and then giving some kind of solution that will work and give the desired result: webservices. However when I look at obfuscation techniques I see a desire to profit from giving some person the idea that he or she is superior to someone else because he has a better product. In order to avoid copying we now need obfuscation. The difficulty to copy the thing (whether it is a swiss watch, a sportscar, designer clothes, the latest computer game, an ipod, a computer program) is part of the advertising game and is the basis for associating it with a certain status. If you look for a few minutes at a TV screen and notice what the commercials are trying to tell you, you will see that it's almost always that you will be better, stronger, more popular or beautyfull etc. if only you use product X. You are perfectly right if you would say that it is an illogical strategy to make people feel better relative to other people in order to get them to do something you want. Commercial entities could in principle be free of such things but we live in a world that is dominated by this worldview and if one tries to sell something one has to take that into account. So how to get the same kind of market segmentation (as you call it) when you deploy your program as a webservice and where essentially the cost for you (moving a few electrons to produce a solution to a problem) is exactly the same whether you give the user a good or a bad result. If you give optimal results to everyone, users will go to other sites just because these sites give them opportunity to feel better than other people, not because this is objectively better, but just because that is how they think the world "works". > I hope this analogy clarifies why, while I don't think deliberate damage > of result quality can be entirely ruled out, I think it's extremely > unlikely to make any sense compared to ofher market segmentation > tactics, even if you DO grant that it's worth segmenting (free samples > are an extremely ancient and traditional tactic in all kind of food > selling situations, after all, and when well-designed and promoting a > product whose taste is indeed worth a premium price, they have been > repeatedly shown to be potentially quite effective -- so, I'm hoping > there will be no debate that the segmentation might perfectly well be > appropriate for this "analogy" case, whether it is or isn't in the > originally discussed case of selling predictions-via-webservices). I agree it doesn't make sense. Like uncle Harry who thinks he can lay golden eggs. We could cure him but we need the egss :-) Alternatively, lets just forget about obfuscation and try to get people to freely share by promoting open source (and open webservices). Anton -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused about namespaces
Thanks a lot for all the answers. After rereading everything said here today it's become more clear to me what you guys are telling me and I'll actively try to forget about "from ... import *" ;). -- http://mail.python.org/mailman/listinfo/python-list
Re: Web-based client code execution
Steve wrote: > AJAX works because browsers can execute javascript. I don't know of a > browser that can execute python. Basically your stuck with java or > javascript because everything else really isn't cross platform Don't jump to conclusions... http://dwahler.ky/python/ If you really, really want Python in a browser, it's certainly possible. :) -- David -- http://mail.python.org/mailman/listinfo/python-list