pprinting objects
Hi, Is there a way to get a dump of the insides of an object? I thought pprint would do it. If I had a class like this: class t: def __init__(self): self.x=1 self.y=2 self.obj = SomeOtherObj() Then it could display it as: t, x,1, y,2, obj, Or something like that -- a complete output of the object really, with id()'s and so forth. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
On Dec 8, 9:34 pm, "Mario M. Mueller" <[EMAIL PROTECTED]> wrote: > Hi, > > I have a binary file containing 3 byte float values (big endian). How can I > read them into python? The struct module does not work, since it expects 4 > byte floats. > > Any hints? > > Mario What does a three-byte float look like? To write an unpack routine from scratch, one would need to know position & size of the mantissa and exponent, position of sign bit, how infinities, NaN, -0 etc are represented (if at all) ... -- http://mail.python.org/mailman/listinfo/python-list
XSLT 2 Processor
Hi, I wanted to know if there is a XSLT 2 processor for python?? Thanks, Anand Nalya -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
[EMAIL PROTECTED] wrote: > Hi, > > With properties, attributes and methods seem very similar. I was > wondering what techniques people use to give clues to end users as to > which 'things' are methods and which are attributes. With ipython, I > use tab completion all the time, but I can rarely tell from the names > alone whether it is an attribute or method. > > Tips? Ideas? Best practices? > > Here is one idea: Ipython should color-code the tab completion based > on attributes and methods. Sure. Import types and test, then color code based on the test result. For example: py> import types py> def doit(stuff): ... print stuff ... py> class Thing(object): ... def amethod(self): ... print 42 ... py> t = Thing() py> type(t.amethod) is types.MethodType True py> type(t.doit) is types.FunctionType True py> type(Thing.amethod) is types.UnboundMethodType True py> t.value = 4 py> type(t.value) not in (types.FunctionType, types.UnboundMethodType, types.MethodType) True James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
"Donn Ingle" schrieb > Is there a way to get a dump of the insides of an object? > I thought pprint would do it. > print would actually like to do it if you told it how to do it. print actually does it, but takes a default implementation if you do not override __repr__ or __str__. > If I had a class like this: > > class t: > def __init__(self): > self.x=1 > self.y=2 > self.obj = SomeOtherObj() > > Then it could display it as: > > t, > x,1, > y,2, > obj, > > Or something like that -- a complete output of the object really, > with id()'s and so forth. > Define a __repr__ or __str__ method for the class: class t: def __init__(self): self.x=1 self.y=2 self.obj = SomeOtherObj() def __repr__(self): s = " %s\n x,%d\n y,%d\n obj," \ % (self.__class__, self.x, self.y, self.obj.__class__) return s a_t = t() print "a t obj: %s" % (a_t) a t obj: __main__.t x,1 y,2 obj, HTH Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
John Machin wrote: > On Dec 8, 9:34 pm, "Mario M. Mueller" <[EMAIL PROTECTED]> wrote: >> Hi, >> >> I have a binary file containing 3 byte float values (big endian). How can >> I read them into python? The struct module does not work, since it >> expects 4 byte floats. >> >> Any hints? >> >> Mario > > What does a three-byte float look like? To write an unpack routine > from scratch, one would need to know position & size of the mantissa > and exponent, position of sign bit, how infinities, NaN, -0 etc are > represented (if at all) ... Unfortunatly I don't know anything in detail about these floats (yet). Any documentation about it seems to be lost... :( Maybe I can can get some working C code in the next days. Mario -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
Bjoern Schliessmann wrote: [...] > BTW, who in his mind designs three byte floats? Memory isn't that > expensive anymore. Even C bool is four bytes long. It's output of a digitizer (but not that old). I was also wondering about the reason for this limitation (maybe the design is ~20 years old). Mario -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
On Dec 8, 9:16 pm, Donn Ingle <[EMAIL PROTECTED]> wrote: > Hi, > Is there a way to get a dump of the insides of an object? I thought pprint > would do it. If I had a class like this: > > class t: > def __init__(self): > self.x=1 > self.y=2 > self.obj = SomeOtherObj() > > Then it could display it as: > > t, > x,1, > y,2, > obj, > > Or something like that -- a complete output of the object really, with > id()'s and so forth. > > \d AFAIK you have to roll your own. Here is a very rudimentary example: C:\junk>type dumpobj.py class MixDump(object): def dump(self): print "Dump of", self.__class__.__name__, 'instance' for attr, value in sorted(self.__dict__.iteritems()): print attr, repr(value) class T(MixDump): def __init__(self): self.x=1 self.y=2 self.obj = list() def amethod(self): pass class U(MixDump): def __init__(self): self.f = 'foo' self.yorick = 'y' self.bananas = None t = T() t.dump() u = U() u.dump() C:\junk>dumpobj.py Dump of T instance obj [] x 1 y 2 Dump of U instance bananas None f 'foo' yorick 'y' HTH, John -- http://mail.python.org/mailman/listinfo/python-list
how to convert 3 byte to float
Hi, I have a binary file containing 3 byte float values (big endian). How can I read them into python? The struct module does not work, since it expects 4 byte floats. Any hints? Mario -- http://mail.python.org/mailman/listinfo/python-list
XSLT 2 Processor
Hi, I wanted to know if there is a XSLT 2 processor for python?? Thanks, Anand Nalya -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
Donn Ingle wrote: > Hi, > Here's some code, it's broken: > > > class Key( object ): > def __init__(self): > self.props = KeyProps() > def __getattr__(self, v): > return getattr( self.props,v ) > def __setattr__(self,var,val): > object.__setattr__(self.props,var,val) > > class KeyProps(object): > def __init__(self): > self.x="NOT SET YET" > k1=Key() > > It does not run because of the recursion that happens, but I don't know how > to lay this out. > > I am trying to set the x value within props within Key: > k1.x="DAMN" > print k1.x > > It seems to work, but it's really making a new 'x' in k1. > print k1.props.x > Shows "NOT SET YET", thus proving it failed to set x here. > > I want to change k1.props.x by k1.x="something new" -- can this be done? > > \d > You will want to study the attribute proxy recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/510402 Also, its not obvious how what you seem to be describing is different from: class Key(object): def __init__(self): self.x = 'NOT SET YET' self.props = self e.g. py> class Key(object): ... def __init__(self): ... self.x = 'NOT SET YET' ... self.props = self ... py> k = Key() py> k.props.x 'NOT SET YET' py> k.x 'NOT SET YET' py> k.x = "DAMN" py> k.x 'DAMN' py> k.props.x 'DAMN' So you might want to describe your use-case. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com -- http://mail.python.org/mailman/listinfo/python-list
setdefaultencoding error
>>> import sys >>> sys.setdefaultencoding(utf8) Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'setdefaultencoding' but i find the attribute"setdefaultencoding" in python manuals where is the error? -- http://mail.python.org/mailman/listinfo/python-list
Re: Some python syntax that I'm not getting
Think of it as using a name instead of a position for your "%s".
In addition to what others already said, I thought I'd add an example
of where this is useful.
One place where you don't just want to have a position is when doing
internatiolization.
When translating for example:
"I'm going by %(transport)s to %(place)s" % ( {'transport' : 'car',
'place' : 'mexico'} )
In another language, the 'place' and 'transport' might not be in the
same order in the sentence, so pretty much the only way to get it
right is to use named parameters instead of positions.
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
Mario M. Mueller wrote: > I have a binary file containing 3 byte float values (big endian). > How can I read them into python? The struct module does not work, > since it expects 4 byte floats. Since the module crystalball is still in development, you'll have to analyze your three byte float format and convert it either to a IEEE 754 "single" float and use struct, or convert manually using bitwise operators. BTW, who in his mind designs three byte floats? Memory isn't that expensive anymore. Even C bool is four bytes long. Regards, Björn -- BOFH excuse #87: Password is too complex to decrypt -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
> AFAIK you have to roll your own. Here is a very rudimentary example: Very cool, thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: weird embedding problem
On Dec 7, 11:44 pm, DavidM <[EMAIL PROTECTED]> wrote: > On Fri, 07 Dec 2007 00:53:15 -0800, Graham Dumpleton wrote: > > Are you actually linking your C program against the Python library? > > Yes. Refer OP: > > >> I'm embedding python in a C prog which is built as a linux shared lib. > >> The prog is linked against libpython, and on startup, it calls > >> Py_Initialize(). What was the compiler link line you used for your program/shared library then? Have you confirmed using 'ldd' command that your program/shared library do actually link against libpython? Your original description is confusing. You say your program is built as a shared library. Can you properly explain the full process you are using to build your code and if you are producing a shared library for your program how then is that shared library being used with an actual executable? Be specific about where the program main() is located? Some platforms don't necessarily find symbols from shared library 'A' linked against a program executable if the main() is actually obtained from a shared library 'B" linked to the same program and where the symbols required from 'A' are only used in 'B'. What is required is to link library 'A' against library 'B'. Graham -- http://mail.python.org/mailman/listinfo/python-list
setattr getattr confusion
Hi, Here's some code, it's broken: class Key( object ): def __init__(self): self.props = KeyProps() def __getattr__(self, v): return getattr( self.props,v ) def __setattr__(self,var,val): object.__setattr__(self.props,var,val) class KeyProps(object): def __init__(self): self.x="NOT SET YET" k1=Key() It does not run because of the recursion that happens, but I don't know how to lay this out. I am trying to set the x value within props within Key: k1.x="DAMN" print k1.x It seems to work, but it's really making a new 'x' in k1. print k1.props.x Shows "NOT SET YET", thus proving it failed to set x here. I want to change k1.props.x by k1.x="something new" -- can this be done? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: download complete webpage with python
En Fri, 07 Dec 2007 17:58:43 -0300, yi zhang <[EMAIL PROTECTED]> escribió: > The urllib.urlretrieve() can only download the text part of a webpage, > not the image associated. How can I download the whole, complete webpage > with python? Thanks! The images are separate from the html document. You have to parse the html text, find the tags, and retrieve them. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculate an age
On Fri, 07 Dec 2007 23:37:23 -0800, Pierre Quentel wrote: > On Dec 7, 7:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > >> How many days in a year? 365.25 (J2000 epoch), 365.2422 [as I >> recall](B1900 epoch), 365.0 (non-leap year), 366 (leap year)? Gregorian >> or Julian calendar -- and depending upon one's country, the Gregorian >> reform may take place at different years. >> >> Simple months of (year/12) days, or calendrical mishmash (30 days >> hath September, April, June, and November...) again with leap year >> exceptions? >> > > I don't see where the ambiguity is. Isn't it obvious what we mean by > "I am X years, Y months and Z days" ? That's obvious but given either the present date or the birth date along with that information it's not so clear what the other date may be. Unless you give the info about the used calender systems and the points in time (according to which calender system!?) when to use which system. If you are just asking those questions for people living now (and are not called Connor McLeod ;-) and the gregorian calender it's easy but providing functions in the standard library for arbitrary date calculation involving years is not so easy. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote: > With properties, attributes and methods seem very similar. I was > wondering what techniques people use to give clues to end users as to > which 'things' are methods and which are attributes. Methods are attributes. So the decision is easy -- everything on an object is an attribute. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: setdefaultencoding error
On Dec 8, 8:36 pm, smalltalk <[EMAIL PROTECTED]> wrote: > >>> import sys > >>> sys.setdefaultencoding(utf8) > > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'setdefaultencoding' > > but i find the attribute"setdefaultencoding" in python manuals > > where is the error? You need to do more than find an attribute in a manual, you need to read what the manual says about that attribute. -- http://mail.python.org/mailman/listinfo/python-list
how to convert 3 byte to float
Hi, I have a binary file containing 3 byte float values. How can I read them into python? The struct module does not work, since it expects 4 byte floats. Any hints? Mario -- http://mail.python.org/mailman/listinfo/python-list
Re: How does python build its AST
On Dec 7, 9:23 am, MonkeeSage <[EMAIL PROTECTED]> wrote: > A quick question about how python parses a file into compiled > bytecode. Does it parse the whole file into AST first and then compile > the AST, or does it build and compile the AST on the fly as it reads > expressions? (If the former case, why can't functions be called before > their definitions?) Python creates certain objects at compile time but doesn't bind them to names in the modulespace until run time. Python could--and many other languages do--automatically bind these objects to names upon import. Python doesn't do it because it sees a module as "code to be executed" rather than a "list of global object definitions". Something like this would be awkward if Python bound the names at import time: if X: def a(): do_this() else: def a(): do_that() Which one gets bound to a? To do something similar in C would require preprocessor macros (ick). Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
On 8 dec 2007, at 12.52, Mario M. Mueller wrote: > Bjoern Schliessmann wrote: > > [...] >> BTW, who in his mind designs three byte floats? Memory isn't that >> expensive anymore. Even C bool is four bytes long. > > It's output of a digitizer (but not that old). I was also wondering > about > the reason for this limitation (maybe the design is ~20 years old). > > Mario > -- One thing to consider: It is possible that one of the bytes contributes bits to BOTH the mantissa and the exponent ; Do you know the relative accurazy of the digitizer? - This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How does python build its AST
On Dec 8, 3:32 am, Carl Banks <[EMAIL PROTECTED]> wrote: > On Dec 7, 9:23 am, MonkeeSage <[EMAIL PROTECTED]> wrote: > > > A quick question about how python parses a file into compiled > > bytecode. Does it parse the whole file into AST first and then compile > > the AST, or does it build and compile the AST on the fly as it reads > > expressions? (If the former case, why can't functions be called before > > their definitions?) > > Python creates certain objects at compile time but doesn't bind them > to names in the modulespace until run time. > > Python could--and many other languages do--automatically bind these > objects to names upon import. Python doesn't do it because it sees a > module as "code to be executed" rather than a "list of global object > definitions". > > Something like this would be awkward if Python bound the names at > import time: > > if X: > def a(): do_this() > else: > def a(): do_that() > > Which one gets bound to a? > > To do something similar in C would require preprocessor macros (ick). > > Carl Banks Gotcha. Thanks again everyone for your answers. Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote: > > With properties, attributes and methods seem very similar. I was > > wondering what techniques people use to give clues to end users as to > > which 'things' are methods and which are attributes. > > Methods are attributes. So the decision is easy -- everything on an > object is an attribute. ;-) > > Ciao, > Marc 'BlackJack' Rintsch I think he means callable attributes (methods) and non-callable attributes (variables). Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 6:50 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Sat, 08 Dec 2007 00:34:06 -0800, MonkeeSage wrote: > > I think he means callable attributes (methods) and non-callable > > attributes (variables). > > But not every callable attribute is a method. > > Ciao, > Marc 'BlackJack' Rintsch I swear, you dynamic programmers and your metaprogramming tomfoolery! :P Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
On Dec 8, 6:06 am, Donn Ingle <[EMAIL PROTECTED]> wrote: > Hi, > Here's some code, it's broken: > > class Key( object ): > def __init__(self): > self.props = KeyProps() > def __getattr__(self, v): > return getattr( self.props,v ) > def __setattr__(self,var,val): > object.__setattr__(self.props,var,val) If you define __setattr__ you can't initialize attributes the ordinary way. Instead, use self.__dict__. (Once it's initialized, you can refer to it in the ordinary way.) So do it like this: class Key(object): def __init__self): self.__dict__['props'] = KeyProps() def __getattr__(self,var): return getattr(self.props,var) def __setattr__(self,var,val): setattr(self.props,var,val) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Sat, 08 Dec 2007 00:34:06 -0800, MonkeeSage wrote: > I think he means callable attributes (methods) and non-callable > attributes (variables). But not every callable attribute is a method. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
> So you might want to describe your use-case. Um.. I wanted an object with Key to hold other data. I wanted a way to set that *other* data within Key without having to specify the "object in-between" everytime. k1.x = "ni!" should perform: k1.props.x = "ni!" and print k1.x should perform: print k1.props.x I'll go look at your link. Thanks. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculate an age
What is so obvious about dealing with months that vary in length and the leap-year issue? Nothing. If you were born on a day that does not exist every year (Feb 29th), how old are you on Feb 28th? or Mar 1 of non-leap years? If you were born on Feb 29th, then you would be one month old on March 29th, but would you be one year, one month and one day old on March 29th of the next year? or would you merely be one year and one month old? I believe this is exactly why datetime merely states deltas in days, not months or years. Marc 'BlackJack' Rintsch wrote: > On Fri, 07 Dec 2007 23:37:23 -0800, Pierre Quentel wrote: > > >> On Dec 7, 7:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: >> >> >>> How many days in a year? 365.25 (J2000 epoch), 365.2422 [as I >>> recall](B1900 epoch), 365.0 (non-leap year), 366 (leap year)? Gregorian >>> or Julian calendar -- and depending upon one's country, the Gregorian >>> reform may take place at different years. >>> >>> Simple months of (year/12) days, or calendrical mishmash (30 days >>> hath September, April, June, and November...) again with leap year >>> exceptions? >>> >>> >> I don't see where the ambiguity is. Isn't it obvious what we mean by >> "I am X years, Y months and Z days" ? >> > > That's obvious but given either the present date or the birth date along > with that information it's not so clear what the other date may be. > Unless you give the info about the used calender systems and the points in > time (according to which calender system!?) when to use which system. > > If you are just asking those questions for people living now (and are > not called Connor McLeod ;-) and the gregorian calender it's easy but > providing functions in the standard library for arbitrary date calculation > involving years is not so easy. > > Ciao, > Marc 'BlackJack' Rintsch > -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
On 8 dec 2007, at 13.57, Bjoern Schliessmann wrote: > Mario M. Mueller wrote: > >> It's output of a digitizer (but not that old). I was also >> wondering about the reason for this limitation (maybe the design >> is ~20 years old). > > Uh, that's weird. Since Python cannot guess its format, you'll have > to try it out. Why don't you try to let the device output > well-known values and write a python script to display them > bitwise? With some luck you can reverse engineer the format. > > Regards, > > > Björn > > -- > BOFH excuse #12: > > dry joints on cable plug > It will probably require a high quality voltage standard to do this. There are special high precission voltage standard chips to do this. For producing other voltages than the standard voltage of the chip, use pulsewith modulation with a low pass filter. - This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
Mario M. Mueller wrote: > It's output of a digitizer (but not that old). I was also > wondering about the reason for this limitation (maybe the design > is ~20 years old). Uh, that's weird. Since Python cannot guess its format, you'll have to try it out. Why don't you try to let the device output well-known values and write a python script to display them bitwise? With some luck you can reverse engineer the format. Regards, Björn -- BOFH excuse #12: dry joints on cable plug -- http://mail.python.org/mailman/listinfo/python-list
Re: pprinting objects
> Define a __repr__ or __str__ method for the class Yes, then I could include the code John Machin suggested in there: for attr, value in sorted(self.__dict__.iteritems()): blah That will do nicely. Thanks all. \d -- http://mail.python.org/mailman/listinfo/python-list
Basic animation in Python - how to
I need to draw a shaded rectangle and have flashing (gif animated) points on it so not to refresh all objects a rectangle, but points, changing their colors, attributes. Please refer me to some basic Python code for animation like that . Darius -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent of perl's Pod::Usage?
On 2007-12-08, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On Fri, 7 Dec 2007 20:12:21 +, Adam Funk <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > >> I'm using to using Pod::Usage in my Perl programs (a snipped example >> is shown below, if you're interested) to generate a little man page >> when they are called with the -h option. >> >> Is there an equivalent in Python? >> > I'd suggest you look in the Python references for docstring and/or > __doc__ I found the example incomprehensible, so I looked it up in perldoc. Anyhow, Python doesn't have it. Combining printing various verboseness of usage messages with setting exit codes with calling the exit function seems a little bizarre. But I believe optparse will handle parsing arguments and printing usage messages, though not, I think, setting verbosity levels and exiting the program. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
Tommy Nordgren wrote: [...] > One thing to consider: It is possible that one of the bytes > contributes bits to BOTH the mantissa and the exponent ; >From todays point of view I cannot exclude this. > Do you know the relative > accurazy of the digitizer? Not yet. It's seismic data, that implies: - values will be positive and negative - value range should cover several orders of magnitude Mario -- http://mail.python.org/mailman/listinfo/python-list
Re: Running unmodified CGI scripts persistently under mod_wsgi.
Jeffrey Froman wrote: > > I'd still be interested in a mod_wsgi wrapper for 3rd-party CGI scripts. I doubt that this is possible, not because of the interface. But conventional CGI scripts are implemented with the assumption of being stateless. You would have to completely reinitialize them for each hit. Without knowledge about the internal CGI script processing this would mean reinitializing the whole Python run-time environment. So IMHO there's no real gain. Just my 2 c. Ciao, Michael. -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Martin v. Löwis wrote: > At first, I also thought that Robin suggested that there is a problem > with Python. Upon re-reading, I now believe he rather sees the bug > in the reportlabs code, and is asking for an approach to solve it there. I saw your posting after I sent mine. The gmane web interface is slow and sluggish today. The macro WORDS_BIGENDIAN isn't mentioned in the docs. The docs sure need some extra information how to create universal binaries and how to write endian safe C code. I'm going to create a GHOP task. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
Colin J. Williams wrote: > Steve Howell wrote:> > Thanks for the interesting comparison. > > [snip] > >> 3) I actually like being able to omit parentheses in >> method definitions and method calls. In Ruby you can >> express "add(3,5,7)" as both "add(3,5,7)" and "add 3, >> 5, 7." The latter syntax is obviously more error >> prone, but I don't think I've ever actually gotten bit >> by it, and the code appears more clean to me. >> >> > [snip] > > I'm not sure that I like add 3, 5, 7 > > but it would be nice to be able to drop > the parentheses > when no argument is required. > > Thus: close; > could replace close(); > > The fact that you can do this in Ruby and not in Python is why passing callables in Ruby is awkward and it's extremely natural in Python. In Ruby, of course, you don't pass callables around as much, using blocks instead, so it works out there. But it's an example of some of the fundamental syntax differences between the languages. -- http://mail.python.org/mailman/listinfo/python-list
callback confusion
Hi, I have two modules, the second is imported by the first. Let's call them one.py and two.py (two being my API) In the first I register a function into the second. [in one.py] def boo(): ... ... two.register( boo ) two.startLoop() In two.py it starts a loop (GTK timeout), so processing remains there. At some point it's time to call the callback. [within the loop in two.py] f = getFunc() f() That works, it calls boo( ) in one.py -- all fine. The thing I can't figure out is that it's calling it from the namespace p.o.v of two.py -- For example: [in one.py] kills=0 def boo(): print kills It will abort with: print kills UnboundLocalError: local variable 'kills' referenced before assignment How can I get the 'self' of a module? If I could tell it to [print moduleself.kills] or something like that I'd be in business again. It would be best to have no funny stuff on the user-end of the API; a simple [print kills] would be best. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Running unmodified CGI scripts persistently under mod_wsgi.
On Dec 8, 8:26 am, Michael Ströder <[EMAIL PROTECTED]> wrote: > But conventional CGI scripts are implemented with the assumption of being > stateless. while it might be that some CGI scripts must be executed in a new python process on each request, common sense and good programming practices would steer most people away from that sort of approach. after all such CGI scripts would not execute properly under mod_python either i. -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
> class Key(object): > def __init__self): > self.__dict__['props'] = KeyProps() Okay - that's weird. Is there another way to spin this? > def __setattr__(self,var,val): > setattr(self.props,var,val) Perhaps by changing this one? \d -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
MonkeeSage wrote: > On Dec 7, 11:08 pm, Steve Howell <[EMAIL PROTECTED]> wrote: >> Python is my favorite programming language. I've used >> it as my primary language for about six years now, >> including four years of using it full-time in my day >> job. Three months ago I decided to take a position >> with a team that does a lot of things very well, but >> they don't use Python. We use Ruby instead. I'd like >> to share my observations about Ruby, because I think >> they say important things about Python, which has been >> my frame of reference. >> >> First of all, I actually enjoy programming in Ruby. >> Although I'm still fairly early on the learning curve, >> I feel like I've achieved basic fluency, and it >> generally stays out of the way. >> >> (A quick disclaimer is that some of the observations I >> make about Ruby may simply reflect my ignorance about >> the language. I'm still learning it.) >> >> The thing that I like least about Ruby is its >> "require" mechanism. Basically, when you do "require" >> in Ruby, it sort of pollutes your namespace. I much >> prefer Python's explicitness. >> >> Some surprising things that I like about Ruby: >> >> 1) It has the Perlish natural language syntax of >> "raise 'foo' if condition." I never missed having >> that syntax in Python, but now that I have it in Ruby, >> I use it quite often. This could be done in Python if raise became a function, as it has for print. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
Steve Howell wrote:> Thanks for the interesting comparison. [snip] > 3) I actually like being able to omit parentheses in > method definitions and method calls. In Ruby you can > express "add(3,5,7)" as both "add(3,5,7)" and "add 3, > 5, 7." The latter syntax is obviously more error > prone, but I don't think I've ever actually gotten bit > by it, and the code appears more clean to me. > [snip] I'm not sure that I like add 3, 5, 7 but it would be nice to be able to drop the parentheses when no argument is required. Thus: close; could replace close(); Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Python" is not a good name, should rename to "Athon"
Op Mon, 03 Dec 2007 14:20:52 +1300, schreef greg: > If you want a really appropriate name for a programming language, I'd > suggest Babbage. (not for Python, though!) Konrad Zuse wrote the first high-level programming language, so I think his name would be a better candidate... -- JanC -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
On Sat, 08 Dec 2007 14:26:00 +0200, Donn Ingle wrote: >> So you might want to describe your use-case. > Um.. I wanted an object with Key to hold other data. I wanted a way to > set that *other* data within Key without having to specify the "object > in-between" everytime. That's called "automatic delegation". -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Martin v. Löwis wrote: . > > In the specific case, just use the WORDS_BIGENDIAN macro defined in > pyconfig.h; it will be defined if the target is bigendian, and > undefined otherwise. In the case of a universal build, it will be > undefined in the x86 compiler invocation, and defined in the ppc > invocation. > > If you are curious as to how it arranges that, read the source. .. OK I read the source and am slightly puzzled by the code in pyconfig.h.in which reads #ifdef __BIG_ENDIAN__ #define WORDS_BIGENDIAN 1 #else #ifndef __LITTLE_ENDIAN__ #undef WORDS_BIGENDIAN #endif #endif I'm puzzled why WORDS_BIGENDIAN is undefined if both __BIG_ENDIAN__ and __LITTLE_ENDIAN__ are undefined. Surely in that case WORDS_BIGENDIAN should be left alone (if it is already defined). If there's a compiler for a bigendian architecture which doesn't define the gcc macros the we seem to get the wrong result. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic animation in Python - how to
> Please refer me to some basic Python code for animation like that . You are in for a wild ride! Depending on your platform you can use dozens of different tools. Try wxPython, pyCairo, pyGTK and PIL (Python Imaging Library) for the most capable. Basically you are looking at a fairly complex thing - you need to create a "context" and then draw into it with commands (they vary according to your toolkit) and then display the result. Loop that and change the drawing every time and you have animation. wxPython has very easy widgets for doing something like this (you can use an animated gif for example), and it's cross-platform so that a big plus. It's tricky to get into, but well worth it. hth \d -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic animation in Python - how to
On Dec 8, 6:37 am, "http://members.lycos.co.uk/dariusjack/"; <[EMAIL PROTECTED]> wrote: > I need to draw a shaded rectangle and have flashing (gif animated) > points on it > so not to refresh all objects a rectangle, but points, changing their > colors, attributes. > Please refer me to some basic Python code for animation like that . > > Darius What kind of graphical environment and operating system do you want to do this on? Is there a particular UI toolkit you have in mind? Or do you want to output an animated gif or small movie file? -Peter -- http://mail.python.org/mailman/listinfo/python-list
distutils & OS X universal binaries
A user reports problems with one of our extensions when running the intel compiled extension on ppc and vice versa. He is building the extension as a universal binary. Although the intel compiled version runs fine it displays a known bug when run on a ppc. It appears we have an endianness dependency which is statically compiled into the binaries. One proposed fix is to make the endian variable code dynamically change at run time. However, I assume that under the hood the extension is being built in multiple ways so our static definition of endianness in a pre-processor macro needs to be dynamic. Is there a way to get distutils to pass different macros/definitions to the separate compilations. Failing that does anyone know off hand exactly how this problem is supposed to be handled? Ie if there are multiple compiles what distinguishes them. My understanding is that up to 4 different binaries are being squashed together in these universal binaries. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Martin v. Löwis wrote:
>>> A user reports problems with one of our extensions when running the
>>> intel compiled extension on ppc and vice versa. He is building the
>>> extension as a universal binary. Although the intel compiled version
>>> runs fine it displays a known bug when run on a ppc.
>> Have you reported the problem at http://bugs.python.org/? A minimal
>> example could help us to fix the problem.
>
> At first, I also thought that Robin suggested that there is a problem
> with Python. Upon re-reading, I now believe he rather sees the bug
> in the reportlabs code, and is asking for an approach to solve it there.
>.
Yes that's right. Unfortunately this problem doesn't arise in the python
interface, but in libart_lgpl which we depend on. I will look at the
pyconfig.h code to see how our definition should be put into libart's .h
config file. Presumably I can then remove the calculated definition we
have in our setup.py script or at least override it in the right way.
PIL may also have a similar problem as the 1.1.6 setup.py script also
defines WORDS_BIGENDIAN like this
if struct.unpack("h", "\0\1")[0] == 1:
defs.append(("WORDS_BIGENDIAN", None))
probably I borrowed/stole this as we have something very similar in our
setup.py.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
> One proposed fix is to make the endian variable code dynamically change > at run time. I would advise against that. Endianness depdency should be resolved at compile time, with appropriate conditional compilation. Endianness won't change at run-time (and no, not even for a fat binary - the x86 code will always "see" the same endianness, and so will the ppc code). > Is there a way to get distutils to pass different macros/definitions to > the separate compilations. No. distutils only invokes the compiler a single time, not multiple times, for a specific universal object file. The gcc driver then invokes different cc1 backends repeatedly. > Failing that does anyone know off hand exactly how this problem is > supposed to be handled? Ie if there are multiple compiles what > distinguishes them. My understanding is that up to 4 different binaries > are being squashed together in these universal binaries. In the specific case, just use the WORDS_BIGENDIAN macro defined in pyconfig.h; it will be defined if the target is bigendian, and undefined otherwise. In the case of a universal build, it will be undefined in the x86 compiler invocation, and defined in the ppc invocation. If you are curious as to how it arranges that, read the source. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: "Python" is not a good name, should rename to "Athon"
--- Jan Claeys <[EMAIL PROTECTED]> wrote: > Op Mon, 03 Dec 2007 14:20:52 +1300, schreef greg: > > > If you want a really appropriate name for a > programming language, I'd > > suggest Babbage. (not for Python, though!) > > Konrad Zuse wrote the first high-level programming > language, so I think > his name would be a better candidate... > If you renamed the language Z in honor of Mr. Zuse, there would be a certain symmetry given the role of ABC in Python's history: http://www.artima.com/intv/pythonP.html Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Robin Becker wrote: > A user reports problems with one of our extensions when running the > intel compiled extension on ppc and vice versa. He is building the > extension as a universal binary. Although the intel compiled version > runs fine it displays a known bug when run on a ppc. Have you reported the problem at http://bugs.python.org/? A minimal example could help us to fix the problem. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
>> A user reports problems with one of our extensions when running the >> intel compiled extension on ppc and vice versa. He is building the >> extension as a universal binary. Although the intel compiled version >> runs fine it displays a known bug when run on a ppc. > > Have you reported the problem at http://bugs.python.org/? A minimal > example could help us to fix the problem. At first, I also thought that Robin suggested that there is a problem with Python. Upon re-reading, I now believe he rather sees the bug in the reportlabs code, and is asking for an approach to solve it there. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
> #ifdef __BIG_ENDIAN__ > #define WORDS_BIGENDIAN 1 > #else > #ifndef __LITTLE_ENDIAN__ > #undef WORDS_BIGENDIAN > #endif > #endif > > > I'm puzzled why WORDS_BIGENDIAN is undefined if both __BIG_ENDIAN__ and > __LITTLE_ENDIAN__ are undefined. Surely in that case WORDS_BIGENDIAN > should be left alone (if it is already defined). If there's a compiler > for a bigendian architecture which doesn't define the gcc macros the we > seem to get the wrong result. No. pyconfig.h.in gets processed by configure into pyconfig.h; configure replaces all #undef lines with appropriate #define lines if the macro got define in configure. The autoconf macro AC_C_BIGENDIAN performs a configure-time check. So - if the compiler either defines __BIG_ENDIAN__ or __LITTLE_ENDIAN__, that is taken for granted. - otherwise, the configure-time value is used On your normal big-endian compiler (e.g. SPARC), it's the configure-time value that makes WORDS_BIGENDIAN defined. HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
> PIL may also have a similar problem as the 1.1.6 setup.py script also
> defines WORDS_BIGENDIAN like this
>
> if struct.unpack("h", "\0\1")[0] == 1:
> defs.append(("WORDS_BIGENDIAN", None))
>
> probably I borrowed/stole this as we have something very similar in our
> setup.py.
All such checks are broken for fat binaries. Fat binaries essentially
are a form of cross-compilation, and in cross-compilation, thou shalt
not infer target system properties by looking at the host system.
(IOW, autoconf is, in principle, also broken for fat binaries. Indeed,
although the current solution for WORDS_BIGENDIAN is good for ppc
vs. x86, many of the other configure-time detected properties are
incorrect for ppc vs. ppc64 or x86 vs. amd64, such as SIZEOF_LONG)
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list
Re: callback confusion
Donn Ingle a écrit : (snip) > [in one.py] > kills=0 > def boo(): > print kills > > It will abort with: > print kills > UnboundLocalError: local variable 'kills' referenced before assignment As far as I can tell, you have a bit more code in boo, and somewhere in that code (after the print statement), you rebind the name 'kills'. In the absence of a global declaration, this makes this name a local variable. FWIW, this is a FAQ. -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
Donn Ingle a écrit : >>class Key(object): >>def __init__self): >>self.__dict__['props'] = KeyProps() > > Okay - that's weird. No, that's coherent. The default behavior (I mean, when there's no descriptor involved etc) of __setattr__ is to store attributes in instance.__dict__. So as long a you override __setattr__, you have to take care of this by yourself. > Is there another way to spin this? > >>def __setattr__(self,var,val): >>setattr(self.props,var,val) > > Perhaps by changing this one? If you know by advance which names should live in your object and/or which should belong to the KeyProps instance, then you can check and dispatch, ie: class Key(object): # names that must not be delegated to instance.props _mynames = ['props', 'foo', 'bar'] def __setattr__(self, name, value): if name in self._mynames: object.__setattr__(self, name, value) else: setattr(self.props, name, value) -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
I have been waiting for something like this! Thanks! On Dec 8, 2007 6:08 AM, Steve Howell <[EMAIL PROTECTED]> wrote: > Python is my favorite programming language. I've used > it as my primary language for about six years now, > including four years of using it full-time in my day > job. Three months ago I decided to take a position > with a team that does a lot of things very well, but > they don't use Python. We use Ruby instead. I'd like > to share my observations about Ruby, because I think > they say important things about Python, which has been > my frame of reference. > > First of all, I actually enjoy programming in Ruby. > Although I'm still fairly early on the learning curve, > I feel like I've achieved basic fluency, and it > generally stays out of the way. > > (A quick disclaimer is that some of the observations I > make about Ruby may simply reflect my ignorance about > the language. I'm still learning it.) > > The thing that I like least about Ruby is its > "require" mechanism. Basically, when you do "require" > in Ruby, it sort of pollutes your namespace. I much > prefer Python's explicitness. > > Some surprising things that I like about Ruby: > > 1) It has the Perlish natural language syntax of > "raise 'foo' if condition." I never missed having > that syntax in Python, but now that I have it in Ruby, > I use it quite often. > > 2) On a general note, Ruby is enough like Python > that it doesn't bend my brain. > > 3) I actually like being able to omit parentheses in > method definitions and method calls. In Ruby you can > express "add(3,5,7)" as both "add(3,5,7)" and "add 3, > 5, 7." The latter syntax is obviously more error > prone, but I don't think I've ever actually gotten bit > by it, and the code appears more clean to me. > > 4) Ruby forces you to explicitly make attributes for > instance variables. At first I found this clumsy, but > I've gotten used to it, and I actually kind of like it > in certain circumstances. > > What I miss about Python: > > 1) I like the fact that Python's syntax for passing > around methods is very natural. Ruby's syntax is much > more clumsy. > > 2) I miss indentation. I get bitten by kEnd in Ruby > all the time. > > 3) I miss Python's maturity. Just to give a small > example, Python's interpreter gives more readable > syntax error messages. > > Those are the things that jump out for me. I'm > curious to hear what other people have learned about > Python after maybe going away from it for a while. > > > > > > > > Be a better friend, newshound, and > know-it-all with Yahoo! Mobile. Try it now. > http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Martin v. Löwis wrote: ... >> I'm puzzled why WORDS_BIGENDIAN is undefined if both __BIG_ENDIAN__ and >> __LITTLE_ENDIAN__ are undefined. Surely in that case WORDS_BIGENDIAN >> should be left alone (if it is already defined). If there's a compiler >> for a bigendian architecture which doesn't define the gcc macros the we >> seem to get the wrong result. > > No. pyconfig.h.in gets processed by configure into pyconfig.h; configure > replaces all #undef lines with appropriate #define lines if the macro > got define in configure. The autoconf macro AC_C_BIGENDIAN performs > a configure-time check. So > > - if the compiler either defines __BIG_ENDIAN__ or __LITTLE_ENDIAN__, > that is taken for granted. > - otherwise, the configure-time value is used > > On your normal big-endian compiler (e.g. SPARC), it's the > configure-time value that makes WORDS_BIGENDIAN defined. .. OK I need to use something a bit more complex then; I figure this should work #if defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) # ifdef __BIG_ENDIAN__ # ifdef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif # define WORDS_BIGENDIAN 1 # else # ifdef __LITTLE_ENDIAN__ # ifdef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif # endif # endif #endif -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Calculate an age
On Dec 8, 10:04 am, Shane Geiger <[EMAIL PROTECTED]> wrote: > What is so obvious about dealing with months that vary in length and the > leap-year issue? Nothing. If you were born on a day that does not > exist every year (Feb 29th), how old are you on Feb 28th? X years, 11 months, 28 days or Mar 1 of > non-leap years? X' years, 0 month, 1 day If you were born on Feb 29th, then you would be one > month old on March 29th, but would you be one year, one month and one > day old on March 29th of the next year? or would you merely be one year > and one month old? 1 year, 1 month, 0 day ; why would there be one day more ? People born on the 28th would be one year, one month and one day old. If two dates have the same day-in-the-month then the difference is X years, Y months and 0 day I understand that there is no possible conversion from a number of days to a (X,Y,Z) tuple of (years,months,days), and the reverse. But the difference between 2 dates can be unambiguously expressed as (X,Y,Z), and given a start date and an interval (X,Y,Z) you can also find the end date unambiguously, provided the arguments are valid (for instance, 1 month after the 30th of January is not valid) Regards, Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr getattr confusion
Thanks Bruno, I had to keep coding, so I used the long form [Object.subobject.property = blah] anyway. It's long-winded, but unambiguous. \d -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
> OK I need to use something a bit more complex then; I figure this should > work > > #if defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) > #ifdef __BIG_ENDIAN__ > #ifdef WORDS_BIGENDIAN > #undef WORDS_BIGENDIAN > #endif > #define WORDS_BIGENDIAN 1 > #else > #ifdef __LITTLE_ENDIAN__ > #ifdef WORDS_BIGENDIAN > #undef WORDS_BIGENDIAN > #endif > #endif > #endif > #endif I don't understand. If you assume that either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ is defined, anyway - just use that! If neither is defined, you are still lost, unless you use pyconfig.h, in which case, you don't need anything of that. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: callback confusion
> As far as I can tell, you have a bit more code in boo, and somewhere in > that code (after the print statement), you rebind the name 'kills'. Okay, yes: def boo() kills += 1 print kills > the absence of a global declaration, this makes this name a local > variable. I think I see what you mean: >>> kills=0 >>> def boo(): ... kills += 1 ... print kills ... >>> print kills 0 >>> boo() Traceback (most recent call last): File "", line 1, in File "", line 2, in boo UnboundLocalError: local variable 'kills' referenced before assignment >>> kills=77 >>> def boo(): print kills ... >>> boo() 77 I'm amazed that I've spent so much time with Python and something like that totally stumps me!? > FWIW, this is a FAQ. If you have a link, that'll help. \d -- http://mail.python.org/mailman/listinfo/python-list
Newbie edit/compile/run cycle question
I'm a java guy used to the effective edit/run cycle you get with a good IDE. Today I'm writing my first Python, but can't seem to find the way to use Python's inherent edit/run cycle. I edit my source, import it into Python, run it. Fine. Then I edit again, but the next import doesn't notice that a new compile is needed. I'm making a little progress (very little) by exiting/ reentering Python after each edit. Ugh. What don't I know that I should know to just edit/run, preferably at the tap of a function key? -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils & OS X universal binaries
Martin v. Löwis wrote: >> OK I need to use something a bit more complex then; I figure this should >> work >> >> #if defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__) >> #ifdef __BIG_ENDIAN__ >> #ifdef WORDS_BIGENDIAN >> #endif > > I don't understand. If you assume that either __BIG_ENDIAN__ or > __LITTLE_ENDIAN__ is defined, anyway - just use that! > > If neither is defined, you are still lost, unless you use pyconfig.h, > in which case, you don't need anything of that. I prefer to continue using WORDS_BIGENDIAN so fewer changes need to be made to the code. It just makes resynching with the upstream code easier. If neither are defined we get to use the definition from setup.py if it's needed. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
highscores list
I'm writing a game that uses two functions to check and see if a file
called highScoresList.txt exists in the main dir of the game program.
If it doesn, it creates one. That part is working fine. The problem is
arising when it goes to read in the high scores from the file when I
play again.
This is the error msg python is giving me
Traceback (most recent call last):
File "", line 1, in
main()
File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
if(hasHighScore(wins) == True):
File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
scores[i],names[i] = string.split(line,"\t")
ValueError: need more than 1 value to unpack
Here's the relavant code:
def hasHighScore(score):
#opens highScoresList.txt
infile = open("highScoresList.txt",'r')
scores = [0,0,0]
names = ["","",""]
#reads in scores from highScoresList.txt
i=0
for line in infile.readlines():
scores[i],names[i] = string.split(line,"\t")
names[i]=string.rstrip(names[i])
i += 1
infile.close()
#compares player's score with those in highScoresList.txt
i=0
for i in range(0,len(scores)):
if(score > int(scores[i])):
return True
else:
return False
def setHighScores(score,name):
#opens highScoresList.txt
infile = open("highScoresList.txt",'r')
scores = [0,0,0]
names = ["","",""]
#reads in scores from highScoresList.txt
i=0
for line in infile.readlines():
scores[i],names[i] = string.split(line,"\t")
scores[i]=int(scores[i])
names[i]=string.rstrip(names[i])
i += 1
infile.close()
#shuffles thru the highScoresList.txt and inserts player's score if
higher then those in file
i=len(scores)
while(score > scores[i-1] and i>0):
i -= 1
scores.insert(i,score)
names.insert(i,name)
scores.pop(len(scores)-1)
names.pop(len(names)-1)
#writes new highScoresList.txt
outfile = open("highScoresList.txt","w")
outfile.write (" High Score Name \n")
outfile.write ("-\n")
i=0
for i in range(0,len(scores)):
outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
outfile.close()
And here's the call to the functions at the end of my game, included in
the error msg.
#adds player's score to high score list if high enough
if(hasHighScore(wins) == True):
setHighScores(wins,getName(wins))
And this is what the text file looks like when it happens.
High Score Name
-
15 SHAWN
0
0
The answer is probably simple, I've just been working on this program so
long that my brain has turned to mush. Any help would be much
appreciated...thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: eof
On Nov 24, 12:03 am, MonkeeSage <[EMAIL PROTECTED]> wrote:
>
> class open(file):
> def __init__(self, name):
> self.size = os.stat(name).st_size
> file.__init__(self, name)
> def eof(self):
> return self.tell() == self.size
>
> f = open('tmp.py')
> print f.eof() # False
> f.read()
> print f.eof() # True
This is a bad idea because self.size is not guaranteed to be accurate.
For files in /proc, /sys, and for fifo's, unix domain sockets, etc,
you will get incorrect results.
Always write your algorithm to simply read until there is no more
data. Once that happens, you are at EOF.
EOF is a property of a file only after reading didn't return any data.
If you use EOF in the middle of reading a file, it will never be
accurate (or it will be slow).
-JJ
--
http://mail.python.org/mailman/listinfo/python-list
Re: eof
On Nov 22, 10:37 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > > def read(self, size=None): > if size is None: > val = file.read(self) > self.eof = True > else: > val = file.read(self, size) > if len(val) < size: > self.eof = True > return val Anyone using this routine must be careful not to fall in to this trap. !f.eof implies f.read() will return data For example, with a 5-byte file: f = MyFile(5byte.bin) data = f.read(5) f.eof # ==> False data = f.read(5) # ==> Empty String f.eof # ==> True In other words, don't rely on "f.eof" telling you that there is or is not more data... on Unix systems, no matter what, you ALWAYS have to read past EOF to detect it. Languages (like C with FILE*, or Ruby, or anything else) that detects EOF either does it incorrectly, or (what usually happens) reads 1 byte to see if they get an empty string back from the OS. Think about this: If you have to read 1 byte every time you want to check for EOF, what happens if you are reading from a network stream? That 1-byte read may take a while, waiting for data to be sent over the wire. What a performance hit. -JJ -- http://mail.python.org/mailman/listinfo/python-list
Nice Python Cartoon!
http://xkcd.com/353/ -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com http://www.goldwatches.com -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
MonkeeSage a écrit :
> On Dec 7, 11:08 pm, Steve Howell <[EMAIL PROTECTED]> wrote:
>
(snip)
>> 4) Ruby forces you to explicitly make attributes for
>> instance variables. At first I found this clumsy, but
>> I've gotten used to it, and I actually kind of like it
>> in certain circumstances.
> 4.) Yeah, it's hard when learning ruby, especially if coming from
> languages that distinguish between methods and attributes,
which is not the case in Python
> to get used
> to thinking of "a.a" and "a.a=" as method calls and defining accessors
> for those methods (or using one of the attr_* keywords) in the class
> body.
Python has an equivalent support for computed attributes, using property
or a custom descriptors. While it's a bit lower-level than Ruby, it's
still quite easy to use and IMHO a bit more powerful.
> The equivalent python idiom is something like:
>
> class A:
> __a = "foo"
> def __init__(self):
> self.a = A.__a
WTF ???
> Which roughly translates to this in ruby:
>
> class A
> attr_accessor :a
> def initialize
> @a = "foo"
> end
> end
The Python translation of the above Ruby snippet is actually way more
simple:
class A(object):
def __init__(self):
self.a = "foo"
> Python:
>
> 1.) I also found python's style of method referencing to be a lot more
> intuitive than using something like ruby's "m = method('foo');
> m.call('bar')" to get a reference to foo() and call it. It's alot
> cleaner to say "m = foo; m('bar')", imo. But this goes back to the
> omitting parens thing, which makes it impossible to do it that way in
> ruby.
Yeps. This is where the real and fundamental difference between Ruby and
Python becomes evident. Both have support for transparent computed
attributes, but the way it's implemented is totally different - in Ruby,
by not having a call operator at all (I mean, the parens), in Python by
having both an explicit call operator and an explicit protocol for
computed attributes (the descriptor protocol). Not to say one is better
than the other, but that while both languages have similar features
(and, at first look, similar syntaxes), they really have totally
different object models.
> Though, ruby does allow some interesting things by having it
> that way, e.g., letting you substitute a Proc object (e.g., a block or
> lambda) for a method reference transparently.
Care to give an example ? I don't have enough working experience with
Ruby to be sure I understand what you mean here.
> 2.) I also find layout to be a nice feature. And since I've recently
> been using Haskell, it has only re-inforced that opinion. But when I
> first started using python, I got bitten by IndentationError quite
> often. And I kept wanting to type some closing symbol, heh. ;)
The nice thing with Python is that it lets you use the closing symbol
you want, as long as you prefix it with a '#' !-)
--
http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
Colin J. Williams a écrit : > Steve Howell wrote:> > Thanks for the interesting comparison. > > [snip] > >> 3) I actually like being able to omit parentheses in >> method definitions and method calls. In Ruby you can >> express "add(3,5,7)" as both "add(3,5,7)" and "add 3, >> 5, 7." The latter syntax is obviously more error >> prone, but I don't think I've ever actually gotten bit >> by it, and the code appears more clean to me. >> > [snip] > > I'm not sure that I like add 3, 5, 7 > > but it would be nice to be able to drop the parentheses > when no argument is required. > > Thus: close; > could replace close(); This just could not work given Python's object model. The parens actually *are* the call operator. -- http://mail.python.org/mailman/listinfo/python-list
Re: Gnu/Linux dialogue boxes in python
On 7 Des, 17:43, [EMAIL PROTECTED] wrote: > > If you built a GUI with wxPython, it would just use the OS's native > dialogs unless it didn't have one and then it would use a generic > dialog. I would think creating a installer with wxPython and threads > would be fairly trivial. I'm not convinced that bundling a GUI component with a program which may have no GUI elements whatsoever is easier than having a lightweight wrapper around the spawning of a program like kdialog or Xdialog. Of course, there's some work required in supporting dialog program variants, mostly because the developers of these programs do like to extend the interface and add new features and options, but it's arguably less effort than messing around with "wxPython and threads" (without considering the additional dependencies). Of course, not all operating systems bundle a dialog-like program, so perhaps there'd be a need to duplicate this functionality for some platforms, as you suggest. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
[EMAIL PROTECTED] a écrit : > Hi, > > With properties, attributes and methods seem very similar. I was > wondering what techniques people use to give clues to end users as to > which 'things' are methods and which are attributes. Documentation. > With ipython, I > use tab completion all the time, but I can rarely tell from the names > alone whether it is an attribute or method. Actually, in Python, what you call "methods" are technically attributes - usually class attributes, instances of the function class - until they are looked up, at which time the lookup mechanism detect that they implement the descriptor protocol, invoke it, an return the result of this invocation - here a 'method' instance - in place of the original attribute. > Tips? Ideas? Best practices? Reading the doc ?-) Else, you can check whether the attribute is an instance of types.MethodType - but that's not 100% garanteed to work (someone could implement it's own descriptor type acting like a function but not returning a method object). Or if all you need to know is if the attribute is callable, then just ask: print callable(obj.attr) My 2 cents -- http://mail.python.org/mailman/listinfo/python-list
Highscores list
I'm writing a game that uses two functions to check and see if a file
called highScoresList.txt exists in the main dir of the game program.
If it doesn, it creates one. That part is working fine. The problem is
arising when it goes to read in the high scores from the file when I
play again.
>
> This is the error msg python is giving me
>
> Traceback (most recent call last):
> File "", line 1, in
> main()
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
> if(hasHighScore(wins) == True):
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
> scores[i],names[i] = string.split(line,"\t")
> ValueError: need more than 1 value to unpack
>
> Here's the relavant code:
>
> def hasHighScore(score):
>#opens highScoresList.txt
>infile = open("highScoresList.txt",'r')
>scores = [0,0,0]
>names = ["","",""]
>
>#reads in scores from highScoresList.txt
>i=0
>for line in infile.readlines():
>scores[i],names[i] = string.split(line,"\t")
>names[i]=string.rstrip(names[i])
>i += 1
>infile.close()
> #compares player's score with those in highScoresList.txt
>i=0
>for i in range(0,len(scores)):
>if(score > int(scores[i])):
>return True
>else:
>return False
>
>
> def setHighScores(score,name):
>#opens highScoresList.txt
>infile = open("highScoresList.txt",'r')
>scores = [0,0,0]
>names = ["","",""]
>
>#reads in scores from highScoresList.txt
>i=0
>for line in infile.readlines():
>scores[i],names[i] = string.split(line,"\t")
>scores[i]=int(scores[i])
>names[i]=string.rstrip(names[i])
>i += 1
>infile.close()
> #shuffles thru the highScoresList.txt and inserts player's score
> if higher then those in file
>i=len(scores)
>while(score > scores[i-1] and i>0):
>i -= 1
>
>scores.insert(i,score)
>names.insert(i,name)
>scores.pop(len(scores)-1)
>names.pop(len(names)-1)
> #writes new highScoresList.txt
>outfile = open("highScoresList.txt","w")
>
>outfile.write (" High Score Name \n")
>outfile.write ("-\n")
>
>i=0
>for i in range(0,len(scores)):
>outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
>outfile.close()
>
> And here's the call to the functions at the end of my game, included
> in the error msg.
>
>#adds player's score to high score list if high enough
>if(hasHighScore(wins) == True):
>setHighScores(wins,getName(wins))
>
> And this is what the text file looks like when it happens.
>
> High Score Name
15 SHAWN
0
0
> The answer is probably simple, I've just been working on this program
> so long that my brain has turned to mush. Any help would be much
> appreciated...thanks.
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Dec 8, 12:42 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> MonkeeSage a écrit :
>
> > On Dec 7, 11:08 pm, Steve Howell <[EMAIL PROTECTED]> wrote:
>
> (snip)
> >> 4) Ruby forces you to explicitly make attributes for
> >> instance variables. At first I found this clumsy, but
> >> I've gotten used to it, and I actually kind of like it
> >> in certain circumstances.
> > 4.) Yeah, it's hard when learning ruby, especially if coming from
> > languages that distinguish between methods and attributes,
>
> which is not the case in Python
It is, I just wasn't absolutely precise (uh-oh, here comes the
semantics police! -- don't pass GO, don't collect $200, go strait to
jail!). Python *does* distinguish between instance/class vars and
instance/class methods. But in ruby no such distinction exists.
Accessing a "variable" in ruby == calling object.var. I.e., in ruby,
when you say "blah.x" that translates to "blah.send(:x)", whether :x
is a "variable" or a "method," since *everything* is a method. The
call model of ruby is more like smalltalk.
> > to get used
> > to thinking of "a.a" and "a.a=" as method calls and defining accessors
> > for those methods (or using one of the attr_* keywords) in the class
> > body.
>
> Python has an equivalent support for computed attributes, using property
> or a custom descriptors. While it's a bit lower-level than Ruby, it's
> still quite easy to use and IMHO a bit more powerful.
>
> > The equivalent python idiom is something like:
>
> > class A:
> > __a = "foo"
> > def __init__(self):
> > self.a = A.__a
>
> WTF ???
>
> > Which roughly translates to this in ruby:
>
> > class A
> > attr_accessor :a
> > def initialize
> > @a = "foo"
> > end
> > end
>
> The Python translation of the above Ruby snippet is actually way more
> simple:
>
> class A(object):
>def __init__(self):
> self.a = "foo"
>
> > Python:
Not really. In ruby an ivar is accessible within the class *only*, but
not from without (like a mangled python class var), unless you declare
an accessor (or write the accessor methods yourself). So my example is
closer, and is not a WTF, if you know how ruby works.
> > 1.) I also found python's style of method referencing to be a lot more
> > intuitive than using something like ruby's "m = method('foo');
> > m.call('bar')" to get a reference to foo() and call it. It's alot
> > cleaner to say "m = foo; m('bar')", imo. But this goes back to the
> > omitting parens thing, which makes it impossible to do it that way in
> > ruby.
>
> Yeps. This is where the real and fundamental difference between Ruby and
> Python becomes evident. Both have support for transparent computed
> attributes, but the way it's implemented is totally different - in Ruby,
> by not having a call operator at all (I mean, the parens), in Python by
> having both an explicit call operator and an explicit protocol for
> computed attributes (the descriptor protocol). Not to say one is better
> than the other, but that while both languages have similar features
> (and, at first look, similar syntaxes), they really have totally
> different object models.
Yes and no. I'll leave it at that. If you want to know more, do your
homework. :P
> > Though, ruby does allow some interesting things by having it
> > that way, e.g., letting you substitute a Proc object (e.g., a block or
> > lambda) for a method reference transparently.
>
> Care to give an example ? I don't have enough working experience with
> Ruby to be sure I understand what you mean here.
For example, any place expecting a foo (method reference), can be
exchanged with a { "bar" } block or a lambda { "baz" }.
> > 2.) I also find layout to be a nice feature. And since I've recently
> > been using Haskell, it has only re-inforced that opinion. But when I
> > first started using python, I got bitten by IndentationError quite
> > often. And I kept wanting to type some closing symbol, heh. ;)
>
> The nice thing with Python is that it lets you use the closing symbol
> you want, as long as you prefix it with a '#' !-)
LOL. Well, yes, I used to do that, but I got over that irrational
urge. ;)
Regards,
Jordan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
MonkeeSage a écrit : > On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > >>On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote: >> >>>With properties, attributes and methods seem very similar. I was >>>wondering what techniques people use to give clues to end users as to >>>which 'things' are methods and which are attributes. >> >>Methods are attributes. So the decision is easy -- everything on an >>object is an attribute. ;-) >> >>Ciao, >>Marc 'BlackJack' Rintsch > > > I think he means callable attributes (methods) and non-callable > attributes (variables). callable attributes are not necessarily methods, and are still 'variables' anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 12:56 pm, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > MonkeeSage a écrit : > > > > > On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > > >>On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote: > > >>>With properties, attributes and methods seem very similar. I was > >>>wondering what techniques people use to give clues to end users as to > >>>which 'things' are methods and which are attributes. > > >>Methods are attributes. So the decision is easy -- everything on an > >>object is an attribute. ;-) > > >>Ciao, > >>Marc 'BlackJack' Rintsch > > > I think he means callable attributes (methods) and non-callable > > attributes (variables). > > callable attributes are not necessarily methods, and are still > 'variables' anyway. I think it muddies the water to say that a.a() and a.a are the same thing--obviously they are not. In the common case, the first is a method, and the second is a variable. Yes, you can do silly stuff, such that this rule will not hold, but in general it does. Or am I wrong? Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
[EMAIL PROTECTED] a écrit : > I'm a java guy used to the effective edit/run cycle you get with a > good IDE. > > Today I'm writing my first Python, but can't seem to find the way to > use Python's inherent edit/run cycle. > > I edit my source, import it into Python, run it. Fine. Then I edit > again, but the next import doesn't notice that a new compile is > needed. This is not an accurate definition of what happens. The import mechanism keeps already imported modules in cache (for obvious reasons). wrt/ "notice(ing) a new compile is needed", it's not the import mechanism's duty, but the VM one's. > I'm making a little progress (very little) by exiting/ > reentering Python after each edit. Ugh. Java doesn't have an interactive shell, so there's no real parallel here, but anyway: with Java, you have to restart a Java VM each time you run your code. Why do you hope something else with Python ? > What don't I know that I should know to just edit/run, Do what you would do with Java: $ python yourprogram.py Or if you want to inspect the state after execution (something you can't do with Java): $ python -i yourprogram.py > preferably at > the tap of a function key? Use an IDE then. Or a real code editor like emacs - it's python-mode is way more powerful than what I saw in any IDE. -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
--- Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Colin J. Williams a écrit : > > I'm not sure that I like add 3, 5, 7 > > > > but it would be nice to be able to drop the > parentheses > > when no argument is required. > > > > Thus: close; > > could replace close(); > > This just could not work given Python's object > model. The parens > actually *are* the call operator. > I mostly agree with you, but in the specific use case of having just a single token on a line, you could argue that Python could DWIM on calling an object if the object is callable, since otherwise it's just a no-op. I think the argument against doing that is more based on explicit-vs.-implicit principle versus actual constraints of the object model. Another aspect of Ruby is that the final expression evaluated in a method actually gets returned as the result of a method, which has further implications on whether "close" is simply evaluated or called. Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
--- [EMAIL PROTECTED] wrote: > > What don't I know that I should know to just > edit/run, preferably at > the tap of a function key? Most good editors let you do these things: 1) Save a file. 2) Run a script from the shell. 3) Turn steps 1 and 2 into a macro. 4) Allow you to map the function key to a macro. It really depends more on the editor than the programming language. Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: highscores list
On Dec 8, 8:32 pm, Shawn Minisall <[EMAIL PROTECTED]> wrote:
> I'm writing a game that uses two functions to check and see if a file
> called highScoresList.txt exists in the main dir of the game program.
> If it doesn, it creates one. That part is working fine. The problem is
> arising when it goes to read in the high scores from the file when I
> play again.
>
> This is the error msg python is giving me
>
> Traceback (most recent call last):
> File "", line 1, in
>main()
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
>if(hasHighScore(wins) == True):
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
>scores[i],names[i] = string.split(line,"\t")
> ValueError: need more than 1 value to unpack
>
> Here's the relavant code:
>
> def hasHighScore(score):
> #opens highScoresList.txt
> infile = open("highScoresList.txt",'r')
> scores = [0,0,0]
> names = ["","",""]
>
> #reads in scores from highScoresList.txt
> i=0
> for line in infile.readlines():
> scores[i],names[i] = string.split(line,"\t")
> names[i]=string.rstrip(names[i])
> i += 1
> infile.close()
>
> #compares player's score with those in highScoresList.txt
> i=0
> for i in range(0,len(scores)):
> if(score > int(scores[i])):
> return True
> else:
> return False
>
> def setHighScores(score,name):
> #opens highScoresList.txt
> infile = open("highScoresList.txt",'r')
> scores = [0,0,0]
> names = ["","",""]
>
> #reads in scores from highScoresList.txt
> i=0
> for line in infile.readlines():
> scores[i],names[i] = string.split(line,"\t")
> scores[i]=int(scores[i])
> names[i]=string.rstrip(names[i])
> i += 1
> infile.close()
>
> #shuffles thru the highScoresList.txt and inserts player's score if
> higher then those in file
> i=len(scores)
> while(score > scores[i-1] and i>0):
> i -= 1
>
> scores.insert(i,score)
> names.insert(i,name)
> scores.pop(len(scores)-1)
> names.pop(len(names)-1)
>
> #writes new highScoresList.txt
> outfile = open("highScoresList.txt","w")
>
> outfile.write (" High Score Name \n")
> outfile.write ("-\n")
>
> i=0
> for i in range(0,len(scores)):
> outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
> outfile.close()
>
> And here's the call to the functions at the end of my game, included in
> the error msg.
>
> #adds player's score to high score list if high enough
> if(hasHighScore(wins) == True):
> setHighScores(wins,getName(wins))
>
> And this is what the text file looks like when it happens.
>
> High Score Name
> -
> 15 SHAWN
> 0
> 0
>
> The answer is probably simple, I've just been working on this program so
> long that my brain has turned to mush. Any help would be much
> appreciated...thanks.
Your first two lines in your highscores file has no Tab Characters.
When reading the file you could do:
for (i, line) in file_input:
if i < 2:
continue
# do normal file parsing
There are better ways to structure your code though, but that's for
you.
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to convert 3 byte to float
On Dec 8, 6:05 am, "Mario M. Mueller" <[EMAIL PROTECTED]> wrote: > Tommy Nordgren wrote: > > [...] > > > One thing to consider: It is possible that one of the bytes > > contributes bits to BOTH the mantissa and the exponent ; > > From todays point of view I cannot exclude this. > > > Do you know the relative > > accurazy of the digitizer? > > Not yet. It's seismic data, that implies: > > - values will be positive and negative > - value range should cover several orders of magnitude > > Mario What a strange thread. However, I have had experience with a computer that had 3-byte words. The Harris "H" series running VULCAN and VOS (yup) had three byte words. As I recall, the single-precision floats used two words, and ignored two of the bytes. The double precision floats used all six bytes. There was also a 12 byte quad precision (which is sort of impressive). However, ... are you *sure* that the digitizer was floating point? There are a few "floating point" ADCs out there today, but not very many, and I'd be amazed if there was a 20 year old one that was part of a seismic instrument. A 12 bit ADC has over 60 dB of dynamic range (in power) even with int encoding. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Newbie Question
Hi Mark, Thank you so much for the help. I figured it was something pretty simple like that. And I was also puzzled by the concept of the lambda function, so now I know what they do too. I just tried it out, and it works well. Much appreciated, Ciao back at you, Robbie -- http://mail.python.org/mailman/listinfo/python-list
Re: highscores list
> I'm writing a game that uses two functions to check and see if a file
> called highScoresList.txt exists in the main dir of the game program.
> If it doesn, it creates one. That part is working fine. The problem is
> arising when it goes to read in the high scores from the file when I
> play again.
>
> This is the error msg python is giving me
>
> Traceback (most recent call last):
> File "", line 1, in
>main()
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
>if(hasHighScore(wins) == True):
> File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
>scores[i],names[i] = string.split(line,"\t")
> ValueError: need more than 1 value to unpack
>
> for line in infile.readlines():
> scores[i],names[i] = string.split(line,"\t")
The error message is straightforward, you are trying to unpack a 1 value
tuple to 2 values
The reason it's a one value tuple is that your first line is this:
> outfile.write (" High Score Name \n")
Running split('\t') on this will return a tuple of length one (since there
is no tab in that line)
Your code is also really unpythonic, take a look at this rewrite to see
what you could have done better:
def getHighScoreList():
scores = []
try:
highscore_file = list(open("highScoresList.txt"))
for line in highscore_file[2:]:
score, name = line.split('\t\t\t')
scores.append((int(score), name.rstrip()))
except IOError: # no highscore file yet
pass
return scores
def hasHighScore(score):
scores = [s for (s, n) in getHighScoreList()]
if scores:
return score > min(scores)
return True
def setHighScores(newscore, newname):
max_scores = 3
scores = getHighScoreList()
for i, (score, name) in enumerate(scores):
if newscore > score:
scores.insert(i, (newscore, newname))
break
else:
scores.append((newscore, newname))
outfile = open("highScoresList.txt","w")
outfile.write (" High Score Name \n")
outfile.write ("-\n")
for i in range(max_scores):
try:
score, name = scores[i]
except IndexError:
score, name = 0, ''
outfile.write("\t%s\t\t\t%s\n" % (score, name))
outfile.close()
if hasHighScore(wins):
setHighScores(wins, getName(wins))
--
http://mail.python.org/mailman/listinfo/python-list
Re: highscores list
On Dec 8, 10:07 pm, Chris <[EMAIL PROTECTED]> wrote:
> On Dec 8, 8:32 pm, Shawn Minisall <[EMAIL PROTECTED]> wrote:
>
>
>
> > I'm writing a game that uses two functions to check and see if a file
> > called highScoresList.txt exists in the main dir of the game program.
> > If it doesn, it creates one. That part is working fine. The problem is
> > arising when it goes to read in the high scores from the file when I
> > play again.
>
> > This is the error msg python is giving me
>
> > Traceback (most recent call last):
> > File "", line 1, in
> >main()
> > File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 330, in main
> >if(hasHighScore(wins) == True):
> > File "I:\PYTHON\PROJECT #3\PROJECT3.PYW", line 175, in hasHighScore
> >scores[i],names[i] = string.split(line,"\t")
> > ValueError: need more than 1 value to unpack
>
> > Here's the relavant code:
>
> > def hasHighScore(score):
> > #opens highScoresList.txt
> > infile = open("highScoresList.txt",'r')
> > scores = [0,0,0]
> > names = ["","",""]
>
> > #reads in scores from highScoresList.txt
> > i=0
> > for line in infile.readlines():
> > scores[i],names[i] = string.split(line,"\t")
> > names[i]=string.rstrip(names[i])
> > i += 1
> > infile.close()
>
> > #compares player's score with those in highScoresList.txt
> > i=0
> > for i in range(0,len(scores)):
> > if(score > int(scores[i])):
> > return True
> > else:
> > return False
>
> > def setHighScores(score,name):
> > #opens highScoresList.txt
> > infile = open("highScoresList.txt",'r')
> > scores = [0,0,0]
> > names = ["","",""]
>
> > #reads in scores from highScoresList.txt
> > i=0
> > for line in infile.readlines():
> > scores[i],names[i] = string.split(line,"\t")
> > scores[i]=int(scores[i])
> > names[i]=string.rstrip(names[i])
> > i += 1
> > infile.close()
>
> > #shuffles thru the highScoresList.txt and inserts player's score if
> > higher then those in file
> > i=len(scores)
> > while(score > scores[i-1] and i>0):
> > i -= 1
>
> > scores.insert(i,score)
> > names.insert(i,name)
> > scores.pop(len(scores)-1)
> > names.pop(len(names)-1)
>
> > #writes new highScoresList.txt
> > outfile = open("highScoresList.txt","w")
>
> > outfile.write (" High Score Name \n")
> > outfile.write ("-\n")
>
> > i=0
> > for i in range(0,len(scores)):
> > outfile.write("\t" + str(scores[i]) + "\t\t\t" + names[i] + "\n")
> > outfile.close()
>
> > And here's the call to the functions at the end of my game, included in
> > the error msg.
>
> > #adds player's score to high score list if high enough
> > if(hasHighScore(wins) == True):
> > setHighScores(wins,getName(wins))
>
> > And this is what the text file looks like when it happens.
>
> > High Score Name
> > -
> > 15 SHAWN
> > 0
> > 0
>
> > The answer is probably simple, I've just been working on this program so
> > long that my brain has turned to mush. Any help would be much
> > appreciated...thanks.
>
> Your first two lines in your highscores file has no Tab Characters.
> When reading the file you could do:
>
> for (i, line) in file_input:
> if i < 2:
> continue
>
> # do normal file parsing
>
> There are better ways to structure your code though, but that's for
> you.
Apologies, I meant 'in enumerate(file_input)'
--
http://mail.python.org/mailman/listinfo/python-list
Re: Securely distributing python source code as an application?
xkenneth wrote: > Hi All, > > I'll shortly be distributing a number of python applications that > use proprietary. The software is part of a much larger system and it > will need to be distributed securely. How can i achieve this? > > Regards, > Ken We have partnered with developers to use our product WebSafe to provide secure software distribution (among other uses for the service). Take a look at: http://www.websafe.com. We have a special program for developers that allows you to put our API inside your application as well. Larry Bates Vice President/CTO WebSafe, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: download complete webpage with python
Gabriel Genellina wrote: > En Fri, 07 Dec 2007 17:58:43 -0300, yi zhang <[EMAIL PROTECTED]> > escribió: > >> The urllib.urlretrieve() can only download the text part of a webpage, >> not the image associated. How can I download the whole, complete >> webpage with python? Thanks! > > The images are separate from the html document. You have to parse the > html text, find the tags, and retrieve them. > Actually IMHO this is even more difficult than it sounds. Javascript can change the webpage after it loads. Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 4:19 am, [EMAIL PROTECTED] wrote: > With properties, attributes and methods seem very similar. I was > wondering what techniques people use to give clues to end users as to > which 'things' are methods and which are attributes. Methods are verbs, attributes are nouns :) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 7:44 pm, MonkeeSage <[EMAIL PROTECTED]> wrote: > I think it muddies the water to say that a.a() and a.a are the same > thing--obviously they are not. A thing is not what it is; A thing is what it does. This is the Way of the Duck. -- Basho (in his "3 extra syllables" phase) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie edit/compile/run cycle question
--- Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] a écrit : > > I'm a java guy used to the effective edit/run > cycle you get with a > > good IDE. > > > > Today I'm writing my first Python, but can't seem > to find the way to > > use Python's inherent edit/run cycle. > > > > Use an IDE then. Or a real code editor like emacs - > it's python-mode is > way more powerful than what I saw in any IDE. Martin, for Python-specific IDEs, I recommend looking at the following page, although I think you might want to get some feedback from the list as well: http://c2.com/cgi/wiki?PythonIde Having said that, I'm more in Bruno's camp that the choice of an editor usually transcends Python. I prefer to use a powerful editor that's good for working on several languages, as long as it has a good Python mode. There are a zillion powerful editors out there. I've been productive in EditPlus, MultiEdit, SlickEdit, vim, and emacs, just to throw out a few examples. I'm confident you'll find a solution that fits your style, and you are obviously doing a good thing in terms of optimizing edit/run cycle, as it's pretty key to productivity. Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Sat, 08 Dec 2007 11:44:36 -0800, MonkeeSage wrote: > On Dec 8, 12:56 pm, Bruno Desthuilliers >> callable attributes are not necessarily methods, and are still >> 'variables' anyway. > > I think it muddies the water to say that a.a() and a.a are the same > thing--obviously they are not. In the common case, the first is a > method, and the second is a variable. No, the first is a call of `a.a` while the second is just referencing `a.a`. And `a.a` is a "variable" no matter if it refers to a callable or not. Variables are name to object bindings and methods are objects. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: highscores list
On Sat, 08 Dec 2007 13:32:08 -0500, Shawn Minisall wrote: > I'm writing a game that uses two functions to check and see if a file > called highScoresList.txt exists in the main dir of the game program. If > it doesn, it creates one. That part is working fine. The problem is > arising when it goes to read in the high scores from the file when I > play again. Not your original problem, but you should want to look at this instead of creating yet another parser: http://docs.python.org/lib/RawConfigParser-objects.html -Samuel -- http://mail.python.org/mailman/listinfo/python-list
Ruby's Template Engine for Python
Hi,
Following the masses I was drawn to RoR's website today and I saw the
following HTML template in one of the screencasts:
--
<% form_remote_tag :url => { :action => :search },
:update => :results,
:complete => visual_effect(:blind_down, 'image')
:before => %(Element.show('image'))
:after=> %(Element.hide('image')) %>
<%= text_field_tag 'Search' %>
<%= submit_tag 'Search' %>
<% end %>
--
I have to admit that a template engine that integrates with AJAX like
that looks inherently cool. Is there anything like that for Python,
optimally a stand-alone library? Django seems to handle this differently,
from what I can see.
-Samuel
--
http://mail.python.org/mailman/listinfo/python-list
Re: Ruby's Template Engine for Python
--- Samuel <[EMAIL PROTECTED]> wrote: > Hi, > > Following the masses I was drawn to RoR's website > today and I saw the > following HTML template in one of the screencasts: > I know a lot of Rails goodies have been ported to Python, so you might want to google some variations on "form_remote_tag python." This is what I came up with: http://pylonshq.com/pastetags/form_remote_tag I haven't used it personally, but hope this gets you pointed in the right direction. Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Distinguishing attributes and methods
On Dec 8, 2:51 pm, Glenn Hutchings <[EMAIL PROTECTED]> wrote: > On Dec 8, 7:44 pm, MonkeeSage <[EMAIL PROTECTED]> wrote: > > > I think it muddies the water to say that a.a() and a.a are the same > > thing--obviously they are not. > > A thing is not what it is; > A thing is what it does. > This is the Way of the Duck. > > -- Basho (in his "3 extra syllables" phase) Bah. Type-by-behavior never impressed me much. And I still think that a.a is semantically different from a.a() in python. Regards, Jordan -- http://mail.python.org/mailman/listinfo/python-list
Re: Running unmodified CGI scripts persistently under mod_wsgi.
On Dec 9, 12:26 am, Michael Ströder <[EMAIL PROTECTED]> wrote: > Jeffrey Froman wrote: > > > I'd still be interested in a mod_wsgi wrapper for 3rd-party CGI scripts. > > I doubt that this is possible, not because of the interface. But > conventional CGI scripts are implemented with the assumption of being > stateless. You would have to completely reinitialize them for each hit. > Without knowledge about the internal CGI script processing this would > mean reinitializing the whole Python run-time environment. So IMHO > there's no real gain. Just my 2 c. One doesn't necessarily need to reinitialise the whole Python run time environment. The hack that mod_python uses is to remember what Python modules had been loaded before first request. At the end of the request it will delete from sys.modules anything that was added since the beginning of the request. It also replaces os.environ in its entirety at the start of each request as well. Yes, it may not still work for all CGI scripts, eg., C extension modules may be a problem, but may be adequate for many. In fact, for some class of CGI scripts, deleting all those modules from sys.modules may not be necessary, provided you at least cause the main CGI script file to at least be reinterpreted/reimported. What degree of cleaning out the environment could be a configurable parameter of the WSGI/CGI bridge. So, although it can be done, it is the need to use strange hacks like this that means it may just be better to convert CGI script to work as WSGI, as more guarantee of success. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: a Python person's experience with Ruby
On Sat, 08 Dec 2007 11:23:57 -0800, MonkeeSage wrote: >> > The equivalent python idiom is something like: >> >> > class A: >> > __a = "foo" >> > def __init__(self): >> > self.a = A.__a [...] >> > Which roughly translates to this in ruby: >> >> > class A >> > attr_accessor :a >> > def initialize >> > @a = "foo" >> > end >> > end [...] > Not really. In ruby an ivar is accessible within the class *only*, but > not from without (like a mangled python class var), unless you declare > an accessor (or write the accessor methods yourself). So my example is > closer, and is not a WTF, if you know how ruby works. In your python example, the class attribute is mangled, but the instance attribute isn't, whereas your ruby code has no class attribute, and an instance attribute that isn't (directly) accessible outside the class. The equivalent in python would involve a mangled instance attribute, like: class A(object): def __init__(self): self.__a = "foo" def get_a(self): return self.__a def set_a(self, val): self.__a = val a = property(get_a, set_a) -- http://mail.python.org/mailman/listinfo/python-list
