[Tutor] replacement for constants from other languages in Python?
Hey all, I've done the usual googling, checked the Learning Python book and did some list searches, to no avail as of yet. I'm _very_ used to using C style constants (preprocessor #define directives) or C++ const keyword style, for a variety of reasons. I've yet to see anything covering 'how to work around the lack of constants in Python'...can anyone point me in the right direction here? A few examples/reasons for use: The 'need' to define a global constant in an imported module, for example- (I know about sys.version_info, but it doesn't exist in 1.5.2...don't ask ;-) I also know this could be handled via a class, but what is the equivalent of the following snippets? Not so interested in style comments (I am, but not on these/this thread ;-) as much as other ways to do this.. 1. ourversion.py: import sys MINVERSION = 1.5 def checkVersion(): used as an evil hack because 1.5.2 doesn't have sys.version_info # Not sure why, but declaring MINVERSION as repr(foo) in the # first place doesn't work, something about python type handling # I'm sure.. return repr(MINVERSION) = repr(getVersion()) def getVersion(): return sys.version[0:3] if repr(getVersion() 2.0) # boo, we have no builtin bool global True global False True = 1 False = 0 funkyScopeAndConstants.py: import ourversion.py import sys import os import someOtherModule ... ... if someOtherModule.property = True # do something You get the point. The other oddity is without being able to define a 'real' constant, as in #DEFINE MINVERSION 1.5, the scope of MINVERSION (and True/False) even using the global keyword still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generallynot to mention the fact that I really am _not_ thrilled with the use of string literals typed in each time in code (yes, quick and dirty code but still) I see seems to be 'OK' in python for the use of comparisons...opposed to something like if(strncmp(strVal, CONSTANT_STRING_VAL_LIKE_HTTP_ACCEPT_ENCODING_HEADER, strlen(strVal) { do_something(); } or if(floatVal PI) { do_something() } ok, hopefully that's explaining some of why I'd like a 'constant equivalent' as well as a question on global scoping/python namespaces. A last question would also be if the equivalent of __FILE__ and __LINE__ macros exist? Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] The Game of Life
Danny Yoo wrote: There seems to be a fashionable push to introduce patterns early on in computer science education, perhaps because they are easy to put in as test questions. But despite this, I do think that there are some patterns that are worth seeing, even if they are in unrealistic toy situations. I got a kick out of seeing how 'Command' was applied in the Life example, because it shows that we can store active actions as data. I agree that it is helpful to understand design patterns. It's also helpful to understand that applying design patterns doesn't always yield the simplest solution to a problem :-) Why not just build a new world with the values of the next generation in it, and return that from apply_next_generation? That also works, but it doesn't fit the function's description. The example that I adapted originally wanted a function that mutated the previous generation, so that's what I stuck with. OK. I didn't have the spec available. But you can still do it with just one copy, then generate the world back into the original world. For a class problem you might have a firm requirement of a mutating method but in the real world you can often adjust your design to accomodate a more efficient algorithm. If the Life example sucked, don't blame me too badly: I'm just the translator. *grin* soapbox I hope this is not representative of CS education today. My subjective impression is that a lot of Java software suffers from overengineering of this sort. The Python world is refreshingly free of this. I think a lot of the difference may be due to the better tools available in Python, especially first-class functions. But there may also be a cultural bias toward heavier solutions in the Java world. /soapbox Kent Talk to you later! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
Scott W wrote: The 'need' to define a global constant in an imported module, for example- (I know about sys.version_info, but it doesn't exist in 1.5.2...don't ask ;-) I also know this could be handled via a class, but what is the equivalent of the following snippets? Not so interested in style comments (I am, but not on these/this thread ;-) as much as other ways to do this.. 1. ourversion.py: import sys MINVERSION = 1.5 This is the usual Python way. Python's approach generally is 'treat your users like adults', i.e. give them the information needed to make sensible decisions, but don't try to keep them from doing something you think is stupid. Putting the name in upper case gives the information that this is intended to be a constant. def checkVersion(): used as an evil hack because 1.5.2 doesn't have sys.version_info # Not sure why, but declaring MINVERSION as repr(foo) in the # first place doesn't work, something about python type handling # I'm sure.. MINVERSION = repr(1.5) should work just fine. It will give the same result as the more readable MINVERSION = '1.5' I'm not sure why you are using repr() so much. return repr(MINVERSION) = repr(getVersion()) def getVersion(): return sys.version[0:3] if repr(getVersion() 2.0) This will certainly not do what you want for two reasons. - getVersion() returns a string, you are comparing it to a float which will not give a meaningful result. - In Python 2.3 the result of the comparison will be an integer 0 or 1. repr() converts this to a *string* '0' or '1' which will *always* evaluate as True!! # boo, we have no builtin bool global True global False True = 1 False = 0 Rather than testing the version, you can test directly to see whether True and False are defined. If not, you can add them to the __builtin__ module and they will be globally available. Here is one way: import __builtin__ if not __builtin__.hasattr('True'): __builtin__.True = 1 if not __builtin__.hasattr('False'): __builtin__.False = 0 This suggestion is taken from this thread on comp.lang.python: http://tinyurl.com/46me3 Note that adding names to __builtin__ is NOT recommended in general! Don't use this to create your own global constants! It is OK in this case because to duplicate Python 2.3 behaviour you need a true global. The other oddity is without being able to define a 'real' constant, as in #DEFINE MINVERSION 1.5, the scope of MINVERSION (and True/False) even using the global keyword still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generally The usual Python solution is to make a module containing constant definitions and import it where you need them. # Constants.py MINVERSION = 1.5 # Client.py import Constants if (Constants.MINVERSION == 1.5): ... or, if you want to import all the constants directly, # Client2.py from Constants import * if (MINVERSION == 1.5): ... A last question would also be if the equivalent of __FILE__ and __LINE__ macros exist? See this recipe and the one linked to in its discussion: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Kent Thanks, Scott ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
Kent Johnson wrote: Scott W wrote: The 'need' to define a global constant in an imported module, for example- (I know about sys.version_info, but it doesn't exist in 1.5.2...don't ask ;-) I also know this could be handled via a class, but what is the equivalent of the following snippets? Not so interested in style comments (I am, but not on these/this thread ;-) as much as other ways to do this.. 1. ourversion.py: import sys MINVERSION = 1.5 This is the usual Python way. Python's approach generally is 'treat your users like adults', i.e. give them the information needed to make sensible decisions, but don't try to keep them from doing something you think is stupid. Putting the name in upper case gives the information that this is intended to be a constant. Sure, if I can't make it a true constant value, might as well make it 'obvious' ;-) def checkVersion(): used as an evil hack because 1.5.2 doesn't have sys.version_info # Not sure why, but declaring MINVERSION as repr(foo) in the # first place doesn't work, something about python type handling # I'm sure.. MINVERSION = repr(1.5) should work just fine. It will give the same result as the more readable MINVERSION = '1.5' Ok, this would make a bit more sense RE: repr()- in one of the resources I found, it seemed to state that repr(x) was converting x into a numeric representation, ala atoi() and friends. Obviously, this is the opposite of what I'd actually wanted. The sample snippets I put in had a duplicated repr() if not more than one, which wasn't doing what I expected anyways (although at which point I was essentially comparing strings of similar length, getting 'a' result, just not the intended one ;-) I'm not sure why you are using repr() so much. return repr(MINVERSION) = repr(getVersion()) def getVersion(): return sys.version[0:3] if repr(getVersion() 2.0) This will certainly not do what you want for two reasons. - getVersion() returns a string, you are comparing it to a float which will not give a meaningful result. - In Python 2.3 the result of the comparison will be an integer 0 or 1. repr() converts this to a *string* '0' or '1' which will *always* evaluate as True!! Yep, see above...wish I knew where I saw that 'explanation' of repr() and str() # boo, we have no builtin bool global True [snip] Rather than testing the version, you can test directly to see whether True and False are defined. If not, you can add them to the __builtin__ module and they will be globally available. Here is one way: import __builtin__ if not __builtin__.hasattr('True'): __builtin__.True = 1 if not __builtin__.hasattr('False'): __builtin__.False = 0 OK, that's helpful. I can see the advantages of several of python's mechanisms, such as dir() as well as treating everything like an 'interactive object to determine existing methods and attributes (dir() and your example of hasattr(). Pretty cool...now to go from libc/POSIX to an entirely new and (mostly) different set of core libs and functionality.. ;-) Actually, that IS pretty nice, can perhaps take the place of some(most?) of features.h, unistd.h and friendswhich is really what I want, regardless of the example...or having to 'roll my own'. Very cool. This suggestion is taken from this thread on comp.lang.python: http://tinyurl.com/46me3 Note that adding names to __builtin__ is NOT recommended in general! Don't use this to create your own global constants! It is OK in this case because to duplicate Python 2.3 behaviour you need a true global. The other oddity is without being able to define a 'real' constant, as in #DEFINE MINVERSION 1.5, the scope of MINVERSION (and True/False) even using the global keyword still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generally The usual Python solution is to make a module containing constant definitions and import it where you need them. [snip] or, if you want to import all the constants directly, # Client2.py from Constants import * There was my catch/issue I was having. I expected the global keyword being used in my previous bool/True/False definition to put it into a global namespace, but I still had a namespace issue as you explained here- simply doing an 'import module' will allow access to variables created as globals in that module, but not without scope resolution, ie module.True, module.MINVERSION, etc...what I expected was anything declared as global to simply be in the global namespace of any other module importing the one with the declaration. if (MINVERSION == 1.5): ... A last question would also be if the equivalent of __FILE__ and __LINE__ macros exist? Great- looks like there's a link for python 2.X as well, will definitely look at using that! Thanks! See this
[Tutor] Looking for a project participate in (a little OT)
I'm learning python for a few months now, and I would like to get some experience by participating in a good, open source, and small python-CGI project. I searched freshmeat.net but couldn't find anything interesting (except __ but I think its dead...). Anyone knows of a good small and open source python-CGI project that needs people ? Thanks. And sorry if its to much OT. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] automatically finding site-packages and python2.3 in a linux machine
Hi everyone, I'm working on creating an installer for my program using install shield, and I'd like to know how one can automatically determine if Python 2.3 is installed on a linux machine, and where site-packages is located (so that I can install my own files there). For my Windows version I was able to search for the python2.3 entry in the windows registry, but I don't know how do the equivalent from linux. Any ideas? Thanks Fred ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
I'm _very_ used to using C style constants (preprocessor #define directives) or C++ const keyword style, for a variety of reasons. I've yet to see anything covering 'how to work around the lack of constants in Python'...can anyone point me in the right direction here? Define Constants in Upper case letters and don't change anything that has an uppercase name... Its consistent with Python's philosophy of us all being consenting adults not idiots... still uses the ocal file's namespace. I don't want to debate the merits of using globals...most people that claim they never use any in other languages _still_ use constants in header files, which is the purpose I'd like to be able to do generally... THats fine just import the consants module. Using modules avoids name clashes and is A Good Thing - even for constants. really am _not_ thrilled with the use of string literals typed in each time in code (yes, quick and dirty code but still) I see seems to be 'OK' in python for the use of comparisons...opposed to something like if(strncmp(strVal, CONSTANT_STRING_VAL_LIKE_HTTP_ACCEPT_ENCODING_HEADER, strlen(strVal) { do_something(); } Not sure whatthe issue is here. You can define string constants and compare them if you wish. jUst as you can compare string literals in C... I have a feeling I'm missing your point? if(floatVal PI) { do_something() } Again, not sure what the issue is. Use math.pi as a constant, whats the issue? A last question would also be if the equivalent of __FILE__ and __LINE__ macros exist? Sadly not, that's one thing I would like to see. It is possible to fake it via traceback objects but its mucky. You can get file fairly easily via the __Name__ magic variable but line number is trickier. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Array pointers
Pixels - just ones and zeroes? Pack them as integers and apply the right shift operator: i=1 But you have to remember to overflow right hand ones into the next integer if there are more than 32 bits... Although Python long integers migfht work, dunno what the speed of shifting a long integer is in Python.. hmmm must try it! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] automatically finding site-packages and python2.3 in a linux machine
On Thu, 6 Jan 2005, Fred Lionetti wrote: I'm working on creating an installer for my program using install shield, and I'd like to know how one can automatically determine if Python 2.3 is installed on a linux machine, and where site-packages is located (so that I can install my own files there). For my Windows version I was able to search for the python2.3 entry in the windows registry, but I don't know how do the equivalent from linux. Any ideas? Hi Fred, Yes, there are some undocumented functions in the Distutils package that you can use to find where 'site-packages' lives. Let me check... ah, ok, the function that you're probably looking for is distutils.sysconfig.get_python_lib(). For example: ### distutils.sysconfig.get_python_lib() '/usr/lib/python2.3/site-packages' ### def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. If 'prefix' is supplied, use it instead of sys.prefix or sys.exec_prefix -- i.e., ignore 'plat_specific'. So you can use Python itself to introspect where the libraries should live. I hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
On Thu, 6 Jan 2005, Alan Gauld wrote: I'm _very_ used to using C style constants (preprocessor #define directives) or C++ const keyword style, for a variety of reasons. I've yet to see anything covering 'how to work around the lack of constants in Python'...can anyone point me in the right direction here? Hi Scott, There are a few recipes in the Python Cookbook that mentions how to get a const mechanism in Python: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965 But I have to admit that I don't use this approach myself; I've been using the uppercase convension, and it seems to work ok. Good luck to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] automatically finding site-packages and python2.3 in a linux machine
I'm working on creating an installer for my program using install shield, and I'd like to know how one can automatically determine if Python 2.3 is installed on a linux machine Hi Fred, Sorry about ignoring parts of your question! Unix has default places for putting binaries like Python. Check the directories '/usr/bin/' and '/usr/local/bin'. Also, the 'which' command will also tell us where Python is, if it's in the user's PATH: ### [EMAIL PROTECTED] dyoo]$ which python /usr/bin/python ### and where site-packages is located (so that I can install my own files there). For my Windows version I was able to search for the python2.3 entry in the windows registry, but I don't know how do the equivalent from linux. Any ideas? Yes, there are some undocumented functions in the Distutils package that you can use to find where 'site-packages' lives. I'm totally wrong about this. It IS documented. *grin* Here's a link to the official documentation: http://www.python.org/doc/dist/module-distutils.sysconfig.html Sorry about that; I had expected to find it in the Library Reference, but the Distutils stuff has its own separate documentation. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
Danny Yoo wrote: There are a few recipes in the Python Cookbook that mentions how to get a const mechanism in Python: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/197965 These require Python 2.1 and 2.3 respectively; the OP indicated he needs to work with 1.5.2! But I have to admit that I don't use this approach myself; I've been using the uppercase convension, and it seems to work ok. (To Scott, not Danny): Compared to Java and C++, Python has very meager facilities for controlling how code is used. There is no const, and only the slightest nod to access control with the _ and __ naming conventions. And of course the lack of static typing limits your control over function parameters. Although this might make you a bit nervous at first, in practice it doesn't cause problems and is very freeing. Later versions of Python have some methods that let you build controls, as Danny pointed out, but my suggestion is, just relax and try the Python way! Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: The Game of Life
On Jan 6, 2005, at 21:20, Brian van den Broek wrote: Oh, the Life rules allow a world where every cell will change in the next generation, iff your world is a torus (i.e. the lower row touches the upper row as if it were immediately above it, and the right column touches the left column as if it were immediately left of it). It is quite trivial: set all cells to LIVE. Next generation they're all DEAD. Topologist! (That's cheating!) ;-) If we are going that way, you 'iff' seems a bit hasty. Take the 1x1 matrix 'full' of live cells. Well, if the only cell of a 1x1 torus matrix is LIVE, that means it is surrounded by 4 LIVE cells, doesn't it? :D Also, other 'funny' (in the sense that a torus is funny) planes could be defined (say a torus-like structure with more than 1 whole -- cannot recall the general terminology from ill-remembered topology), etc. I meant the claim for a standard non-trivial (i.e. M 1 and N 1) MxN euclidean plane matrix, but your correction is both amusing and welcome. Thanks :) However, the main reason why I talked about a torus is that it's one of the two obvious choices when you're implementing Life using a 2D matrix (the other being a finite rectangular plane). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a project participate in (a little OT)
I searched freshmeat.net but couldn't find anything interesting I guess that depends a bit on what you find intersting! But rather than frshmeat why not search source-forge? There are far more projects on source forge than those that get announced on freshmeat. And many are looking or people to do small jobs like write test scripts that don't need deep knowledge of the project. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] German Totorial!?!
Hoi Michael, Apart from Alan's tutorial in German and the link Andrew provided you might want to have a look here: http://python.sandtner.org/ (The German Python forum.) You'll find not only links to other German sources, but also friendly support in German ;-). Gruss, Christian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] replacement for constants from other languages in Python?
Compared to Java and C++, Python has very meager facilities for controlling how code is used. There is no const, and only the slightest nod to access control my suggestion is, just relax and try the Python way! I'll second that. I came to Python after years of C++ (and Pascal - even more strict!) and initially thought that Python's approach, while great for a scripting language, would lead to problems on bigger projects. Well, I haven't written anything truly huge yet but I haven't hit any more problems than I did in C/C++ so far - and C/C++ introduce their own problems with overly strict typing, especially in OOP work. My experience of Smalltalk at university (and in Lisp too) should have made me less concerned but years of indoctrination by the software engineering establishment had led me to believe in the idea of the language controlling the programmer rather than the other way around... Although I haven't used it on big projects either, I suspect that Objective C as used in Apple's Cocoa framework may offer a good mix of freedom and strictness for large industry strength projects. The more I use Objective C the more I like its divisio of concerns betweentraditional C style coding and the OO features where dynamic dispatch is a huge win over C++/Java's strict typing. Similarly features such as __FILE__ and __LINE__ are often used in C because the debugger and error reporting support is so poor, in a duynamic, interpreted language with full exception handling the need is restricted to log files and audit trails etc. So while I miss __LINE__ especially, I don;t need it nearly as much as I did in C. And finally, because Python operates at a much higher level you only write a fraction of the code that you do in C, so the need for these navigation aids is much less. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: The Game of Life
Hi all, after making the sketch I posted a bit ago, I tried to turn to actual work. But, the bug had bit. ;-) So, here is an attempt at filling out that sketch in an OOP way. (It is my second OOP program, so if anyone was so inclined, I'd very much appreciate any comments. Also, I have a question about a snag I ran into while debugging.) I'm also not too used to sharing complete code. I'd put it in the public domain, but since so much of it was derived from Danny's code, I don't really know the conventions for so doing. (Were I to know it appropriate, I'd follow the copyright comment line with: # This software is released into the public domain. # Fold, spindle, or mutilate at will I've attached it rather than pasted it, as with something 100 lines I don't feel up to shortening line for email. Sorry 'bout that. The question: In an earlier version, instead of the run_world() method I now have, I put the following within my class definition and after (i.e. outside of) the method defs: .while self.current_generation self.total_generations: .time.sleep(self.sleep_interval) .self.update_world() .self.print_world() which caused this: Traceback (most recent call last): File D:\Python Files\foogame_of_life.py, line 3, in -toplevel- class life_world: File D:\Python Files\foogame_of_life.py, line 76, in life_world while self.current_generation self.total_generations: NameError: name 'self' is not defined That surprised me -- I'd have guessed that within a class, self was everywhere defined, and not just within methods. Clearly, I'm confused about something. Anyway, thanks for reading. Best to all, Brian vdB # pylife.py # Version 0.1 # Brian van den Broek # [EMAIL PROTECTED] # 2005-01-06 Thursday 17:41 # Copyright 2005 '''An OOP and ASCII based representation of Conway's Game of Life. Much of the code was inspired by a post of Danny Yoo's on 2005-01-03 04:11 to the Python Tutor List. (You can find that post by searching the archives at http://mail.python.org/pipermail/tutor/.) I make no claims to ellegance or efficency -- this is only the second OOP I have written.''' import random, time class life_world: def __init__(self, X, Y, sleep_interval = 0.5, total_generations = 20): self.X = X self.Y = Y self.world = self.seed_world() self.sleep_interval = sleep_interval self.total_generations = total_generations self.current_generation = 0 self.print_world() def seed_world(self): '''Constructs a new random world of size XxY.''' world = {} for j in range(self.X): for i in range(self.Y): world[i, j] = random.choice((True, False)) return world def print_world(self): '''Prints out a string representation of a world.''' print '\n\nGeneration Number: %s\n' %self.current_generation print '--'*(self.Y + 1) + '-' for j in range(self.X): print '|', for i in range(self.Y): if self.world[i, j]: print 'X', else: print ' ', print '|' print '--'*(self.Y + 1) + '-' def count_neighbours(self, cell): '''Returns the number of live neighbours to this one. 'neghboUrs because I'm Canadian, eh. ''' live_count = 0 i,j = cell for i_delta in [-1, 0, 1]: for j_delta in [-1, 0, 1]: if (i_delta, j_delta) == (0, 0): continue try: # To deal with the edges of the matrix, where the # deltas can take us out of bounds. if self.world[i+i_delta, j+j_delta]: live_count += 1 except KeyError: pass return live_count def cell_will_change(self, cell): '''Returns True if a cell will change, False otherwise.''' change = False if self.world[cell] and not self.count_neighbours(cell) in (2,3): change = True if not self.world[cell] and self.count_neighbours(cell) == 3: change = True return change def get_changed_cells_list(self): '''Returns a list of cells that will change in the next generation.''' changed_cells_list = [] for c in self.world: if self.cell_will_change(c): changed_cells_list.append(c) return changed_cells_list def update_world(self): '''Produces the next generation world.''' self.current_generation += 1 changed_cells_list = self.get_changed_cells_list() for c in changed_cells_list: self.world[c] = not self.world[c] def run_world(self): while self.current_generation self.total_generations: time.sleep(self.sleep_interval) self.update_world()
Re: [Tutor] trouble getting a list to update
On Thu, 6 Jan 2005, Vincent Wan wrote: On Jan 6, 2005, at 12:59 PM, Danny Yoo wrote: Can you show us a snippet of the file output? I'm not immediately seeing anything particular with your debugging output statements: Like the computer, I don't yet understand what the problem is. *grin* If you can point us at the output that looks weird to you, and tell us what you expected to see instead and why, that will help us a lot to better understand the situation. Hi Vincent, Ok, now I understand and see the bug. write_list() contains the problem: ### def write_list(list_to_write, file_name): Writes elements of a list, seperated by spaces, to a file for each in list_to_write: file_name.write(str(list_to_write[each]) + ' ') file_name.write('\n') ### The bug is here: file_name.write(str(list_to_write[each]) + ' ') Do you see why this is buggy? 'each' is not an index into list_to_write, but is itself an element of list_to_write. You probably meant to write: file_name.write(str(each) + ' ') Your list was mutating just fine: the output function simply was obscuring what was happening. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] German Tutorials auf Deutsch
Title: German Tutorials auf Deutsch Pardon to the non-german speaking (or readers) on the list. Guten Tag. Mein Deutsch ist nicht so gut (ich habe keinen Deutsche in sieben Jahren geschreiben). Mann kann Python Tutorials auf Deutsch heir http://www.freenetpages.co.uk/hp/alan.gauld/german/index.htm und http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index_ger.html und http://starship.python.net/crew/gherman/publications/tut-de/ finden. I habe Alan Gauld Tutorial vorgelesen. Es is gut und es abdeckt zimliche viele Themen. Ara ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: The Game of Life
Brian van den Broek wrote: In an earlier version, instead of the run_world() method I now have, I put the following within my class definition and after (i.e. outside of) the method defs: .while self.current_generation self.total_generations: .time.sleep(self.sleep_interval) .self.update_world() .self.print_world() which caused this: Traceback (most recent call last): File D:\Python Files\foogame_of_life.py, line 3, in -toplevel- class life_world: File D:\Python Files\foogame_of_life.py, line 76, in life_world while self.current_generation self.total_generations: NameError: name 'self' is not defined That surprised me -- I'd have guessed that within a class, self was everywhere defined, and not just within methods. self is just another method parameter. OK not quite, but it is a method parameter and it is only bound within the scope of the method. There is nothing magic about the name, either; it is just a (strong) convention. In fact, by using a different name for self and the magic of lexical scoping and closures, you can do something very much like Java inner classes - make a nested class that has access to all the attributes of the enclosing class. This is off-topic and a bit twisted, but I'm not going to let that stop me: ''' Make a nested class that has access to the attributes of its parent class ''' class Outer: def __init__(outerSelf, x): outerSelf.x = x def makeNested(outerSelf, x): class Nested: def __init__(innerSelf, x): innerSelf.x = x def showX(innerSelf): print 'outer x is', outerSelf.x print 'inner x is', innerSelf.x return Nested(x) o = Outer(3) n = o.makeNested(5) n.showX() o.x = 22 n.showX() prints: outer x is 3 inner x is 5 outer x is 22 inner x is 5 Kent Clearly, I'm confused about something. Anyway, thanks for reading. Best to all, Brian vdB # pylife.py # Version 0.1 # Brian van den Broek # [EMAIL PROTECTED] # 2005-01-06 Thursday 17:41 # Copyright 2005 '''An OOP and ASCII based representation of Conway's Game of Life. Much of the code was inspired by a post of Danny Yoo's on 2005-01-03 04:11 to the Python Tutor List. (You can find that post by searching the archives at http://mail.python.org/pipermail/tutor/.) I make no claims to ellegance or efficency -- this is only the second OOP I have written.''' import random, time class life_world: def __init__(self, X, Y, sleep_interval = 0.5, total_generations = 20): self.X = X self.Y = Y self.world = self.seed_world() self.sleep_interval = sleep_interval self.total_generations = total_generations self.current_generation = 0 self.print_world() def seed_world(self): '''Constructs a new random world of size XxY.''' world = {} for j in range(self.X): for i in range(self.Y): world[i, j] = random.choice((True, False)) return world def print_world(self): '''Prints out a string representation of a world.''' print '\n\nGeneration Number: %s\n' %self.current_generation print '--'*(self.Y + 1) + '-' for j in range(self.X): print '|', for i in range(self.Y): if self.world[i, j]: print 'X', else: print ' ', print '|' print '--'*(self.Y + 1) + '-' def count_neighbours(self, cell): '''Returns the number of live neighbours to this one. 'neghboUrs because I'm Canadian, eh. ''' live_count = 0 i,j = cell for i_delta in [-1, 0, 1]: for j_delta in [-1, 0, 1]: if (i_delta, j_delta) == (0, 0): continue try: # To deal with the edges of the matrix, where the # deltas can take us out of bounds. if self.world[i+i_delta, j+j_delta]: live_count += 1 except KeyError: pass return live_count def cell_will_change(self, cell): '''Returns True if a cell will change, False otherwise.''' change = False if self.world[cell] and not self.count_neighbours(cell) in (2,3): change = True if not self.world[cell] and self.count_neighbours(cell) == 3: change = True return change def get_changed_cells_list(self): '''Returns a list of cells that will change in the next generation.''' changed_cells_list = [] for c in self.world: if self.cell_will_change(c): changed_cells_list.append(c) return changed_cells_list def update_world(self): '''Produces the next