Re: [Tutor] Maximum recursion depth problem.
Morning Peter, Thanks, that was something I was unaware of! Not sure how I hadn't bumped into that before! Cheers, Wesley. On 3 August 2010 11:40, Peter Otten <__pete...@web.de> wrote: > Wesley Brooks wrote: > >> I'm having real difficulty understanding why the following is not >> working and hoped I've either missed something obvious of I'm doing >> something wrong! >> >> class A: >> def break_down(self, value, base, broken_list=[]): > >> I'm a little stumped as I don't think I'm using any global or class >> variables? Any help would be much appreciated. > > You are on the right track, the default value for broken_list is > evaluated only once; Modifications during an invocation of the > break_down() method are visible when break_down() is called again later. > > See also > > http://docs.python.org/faq/design.html#why-are-default-values-shared-between-objects > > Peter > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Maximum recursion depth problem.
Ok a little more investigation has found the follwing work but there not as tidy. I'd still really appreciate someone explaing why this behaves like this! class A: def break_down(self, value, base, broken_list=[]): power = len(broken_list) digit = (value % (base ** (power + 1))) / (base ** power) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256, []) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256, []) print d_list_2 ..OR: class A: def break_down(self, value, base, broken_list=None): if broken_list == None: broken_list = [] power = len(broken_list) digit = (value % (base ** (power + 1))) / (base ** power) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256) print d_list_2 Yours Faithfully, Wesley Brooks On 3 August 2010 11:02, Wesley Brooks wrote: > Dear Python Users, > > I'm having real difficulty understanding why the following is not > working and hoped I've either missed something obvious of I'm doing > something wrong! > > class A: > def break_down(self, value, base, broken_list=[]): > power = len(broken_list) > digit = int((value % (base ** (power + 1))) / (base ** power)) > value -= digit * (base**power) > broken_list.append(digit) > if value != 0: > return self.break_down(value, base, broken_list=broken_list) > else: > return broken_list[:] > > if __name__ == '__main__': > a = A() > d_list_1 = a.break_down(34567, 256) > print d_list_1 > a2 = A() > d_list_2 = a2.break_down(34567, 256) > print d_list_2 > > When the above runs it fails with the error "RuntimeError: maximum > recursion depth exceeded while calling a Python object". > > The following also does not work: > > if __name__ == '__main__': > a = A() > digit_list_1 = a.break_down(34567, 256) > print digit_list_1 > del digit_list_1, usc > a2 = A() > digit_list_2 = a2.break_down(34567, 256) > print digit_list_2 > > but the following two do work: > > if __name__ == '__main__': > a = A() > digit_list_1 = a.break_down(34567, 256) > print digit_list_1 > #a2 = A() > #digit_list_2 = a2.break_down(34567, 256) > #print digit_list_2 > > if __name__ == '__main__': > #a = A() > #digit_list_1 = a.break_down(34567, 256) > #print digit_list_1 > a2 = A() > digit_list_2 = a2.break_down(34567, 256) > print digit_list_2 > > I'm a little stumped as I don't think I'm using any global or class > variables? Any help would be much appreciated. > > Yours Faithfully, > > Wesley Brooks > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Maximum recursion depth problem.
Dear Python Users, I'm having real difficulty understanding why the following is not working and hoped I've either missed something obvious of I'm doing something wrong! class A: def break_down(self, value, base, broken_list=[]): power = len(broken_list) digit = int((value % (base ** (power + 1))) / (base ** power)) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list[:] if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256) print d_list_2 When the above runs it fails with the error "RuntimeError: maximum recursion depth exceeded while calling a Python object". The following also does not work: if __name__ == '__main__': a = A() digit_list_1 = a.break_down(34567, 256) print digit_list_1 del digit_list_1, usc a2 = A() digit_list_2 = a2.break_down(34567, 256) print digit_list_2 but the following two do work: if __name__ == '__main__': a = A() digit_list_1 = a.break_down(34567, 256) print digit_list_1 #a2 = A() #digit_list_2 = a2.break_down(34567, 256) #print digit_list_2 if __name__ == '__main__': #a = A() #digit_list_1 = a.break_down(34567, 256) #print digit_list_1 a2 = A() digit_list_2 = a2.break_down(34567, 256) print digit_list_2 I'm a little stumped as I don't think I'm using any global or class variables? Any help would be much appreciated. Yours Faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ask-why I cannot run it, and I am so confused about the traceback
Morning, Your only supplying one argument to cone, when you need two: radius & height. Cheers, Wesley Brooks. On 7 April 2010 11:56, Shurui Liu (Aaron Liu) wrote: > # Filename: classVolume.py > # Demonstrates multiple classes per program. > > class Cube: > """A class for cube shapes.""" > def __init__(self, side): > self.side = side > def calculateArea(self): > return (self.side)**3.0 > > class Sphere: > """A class for sphere shapes.""" > def __init__(self, radius1): > self.radius1 = radius1 > def calculateArea(self): > import math > return (4/3)*(math.pi)*((self.radius1)**3.0) > > class Cone: > """A class for cone shapes.""" > def __init__(self, radius2, height): > self.radius2 = radius2 > self.height = height > def calculateArea(self): > import math > return (1/3.0)*(math.pi)*(self.height)*((self.radius2)**2) > > > # Create a list of volumes. > list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)] > > # Print out the list contents. > for volume in list: > print "The volume is: ", volume.calculateArea() > raw_input("\n\nPress the enter key to exit.") > > > > > > Traceback (most recent call last): > File "classVolume.py", line 30, in > list = [Cube(1.1),Cube(1.2),Sphere(1.1),Sphere(1.2),Cone(1.1),Cone(1.2)] > TypeError: __init__() takes exactly 3 arguments (2 given) > > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > 419-508-1228 > > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Small python web server suitable for web cam streams?
At the minimum the page would need to display progress through a job, any error messages, and a picture from the web camera. I've used something that grabbed images from a USB camera using python a while back so at the simplest I could be just after something to display a html page with an image and just update the page on the server end once every second or so and rely on the user to hit the refresh to get a new image. For the next level it would be great to have something as above but with a video stream from the camera, and various pages displaying temperatures etc. The very best would have time plots for various temperatures (these of course could be images generated by seperate scripts as before) and email alerts out to users when a job is complete or an error occurs. Is this best solved using two different toolkits? One to make the page and another to host it? Thanks for your help. I'll have a look at CherryPy. Wesley. 2009/1/14 Kent Johnson > On Wed, Jan 14, 2009 at 10:37 AM, Wesley Brooks > wrote: > > I have a machine which runs for extended periods of time, and often into > > days rather than just hours. I would like to set up the computer so that > it > > hosts a simple web page displaying current status information, and a feed > > from a web camera which is viewing the business end of the machine. This > web > > site will not be opened to the wider internet, just kept as open access > to > > all machines on the local network. There is currently no requirement for > any > > control from the user end, just to view the page or pages. > > Will the web server generate the status page and talk to the camera, > or is it just showing static data that comes from somewhere else? > > If the data is generated outside the server you can use IIS or Apache > to display them. If you are generating pages in the server then > something simple like CherryPy might be a good choice, rather than one > of the full-featured web frameworks. > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Small python web server suitable for web cam streams?
Dear Users, I'm aware that there is a large array of web toolkits available in python and I would like to hear some opinions on which may be best suited to my specification so I can research them further. I have a machine which runs for extended periods of time, and often into days rather than just hours. I would like to set up the computer so that it hosts a simple web page displaying current status information, and a feed from a web camera which is viewing the business end of the machine. This web site will not be opened to the wider internet, just kept as open access to all machines on the local network. There is currently no requirement for any control from the user end, just to view the page or pages. This will be running on a windows machine. Yours Faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is it thread safe to collect data from threads where run has finished?
Dear Users, I've got a few tasks that block for a while and cause my wxPython interface to lock up while they process. I'm thinking about migrating these to threads which I kick off when I want the task done. In the run bit of the thread the main work will be done, it will store the information as part of the object and when done post an event to the user interface for it to collect of the information and dispose of the thread. So there'll be a part of a wx event that looks something like: *self.loadThread = FileLoadThread(fileName, doneEvent) self.loadThread.start() * The FileLoadThread object would look like: *class FileLoadThread(threading.Thread): def __init__(self, mainGUI, fName, doneEvent): self.mainGUI = mainGUI self.fName = fName self.event = doneEvent threading.Thread.__init__(self) def run(self): self.dataObject = self.LoadFile(fName) wx.PostEvent(mainGUI, doneEvent)* ...where doneEvent is a custom event that signals to the user interface that it can collect the dataObject by doing the following: *self.dataObject = self.loadThread.dataObject* *del self.loadThread* Is this the best way to do this or should I just attach the dataObject to the event? Is the use of wx.PostEvent thread safe? Thanks in advance of any advice, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which exceptions should I be catching?
> > That's why you should write an error log ;) The error log is a valid point. Is there a way to capture the error messages that go the the terminal window or command prompt rather than all my print statements? Can this be set up as a global thing for the whole application rather than inside each thread? try: > put your function here > except: > print 'oops! an error occurred!' > I'll probably resort to this and have done in a couple of other occasions, but thought it was generally frowned upon! I Guess I could do that and print out anything caught by the exception into a log and go more specific at a later date. Cheers, Wesley Brooks > On Mon, Oct 20, 2008 at 3:30 PM, Wesley Brooks <[EMAIL PROTECTED]>wrote: > >> Unfortunately due to the nature of the program the error has normally >> happened hours ago and the error message has disappeared from the buffer of >> the command prompt. >> > > That's why you should write an error log ;) > > >> >> This is the function: >> >> def CommandFileWriter(self, command): >> name1 = os.path.join(self.commandsdir, command + '.temp') >> name2 = os.path.join(self.commandsdir, command) >> comfile = open(name1, 'w') >> comfile.close() >> if not os.path.exists(name2): >> os.rename(name1, name2) >> else: >> os.remove(name1) >> >> This was the best way I could come up with doing the function. So the file >> is written to the correct directory with a wrong name (so the other program >> will ignore it) then it's name is changed to the correct name with >> os.rename. Unfortunately I think in freak occations the other program can >> read and delete the file (running on a multicore processor system) during >> the rename operation. Can you suggest which errors I should be trying to >> catch? >> > > I'm not sure what errors to catch, but it's always possible to use a > general catchall (I'm not sure if this is particularly pythonic) > > try: > put your function here > except: > print 'oops! an error occurred!' > > Or do something besides print an error (such as write a message to a > logfile. If you include the time stamp and some other info that might be > helpful that may give you some more insight as to where the problem is, and > if it's something you can fix.) > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Which exceptions should I be catching?
Dear Users, I've got a program that passes messages to another program in the form of empty files, whereby the title of the file is the command. I've been speaking to this board about this before about doing this in the quickest possible way. Even with the code layed out as follows the code still breaks once in a blue moon. Unfortunately due to the nature of the program the error has normally happened hours ago and the error message has disappeared from the buffer of the command prompt. This is the function: def CommandFileWriter(self, command): name1 = os.path.join(self.commandsdir, command + '.temp') name2 = os.path.join(self.commandsdir, command) comfile = open(name1, 'w') comfile.close() if not os.path.exists(name2): os.rename(name1, name2) else: os.remove(name1) This was the best way I could come up with doing the function. So the file is written to the correct directory with a wrong name (so the other program will ignore it) then it's name is changed to the correct name with os.rename. Unfortunately I think in freak occations the other program can read and delete the file (running on a multicore processor system) during the rename operation. Can you suggest which errors I should be trying to catch? I guess the last four lines could also be caught by try except as well. Although the program is currently running on windows XP I would like any soloution to be cross platform for testing and future-proofing reasons. Thanks in advance of any suggestions, Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating a unicode string from bytes and % opperator
Thanks Tim Golden, That'll do the trick! Thought there must have been something simple for it! Cheers, Wesley Brooks 2008/7/28 Tim Golden <[EMAIL PROTECTED]>: > Wesley Brooks wrote: >> >> I'm trying to create a unicode character from two bytes. Unfortunatly >> I'm getting a "UnicodeDecodeError". Can some one please suggest an >> alternative way of doing what's bellow? In the example bellow the two >> bytes have been converted into a string hex value, but they could just >> as easily be an integer or binary value if either is easier to deal >> with. >> >> Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug 2 2006, 12:09:59) [MSC >> v.1310 >> 32 bit (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> a = u"\u%s%s" %('0d', 'fe') >> >> UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position >> 0-2: tr >> uncated \u escape > > Nice try :) > > Unfortunately, if you think about what's happening here, the > "string interpreter" bit of Python is getting to that > unicode-escape before the "%-processing" bit of Python. > So Python's trying --and failing-- to interpret \u%s%s as some sort of > bizarre unicode escape. > > Can you not just use the unichr function? > > TJG > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating a unicode string from bytes and % opperator
Dear Users, I'm trying to create a unicode character from two bytes. Unfortunatly I'm getting a "UnicodeDecodeError". Can some one please suggest an alternative way of doing what's bellow? In the example bellow the two bytes have been converted into a string hex value, but they could just as easily be an integer or binary value if either is easier to deal with. Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug 2 2006, 12:09:59) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = u"\u%s%s" %('0d', 'fe') UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: tr uncated \u escape >>> Cheers, Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Make sound with python? Cross platform?
Thanks very much. Not quite sure why I didn't find those earlier! I'll have a look now. Cheers, Wesley. On 09/03/2008, Kent Johnson <[EMAIL PROTECTED]> wrote: > Wesley Brooks wrote: > > Dear Users, > > > > I've been digging around to try and find a way to make python make > > sound. I would either like to sound out a string of musical notes > > including rests or simply have something that I set the frequency and > > duration then sound and repeat for the number of notes. > > > > If possible I would prefer a solution that is cross platform, and > > standard library but would settle for Linux only solutions that can be > > downloaded - which preferably don't need compiling. > > > pygame and pyglet+avbin both play sounds, are cross-platform and have > binaries available for Windows, Mac and Linux. > > The "Playing and creating sound" section of this page looks promising: > http://wiki.python.org/moin/PythonInMusic > > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Make sound with python? Cross platform?
Dear Users, I've been digging around to try and find a way to make python make sound. I would either like to sound out a string of musical notes including rests or simply have something that I set the frequency and duration then sound and repeat for the number of notes. If possible I would prefer a solution that is cross platform, and standard library but would settle for Linux only solutions that can be downloaded - which preferably don't need compiling. Thanks for any suggestions. Yours Faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Closing file objects when object is garbage collected?
Dear Python Users, How do I ensure that when an object is deleted by the garbage collector that the file objects contained within the object are closed, or collected by the garbage collector? I'd like to avoid having to read the whole file object into a string and close the file immediately because the files can potentially be large, and I'm dealing with many files at a time. I'm having issues when I test my software on XP, but not Linux. When I run the progam it fails after running for a while but not at exactly the same point each time. It fails in one of two ways, the user interface either completely disappears, or gives a OS error message unhanded exception error. Thanks in advance of any help, Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Interactive Menu Woes
In the middle of your addName function you have defined another function that requires 'self' and you've got a default argument 'get=1'; def numberType(self, get = 1): You call this further down the function with the line; self.type = numberType(self.get) This should have been; self.type = numberType(self) I would suggest moving the numberType function from inside the addName function as follows; class MenuInput: def addName(self): print "To add a name, please input he following information: " name = raw_input("Name: ") number = raw_input("Number: ") get = int(raw_input("What type of number is this? (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : ")) type = self.numberType(get) enter = phoneentry() enter(name, number, returnType) def numberType(self, get): if get == 1: returnType = HOME elif get == 2: returnType = WORK elif get == 3: returnType = FAX return returnType If you use self in a function all functions can see the value without having to have it in the function definition. For example; class a: def a(self): self.get = 1 def b(self): print self.get >>> aa = a() >>> aa.a() >>> aa.b() 1 >>> Default arguments in the function definition work as follows: class a: def a(self): self.get = 1 def b(self, get="Using default argument"): print get >>> aa = a() >>> aa.a() >>> aa.b() "Using default argument" >>> aa.b(1) 1 >>> Cheers, Wes. On 14/11/2007, Bryan Magalski <[EMAIL PROTECTED]> wrote: > > Greetings all!! > > This is my first post and I am going to probably be vague at first, but, I > will try my best to be specific. I am a very GREEN scripter/programmer, so > please be as descriptive as possible. Ok, enough excuses, on with my > question! > > Here is my issue: > > I am trying to build a menu for the following script to make it more "user > friendly". Nothing fancy, just a simple add data and look up the entered > results. > > The problem is that when I run my modified version with this snippet (please > see attachment for original and my modified versions): > > [code] > class MenuInput: > > # ask user to input data and store to be passed to manageable variables. > def addName(self): > print "To add a name, please input he following information: > " > self.enter = phoneentry() > self.name = raw_input("Name: ") > self.number = raw_input("Number: ") > self.get = int(raw_input("What type of number is this? > (choose one): \n 1. Home:\n 2. Work:\n 3. Cell:\n : ")) > def numberType(self, get = 1): > if self.get == 1: > self.returnType = HOME > #return self.getType > elif self.gete == 2: > self.returnType = WORK > #return self.getType > elif self.get == 3: > self.returnType = FAX > #return self.getType > return self.returnType > > self.type = numberType(self.get) > self.enter(self.name, self.number, self.returnType) > > def display(self): > print "Enter a name to look up: (leave blank to exit)" > self.Name = str(raw_input("Name: ")) > print "%s has the following information: " % self.Name > if self.Name != "": > foo = phonedb() > for entry in foo.lookup(self.Name): > print '%-40s %s (%s)' % (entry.name, > entry.number, entry.showtype()) > print > [/code] > > when I instantiate and run it with: > > [code] > menu = MenuInput() > menu.addName() > [/code] > > and enter the information asked, I am given this runtime error: > > [error] > To add a name, please input he following information: > Name: Bryan > Number: 1234567 > What type of number is this? (choose one): > 1. Home: > 2. Work: > 3. Cell: > : 1 > Traceback (most recent call last): > File "examples\testpy\my_object_modified.py", line 101, > in > menu.addName() > File "examples\testpy\my_object_modified.py", line 85, in > addName > self.type = numberType(self.get) > File "examples\testpy\my_object_modified.py", line 74, in > numberType > if self.get == 1: > AttributeError: 'int' object has no attribute 'get' > >>> > [/error] > > I "think" that this has something to do with passing the results or possibly > my functions are not properly calling (proper terminology?) each other. > > Now what/where am I wrong? As this is part of an object oriented > programming class, I wanted the menu constructed inherent to the class. > > Thank you in a
Re: [Tutor] __doc__ strings for attributes?
Thanks for the comments. >shape0 = BasicShape() >shape1 = BasicShape('cylinder', [20.,10.,36.]) I like this way of doing things, I could inherit the 3D data object's class and get it to build on itself. I could for example use a function definition like the following: def __init__(*args, **paramDict): self.args = args self.xScanSpacing = paramDict['xScanSpacing'] etc. and I get a very flexible base to expand on. I do however get a real problem when it comes to documenting the expected keywords and running into huge doc strings, when I prefer concise documentation. I like the following: class a: def __init__(*args, **paramDict): expectedParam = ['xScanSpacing', 'yScanSpacing'] paramDocDict = {'xScanSpacing': 'float mm spacing for x axis hatches', ...} To find out what parameters this object works with I could do; >>> aa = a() >>> aa.expectedParam ['xScanSpacing', 'yScanSpacing'] >>> aa.paramDocDict['xScanSpacing'] 'float mm spacing for x axis hatches' Is there an standard way of doing this? This isn't as nice to use as the doc strings and dir function. For example if I wanted to find out what I can do with a string I could call dir(' ') on the interpreter and have a list of functions and attributes contained in the string object. If I wanted a quick explanation of one function I could run; >>> print ' '.strip.__doc__ S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping >>> Cheers, Wesley Brooks. On 09/11/2007, Evert Rol <[EMAIL PROTECTED]> wrote: > > How can I add information to an object to explain what it expects as > > it's attributes? For instance I may have an object that creates a CAD > > file based on a set of default values which are set by the __init__ > > but can be altered before it runs. for example; > > Why don't you specify a doc-string in your class declaration? > > class MakeBasicShape: > """basic information > > detailed information about attributes > """ > > > But, with what you do, why don't you add parameters to MakeIt()? > > def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]): > self.boundsInfo = [shape, bounds] > > > Or perhaps, let your class be the object you're creating (and rename > it to 'BasicShape'; verbs in class names seem a bit odd to me)? The > __init__ method would then fulfill the function of the MakeIt method, > and things would become: > shape0 = BasicShape() > shape1 = BasicShape('cylinder', [20.,10.,36.]) > etc. > > That is, unless you're doing other things in your factory object that > don't show up here. > > > > def MakeIt(self): > > assert self.boundsInfo[0] in self.boundsOptions, > >"Option not recognised: %s", self.boundsInfo[0] > > I also wouldn't use assert, but try: except: in MakeIt() for example > (assert is really for debugging, but here it looks more like you're > trying to prevent user mistakes). > > > Anyway, hope that that gets you further. > >Evert > > > > if self.boundsInfo[0] == 'cuboid' > > bounds = self.boundsInfo[1] > > # code to make box > > elif self.boundsInfo[0] == 'cylinder' > > [height, radius, noSides] = self.boundsInfo[1] > > # code to make cylinder > > elif self.boundsInfo[0] == 'cad' > > fileName = self.boundsInfo[1] > > # code to load CAD file > > return shape > > > > > > if __name__ == '__main__': > > shapeFactory0 = MakeBasicShape() > > shape0 = shapeFactory.MakeIt() # a box > > > > shapeFactory1 = MakeBasicShape() > > shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]] > > shape1 = shapeFactory.MakeIt() # a cylinder > > > > shapeFactory2 = MakeBasicShape() > > shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl'] > > shape2 = shapeFactory.MakeIt() # a CAD file > > > > While this example could be coded with different functions for making > > a box, cylinder, and loading the CAD file I wanted to use attributes > > to control the object to simplify interaction with it from the user > > interface code. I would like to move away from getters and setters as > > they're taking up vast chunks of my code at the moment and do very > > little! > > > > Can I also stop new attributes being added to the MakeBasicShape > > class? > > > > Thanks in advance of any help. > > > > Wesley Brooks > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] __doc__ strings for attributes?
Dear Users, How can I add information to an object to explain what it expects as it's attributes? For instance I may have an object that creates a CAD file based on a set of default values which are set by the __init__ but can be altered before it runs. for example; class MakeBasicShape: def __init__(self): self.boundsOptions = ['cuboid', 'cylinder', 'cad'] self.boundsInfo = ['cuboid', [0.,10.,0.,10.,0.,10.]'] def MakeIt(self): assert self.boundsInfo[0] in self.boundsOptions, "Option not recognised: %s", self.boundsInfo[0] if self.boundsInfo[0] == 'cuboid' bounds = self.boundsInfo[1] # code to make box elif self.boundsInfo[0] == 'cylinder' [height, radius, noSides] = self.boundsInfo[1] # code to make cylinder elif self.boundsInfo[0] == 'cad' fileName = self.boundsInfo[1] # code to load CAD file return shape if __name__ == '__main__': shapeFactory0 = MakeBasicShape() shape0 = shapeFactory.MakeIt() # a box shapeFactory1 = MakeBasicShape() shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]] shape1 = shapeFactory.MakeIt() # a cylinder shapeFactory2 = MakeBasicShape() shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl'] shape2 = shapeFactory.MakeIt() # a CAD file While this example could be coded with different functions for making a box, cylinder, and loading the CAD file I wanted to use attributes to control the object to simplify interaction with it from the user interface code. I would like to move away from getters and setters as they're taking up vast chunks of my code at the moment and do very little! Can I also stop new attributes being added to the MakeBasicShape class? Thanks in advance of any help. Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] visualizing code structure / flow charting
Following on from the comments above two things I've found really helpful are the __doc__ strings and the exec command. for example: >>> a = 'a random string' >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> print a.strip.__doc__ S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping >>> exec is also very useful. It allows you to run python code that is in a string, for example (Be it a simple and rather useless example!) the string; "print 1 + 2 ": >>> exec("print 1 + 2") 3 >>> Taking both one step further if you can extract all the __doc__ strings for all the objects listed from the dir of an object: a = 'a random string' for i in dir(a): command = "print str." + i + ".__doc__" exec(command) This will print out all the __doc__ strings for functions you can call on your string object a. This is particually helpful when you know what you want to do to something (for instance capitalise the first letter each word in a string) but don't know what function to call. Another instance when exec comes in handy is when receiving input from a user in a user interface. If used in this way you should be careful to check the data (parse) to ensure the user isn't running code that will cause your program problems. For example exec("import sys\nsys.exit()") would close the python interpreter, which will lead to your program crashing. [EMAIL PROTECTED] ~]$ python Python 2.5 (r25:51908, Apr 10 2007, 10:27:40) [GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> exec("import sys\nsys.exit()") [EMAIL PROTECTED] ~]$ Cheers, Wesley. On 06/11/2007, bhaaluu <[EMAIL PROTECTED]> wrote: > Greetings, > > On Nov 6, 2007 4:15 AM, Timmie <[EMAIL PROTECTED]> wrote: > > Hello, > > I am stepping forward into learning python and write my first programs now. > > To facilitate my development I have a question: > > > > Is there a tool which I can run on my code and then get a flow chart from > > it or > > visualize its structure in another form? > > > > I have found that a very simple and inexpensive way to look at Python > code while it's running is to insert a couple of lines in the code at the > points you want to look at: > > print variableName > raw_input("Pause") > > The 'print variableName' will print the value the variable is pointing to, > and 'raw_input("Pause") acts like a breakpoint, stopping program execution > so you can check out what's happening. Two other items of interest are: > > dir (itemName) > type (itemName) > > Both are extremely helpful when you're first learning Python. They're useful > for discovering the modules and attributes in classes, and checking the > type of objects. > > You can use these in addition to any graphical output tools you find. > > (Just Another Noob.) > -- > b h a a l u u at g m a i l dot c o m > http://www.geocities.com/ek.bhaaluu/python/index.html > > > > > There was a discussion about that soem time ago. > > OT: Flow chart - > > http://news.gmane.org/find-root.php?message_id=%3c1103452504.92b04ebcjerimed%40myrealbox.com%3e > > > > Is there any solution that can be used without leaning UML? > > > > Kind regards, > > Timmie > > > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Atomic file creation?
Dear Users, I'm looking for an atomic method for creating a file on the hard disk from python. Currently I'm using; def (command): """Creates a file with the name given by command.""" comFile = open(comFileName, 'w') comFile.close() This is not atomic as there are two operations needed to create this file. If the process was disturbed between these two files another process may not be able to read and delete the file (just reading the file name) as the above process may still hold it open. I realise I could do: import os def (command, tempDir='tempFiles', targetDir='commandDirectory'): """Creates a file with the name given by command in a temporary directory then moves it over to a target directory.""" tempName = os.path.join(tempDir,comFileName) finalName = os.path.join(targetDir,comFileName) comFile = open(tempName, 'w') comFile.close() os.rename(tempName, finalName) This is now atomic as far as anything watching targetDir is concerned. In other words as soon as it can be seen in the directory it is safe to be read and destroyed with out having to worry about another process not having closed the file for what ever reason. I do have two problems with this though; 1. This may fail under windows if another file already exists with this file name in the target directory. I always try to get my code working on Linux and windows, this leaves my code more robust and interestingly sometimes the Linux interpreter picks up different errors than the windows interpreter and visa versa. 2. It doesn't look very nice! I'm assuming there must be something in python to create a and release a file on the system in one line of code? Thank in advance of any help. Cheers, Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about *args and functions
Greetings, You could default it to None and check in your script to see if it has changed. def some_function(req_var, req_var2, un_req_var=None): if un_req_var != None: dosomething else: dosomethingelse Wesley Brooks. On 26/01/07, shawn bright <[EMAIL PROTECTED]> wrote: > lo there all, > > if i have a function that sometimes needs a value passed to it and sometimes > not, is this where i use *args ? > > like this > > def some_function(req_var, req_var2, un_req_var): > do some stuff > return value > > how would i use this if sometimes i need to process un_req_var and sometimes > not ? > > thanks > > ___ > 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] Inheriting Classes and __init__
Thanks again, that is a great help. Wesley Brooks On 26/01/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Wesley Brooks wrote: > > Dear Users, > > > > I would like a class to inherit the methods from wxVTKRenderWindow, > > but to add a few lines of code to __init__ . I would prefer not to > > copy the whole init method from the inherited class into the > > inheriting class. What is the best approach for this? I guess that if > > I have an init in the inheriting class it would overide the init in > > the inherited class? > > Yes, your __init__() will override the base class __init__(). To include > the base class functionality, just call the base class __init__() from > your __init__(). The syntax for this is a little different from the > usual method call; in your __init__() include this call: >wxVTKRenderWindow.__init__(self, args) > > where args is whatever argument list you want to pass to the base class > __init__(). > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Inheriting Classes and __init__
Dear Users, I would like a class to inherit the methods from wxVTKRenderWindow, but to add a few lines of code to __init__ . I would prefer not to copy the whole init method from the inherited class into the inheriting class. What is the best approach for this? I guess that if I have an init in the inheriting class it would overide the init in the inherited class? Yours faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global values & import scope
Thanks for your help I tested what you two said as follows and it worked great. Thank you. (Bellow in file TEST_ClassID.py) class AssemblyItem: itemID = 0 def __init__(self): self.ID = "assemblyItem" + str(AssemblyItem.itemID) AssemblyItem.itemID += 1 def ReturnID(self): return self.ID (Bellow in file TEST_ImportID1.py) from TEST_ClassID import AssemblyItem class Parent1: def __init__(self): self.testList = [] def PrintID(self): self.testList.append(AssemblyItem()) print self.testList[-1].ReturnID() (Bellow in file TEST_ImportID2.py) from TEST_ClassID import AssemblyItem class Parent2: def __init__(self): self.testList = [] def PrintID(self): self.testList.append(AssemblyItem()) print self.testList[-1].ReturnID() (Bellow, the commands run in the python terminal in the same directory) >>> from TEST_ClassID1 import Parent1 >>>from TEST_ClassID2 import Parent2 >>>a = Parent1() >>>b = Parent2() >>>a.PrintID() assemblyItem0 >>>a.PrintID() assemblyItem1 >>>b.PrintID() assemblyItem2 >>>b.PrintID() assemblyItem3 >>>a.PrintID() assemblyItem4 >>>b.PrintID() assemblyItem5 Thanks again for your help. Wesley Brooks. On 24/01/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Wesley Brooks wrote: > > Dear Users, > > > > I'm using global values to create a unique ID, or name for each > > instance of a class. If I import the following in one file and test it > > it works fine. If the following class was imported in two different > > files run by the same program would each instance of the class have a > > unique name, or would they only be unique within the scope of the file > > which contains the import of the bellow class? > > > > itemID = 0 > > class AssemblyItem: > > def __init__(self): > > global itemID > > self.ID = "assemblyItem" + str(itemID) > > itemID += 1 > > That will work fine. When a module is imported twice, the second import > received a cached copy of the same module; the module is only > instantiated once. The variable itemID will just exist in one place, in > the single instance of the module, and AssemblyItems created from > different clients will all share the same counter. > > Kent > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Global values & import scope
Dear Users, I'm using global values to create a unique ID, or name for each instance of a class. If I import the following in one file and test it it works fine. If the following class was imported in two different files run by the same program would each instance of the class have a unique name, or would they only be unique within the scope of the file which contains the import of the bellow class? itemID = 0 class AssemblyItem: def __init__(self): global itemID self.ID = "assemblyItem" + str(itemID) itemID += 1 Thanks for any help, Yours Faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the key for a value in a dictionary.
Cheers for the reply. I'm creating a custom dictionary that I can use to store list of unique objects used in a GUI. Items are added then a unique string is returned. I have used this approach so if an item is deleted from the storage dictionary I can still find it using the key, where as if I had used a list I would have to update all references to an object if an object before it in the list was deleted as it's index would change. Wesley. On 11/01/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Wesley Brooks wrote: > > Dear Users, > > > > I'm trying to find the key of a unique value within a dictionary. Is > > the code bellow a safe way of doing so, or is there a better way of > > doing it? > > > > a = {'de':'df', 'gf':'hg'} > > key = a.keys()[a.values().index('hg')] > > This is safe, as long as the dict is not being modified (by another > thread, presumably) while this is going on - the docs for dict > explicitly guarantee that the order of items in a.keys() and a.values() > will correspond as long as a doesn't change. > > Whether it is a good solution or not, I don't know. It sounds like your > dictionary is backwards, maybe, if you are looking up by value. > > Kent > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding the key for a value in a dictionary.
Dear Users, I'm trying to find the key of a unique value within a dictionary. Is the code bellow a safe way of doing so, or is there a better way of doing it? a = {'de':'df', 'gf':'hg'} key = a.keys()[a.values().index('hg')] Thanks for your help, Yours Faithfully, Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] User identification and running in the background.
Cheers, I'll consider that. So the client would effectively hand shake with the lower level program and be supplied with a list of permissions which the user has access to. You mentioned about many systems being multi-user. When the client attempts to connect to the lower machine is it a trivial issue to either supply information on what user the attempt is coming from within the initial communication, or for the low level program to identify where/who the request is coming from? Thanks, Wesley Brooks. On 13/12/06, Tor Hildrum <[EMAIL PROTECTED]> wrote: > On 12/12/06, Tim Golden <[EMAIL PROTECTED]> wrote: > > > But this is all quite Win32-specific (as well as > > being hand-wavingly unspecific). I don't know > > how you'd go about it on *nix but I bet it's nothing > > like the same. > > The same general principle applies. You need to get a > UID or similar from a specific user, or you have to > check all connected TTYs and just pick a random user > out of the users logged in. Most systems today are > multi-user so the notion of 'the user logged in' doesn't > make sense system-wide. > > I think the best way to solve this is to use a client-server > approach. Have a deamon/service run in the background, > and then have a client started at login that pings the server > and notifies it of your presence. > > Tor > ___ > 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] User identification and running in the background.
Cheers for the reply, I had feared as such! I didn't want to have to code two different apps (windows or linux), or at best have large block of code around a few cases base on the result of sys.platform. The system is based on Windows at the moment, but I would of liked to have produced a version on Linux for evaluation purposes. Thanks again, I'll look up the SID and Token you mentioned. Wesley Brooks On 12/12/06, Tim Golden <[EMAIL PROTECTED]> wrote: > | I've had a quick scan around and can't find a way to identify the user > | who is logged in on the machine while a script is running? I've seen a > | few mentions of it being possible using bits of the win32 library but > | I would have liked my software to be portable with no adjustments. > | > | How can I run a script in the background? I will be writing a > | (prototype) machine control interface and would like the users to be > | able to log out, but leave the script running. When the next user logs > | in they can open up a portal (preferably in the system tray) to give > | them control of the system again. When I link this to the user > | identification I would be able to vary the access to the machine > | depending on the access rights of the user. > > I very much doubt if even the rest of what you're > doing is going to be particularly portable, so I > wouldn't worry too much if the logged-on user bit > isn't either. It looks to me as though you're > working at O/S-specific level. Python doesn't > offer any particular abstraction over detached > processes etc. In Windows you'd have to use a Service, > in *nix a daemon (I think). > > To talk about possibilities on Windows which I know > better, it should be possible to have a service > running which can be messaged to by a desktop app > run from the system tray or elsewhere. When the > desktop app sends its signal to the service it could > send through the SID or Token of the logged on user > which the service could then use to authorise or > not. > > But this is all quite Win32-specific (as well as > being hand-wavingly unspecific). I don't know > how you'd go about it on *nix but I bet it's nothing > like the same. > > TJG > > > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] User identification and running in the background.
Good morning Users, I've had a quick scan around and can't find a way to identify the user who is logged in on the machine while a script is running? I've seen a few mentions of it being possible using bits of the win32 library but I would have liked my software to be portable with no adjustments. How can I run a script in the background? I will be writing a (prototype) machine control interface and would like the users to be able to log out, but leave the script running. When the next user logs in they can open up a portal (preferably in the system tray) to give them control of the system again. When I link this to the user identification I would be able to vary the access to the machine depending on the access rights of the user. Thank you in advance of any help. Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Efficient programming questions. Tuples vs Lists; Custom Objects vs Lists.
Dear Python-Tutor members,I'm currently in the middle of re-writing a program for my research. I've been using python for the past three years now, my first language since a brief exposure to qbasic ten years ago. There are a couple of things I'm not sure about which I'll need to clear up before I present my work, I hope you can either help me or point me to literature / web reference which can help. Most of these are issues relating to a mix of speed of execution for the code, and scripting best practice. Firstly tuples vs lists. I'm guessing that lists use more memory than tuples as they provide more functions? Are they also more CPU intensive to use? Currently if I'm not likely to add or remove Items I use a tuple (eg, a coordinate in 3D space), but when I do I prefer using a list. This leads on to another question: If you use an object many times, for instance a list, does the interpreter remember that each new object is a list and when a function is called on a list look at one section of memory which details the list functions, or for each new object does it dedicate a new section of memory to the functions of that object? Secondly, a similar question to the first. A list object is something which is in the standard python library. I guess in a CPython distribution that this is C/C++ code being called by the python interpreter when the list object is used? If so then this would imply that a list object would be significantly quicker/less memory to use than an equivalent object scripted in python. I'm currently using lists extensively to hold basic information within objects with additional functions in the script to return information about items within the list. My code would be a lot more elegant and easier to read if I used custom objects for some of these but I'm worried they would be much slower. Would it be appropriate to write a function that inherited the methods of the List function? Would the new object retain the speed and efficiency of the standard list object methods? Lastly why can't python be compiled? I understand that there are certain situations where it is preferable to leave the script readable or byte code interpreted such as when programs are updated frequently over the net, or are being distributed to computers with different operating systems. What about situations where speed is critical? Is CPython's interpreter effectively a C program that carries out C functions as requested in the script? If so why is it not possible to have a program that reads in the whole python script, translates it to C and compiles it? Is it simply that the C functions are compiled already so carrying out a complete compile would gain minimal increases in performance? Thank you for your time and help.Yours Faithfully,Wesley Brooks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor