Re: [Tutor] Listing available variables
On 12/25/2009 6:50 PM, Mkhanyisi Madlavana wrote: How do I list all the available variables in python. for example if I say: a = range(10) b = 16 c = (some variables) z = [this,that,none] I then need a command that will list the variables I assigned like: some_command a, b, c, ... (some variables), z dir() a = range(10) b = 16 c = z = [this,that,none] dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b', 'c', 'z'] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python and kiviat diagrams
Hi all, Thanks for your insightful answers, and a merry Christmas + a happy new year! Btw, somebody on the list mentioned rpy as an alternative way to create spider charts. I also think that's a better route to take. R is thoroughly tested and built for the job, and if you ever need more statistical/plotting things, you could easily extend your program. Cheers!! Albert-Jan ~~ In the face of ambiguity, refuse the temptation to guess. ~~ --- On Thu, 12/24/09, Kent Johnson ken...@tds.net wrote: From: Kent Johnson ken...@tds.net Subject: Re: [Tutor] python and kiviat diagrams To: Albert-Jan Roskam fo...@yahoo.com Cc: dwbarne dwba...@earthlink.net, python tutor tutor@python.org Date: Thursday, December 24, 2009, 2:19 PM On Wed, Dec 23, 2009 at 5:27 PM, Albert-Jan Roskam fo...@yahoo.com wrote: I was studying the code on http://matplotlib.sourceforge.net/examples/api/radar_chart.html. Isn't it very unusual that a class is defined within a function? Unusual, but not un-heard of. Usually the function is a factory function that returns the class to the caller. In this case the class is registered as the handler for projections of type 'radar'. Presumably RadarAxes is implementing a protocol (interface) that is required by register_projection(). Why not use a class instance inside the function instead? Presumably register_projection() requires a class (strictly speaking, it probably requires a callable that returns an instance of a class that implements the required protocol). There don't seem to be any docs for register_projection() so it's hard to know for sure what it wants. No methods of the class can currently be inherited outside the scope of the function, right? Do you mean, the class cannot be subclassed? Not easily, only because the function doesn't return the class. There is no inherent reason this class could not be subclassed if a reference to the class were available. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Listing available variables
This may also be useful: a = 1 b = 2 c = 3 locals() {'a': 1, 'c': 3, 'b': 2, '__builtins__': module '__builtin__' (built-in), '__name__': '__main__', '__doc__': None} locals().keys() ['a', 'c', 'b', '__builtins__', '__name__', '__doc__'] Cheers!! Albert-Jan ~~ In the face of ambiguity, refuse the temptation to guess. ~~ --- On Fri, 12/25/09, Lie Ryan lie.1...@gmail.com wrote: From: Lie Ryan lie.1...@gmail.com Subject: Re: [Tutor] Listing available variables To: tutor@python.org Date: Friday, December 25, 2009, 9:16 AM On 12/25/2009 6:50 PM, Mkhanyisi Madlavana wrote: How do I list all the available variables in python. for example if I say: a = range(10) b = 16 c = (some variables) z = [this,that,none] I then need a command that will list the variables I assigned like: some_command a, b, c, ... (some variables), z dir() a = range(10) b = 16 c = z = [this,that,none] dir() ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b', 'c', 'z'] ___ Tutor maillist - Tutor@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
[Tutor] interactive mode questions
I'm working my way through Mr Lutz's Learning Python, and I come to this snippet (page 271): while True: reply = input('Enter text:') if reply == 'stop': break print(reply.upper()) which works as advertised in an interactive session, but not in a script. Yes, I tried tossing the script to both versions of interpreter, it doesn't work with either 2.6 or 3.1. text given as input results in NameError: name 'text' is not defined. numerical input results in AttributeError: 'int' object has no attribute 'upper' either way, enclosing the input in quotes works. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactive mode questions
Op 25-12-09 17:49, rick schreef: I'm working my way through Mr Lutz's Learning Python, and I come to this snippet (page 271): while True: reply = input('Enter text:') Try this: reply = raw_input('Enter text: ') Cheers, Timo if reply == 'stop': break print(reply.upper()) which works as advertised in an interactive session, but not in a script. Yes, I tried tossing the script to both versions of interpreter, it doesn't work with either 2.6 or 3.1. text given as input results in NameError: name 'text' is not defined. numerical input results in AttributeError: 'int' object has no attribute 'upper' either way, enclosing the input in quotes works. ___ Tutor maillist - Tutor@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
[Tutor] unicode ordinals to/from utf8
Special offer for coders coding on Christmas day! I'm looking for the simplest way to decode/encode unicode ordinals (called 'codes' below) to/from utf8. Find this rather tricky, esp because of variable number of meaningful bits in first octet. Specifically, for encoding, is there a way to avoid paasing through binary (and back)? Below what I have so far (test by converting to utf8 back ;-). Denis la vita e estrany http://spir.wikidot.com/ = # coding: utf8 import sys ; end = sys.exit sizes_to_values = {2:192, 3:224, 4:240} def ordinalFromUtf8(s): n = len(s) byte0 = ord(s[0]) # case ASCII if n == 1: return byte0 # case else # get actual value for byte #0 value0 = byte0 - sizes_to_values[n] ordinal = value0 * 64**(n-1) # compute other bytes for i in range(1,n): byte = ord(s[i]) value = byte - 128 weight = 64**(n-i-1) ordinal = ordinal + (byte - 128) * 64**(n-i-1) return ordinal def ordinalToUtf8(o): # case ASCII if o 128 : return chr(o) # case else # split into octets, # each holding '10' 6 meaningful bits binary = bin(o)[2:] octets = list() while len(binary) 6: octet = '10' + binary[-6:] octets.insert(0, octet) binary = binary[:-6] # first octet can have 3 to 5 free bits, # depending on overall length bit_count = 6 - len(octets) rest_bit_count = len(binary) if rest_bit_count bit_count: octet = '10' + '0' * (6 - rest_bit_count) + binary octets.insert(0, octet) binary = binary[:-6] zero_count = 7 - len(octets) - len(binary) octet = '1' * (len(octets)+1) + '0' * zero_count + binary octets.insert(0, octet) # convert to ordinals -- chars -- string ordinals = [int(bits,2) for bits in octets] chars = [chr(o) for o in ordinals] return ''.join(chars) def test(): def ue(u): return unicode.encode(u, 'utf8') # ASCII, latin, BMP, BMP chars = ['\n','\t',' ','A','a','~', ue(u'\u00a0'),'£','µ','¿','À','é','ÿ', ue(u'\u0100'),'€',ue(u'\u1234'),ue(u'\u'), ue(u'\U0001'),ue(u'\U000f')] for char in chars: o = ordinalFromUtf8(char) s = ordinalToUtf8(o) print char,repr(char), --, o,'=',hex(o),--, s,repr(s) test() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Error writing to file...
In writing the following program in creating random numbers and writing them to the file, I get an type error in writing to file. I have tried number = random(10,99), number = randint(10.99), and number = random.random(10,00) and still get various errors of writing to file. If I were to REM out the file.write(number) and file.write('\n') lines, the program run fine. Do I need to convert a numeric random number to a string number? TIA, Ken PROGRAM: import random print (First Group - Write) file = open(Numbers.txt,w) for i in range(1,10): number = random.randint(10,99) print i, number file.write(number) file.write('\n') file.close() ERROR MESSAGE: Traceback (most recent call last): File /home/ken/Python 262/random.py, line 8, in module file.write(number) TypeError: argument 1 must be string or read-only character buffer, not int ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...
Thinking it was a reply to me on Python Tutor, I translated the following into English for the board. Ken � DIAGORN wrote: Bonjour, Je suis absente jusqu'au 03/01/10 inclus. En cas d'urgence Soprane, contacter notre adresse générique projet.sopr...@teamlog.com. Joyeuses fêtes de fin d'année. Cordialement. Geneviève Hello, I am leaves to THE 03/01/10 include. In case of urgency Soprane, contact our generic address projet.sopr...@teamlog.com. Joyous end of year holidays. Cordially. Geneviève ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...(SOLVED)
Thanks! So a file will only take a numeric as a string? Lesson learned. Again, thanks. Ken Amit Sethi wrote: It is as the Error says a type error , the function takes a string and u are passing an int if you put file.write(str(number)) you will not get error .. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...
Ken G. beachkid at insightbb.com writes: [...] Do I need to convert a numeric random number to a string number? [...] Yes, as long as you open the file as w you need to use repr() [repr(int)]. If you want to save the integer, you need to open a file as wb, write binary. Check your documentation, both wb and pickle - I'm pretty new to Python, so I won't try to advise you on the read-only character buffer mentioned in the error message, but also look up bytes objects - they may work as long as your integer range is in range(255). Hope this helps, Gil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...
On 12/25/09 15:00, Ken G. wrote: In writing the following program in creating random numbers and writing them to the file, I get an type error in writing to file. I have tried number = random(10,99), number = randint(10.99), and number = random.random(10,00) and still get various errors of writing to file. If I were to REM out the file.write(number) and file.write('\n') lines, the program run fine. Do I need to convert a numeric random number to a string number? TIA, Ken PROGRAM: import random print (First Group - Write) file = open(Numbers.txt,w) for i in range(1,10): number = random.randint(10,99) print i, number file.write(number) file.write('\n') file.close() ERROR MESSAGE: Traceback (most recent call last): File /home/ken/Python 262/random.py, line 8, in module file.write(number) TypeError: argument 1 must be string or read-only character buffer, not int Hi Ken, From the docs if you are using 2.6 [snip] To write something other than a string, it needs to be converted to a string first: value = ('the answer', 42) s = str(value) f.write(s) http://docs.python.org/tutorial/inputoutput.html -- David Abbott (dabbott) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactive mode questions
rick rdo...@cogeco.ca wrote while True: reply = input('Enter text:') if reply == 'stop': break print(reply.upper()) which works as advertised in an interactive session, but not in a script. Yes, I tried tossing the script to both versions of interpreter, it doesn't work with either 2.6 or 3.1. Somehow you are picking up an older v2 interpreter. How are you running the script? From within IDLE? Or from an OS command? If the latter try using the full path to the v3 Python interpreter. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...
Ken G. beach...@insightbb.com wrote the program run fine. Do I need to convert a numeric random number to a string number? You need to convert your data to a string if you use a text file, which is the default. If you open the file with 'wb' you can write any kind of data to it, but you will have to decode it when you read it back. Its usually easier to use a text file and convert to a string when writing. import random print (First Group - Write) file = open(Numbers.txt,w) The fact you use 'w' here tells Python you want to write text. for i in range(1,10): number = random.randint(10,99) print i, number file.write(number) file.write('\n') file.close() ERROR MESSAGE: Traceback (most recent call last): File /home/ken/Python 262/random.py, line 8, in module file.write(number) TypeError: argument 1 must be string or read-only character buffer, not int But, as the error says, you are passing an int. If you really want to use a binary file see the File Handling topic in my tutor for an example. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] oo design/interaction quandary
Hi all, I'm having a design issue that's really bothering me. The code I'm writing is fairly large by now, but I've written what I think is a decent example that illustrates my problem. My app launches threads that each consume messages from a queue, send them to a processor object, and then the processor needs to return the message to the main thread -- if the processing was successful -- and then the main thread puts the message into a different queue. Here's a shortened version of my code. class Processor(object): def __init__(self): self.qhost = 'localhost' self.qport = '5672' self.uname = 'guest' self.pwd = 'guest' self.ssl = false self.vhost = '/' self.exch_name = 'fooX' self.exch_type = 'direct' self.queue_name = 'fooQ' self.conn = amqp.Connection(userid=self.uname, password=self.pwd, host=self.qhost, virtual_host=self.vhost, ssl=self.ssl) self.chan = self.conn.channel() self.chan.exchange_declare(self.exch_name, type=self.exch_type) self.chan.queue_declare(self.qname) self.chan.queue_bind(self.qname, self.exch_name) def consume(self, callback): self.chan.basic_consume(self.qname, callback=callback) while True: self.chan.wait() class Munger(object): def munge(self,msg): if msg % 2 == 0: yield msg class Sender(object): def run(self): p = Processor() m = Munger() for msg in p.consume(m.munge): I know this doesn't work right now. This piece of the code should send 'msg' to another queue. pass if __name__ == '__main__': s = Sender() s.run() The problem might be obvious to you, but I'll quickly explain: The Sender object (a thread in the real code), is calling p.consume, which just wraps the basic_consume method in py-amqplib. The basic_consume method registers a consumer and a callback with the amqp server. The chan.wait() call blocks and waits for messages. When the messages arrive they are passed to the python callable we passed to the basic_consume method. Therein lies the problem. Messages go from my Processor object, to the Munger object, and this is all initiated by the Sender object, but I can't find a clean way to get messages successfully processed by Munger back to Sender, so that Sender can requeue the message to the new queue. I've thought about having a Queue object in Sender, or maybe registering Sender as an observer of (at different times) the Munger or Processor objects, but I'd like this to be as simple and understandable as possible by other developers, because I'm wanting to make the Processor and Munger objects pluggable (so the Processor can support different queuing protocols, Munger can do literally anything... etc). Ideas welcome. If I've failed to explain some aspect of my issue, give me a poke and I'll expand as best I can. brian Brian K. Jones Python Magazine http://www.pythonmagazine.com My Blog http://www.protocolostomy.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error writing to file...
The docs say write( str) - Write a string to the file. Only a string. Regardless of mode. Mode mostly affects interpretation of line ends. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] oo design/interaction quandary
On Fri, Dec 25, 2009 at 9:03 PM, Brian Jones bkjo...@gmail.com wrote: Hi all, I'm having a design issue that's really bothering me. The code I'm writing is fairly large by now, but I've written what I think is a decent example that illustrates my problem. My app launches threads that each consume messages from a queue, send them to a processor object, and then the processor needs to return the message to the main thread -- if the processing was successful -- and then the main thread puts the message into a different queue. Here's a shortened version of my code. class Processor(object): def __init__(self): self.qhost = 'localhost' self.qport = '5672' self.uname = 'guest' self.pwd = 'guest' self.ssl = false self.vhost = '/' self.exch_name = 'fooX' self.exch_type = 'direct' self.queue_name = 'fooQ' self.conn = amqp.Connection(userid=self.uname, password=self.pwd, host=self.qhost, virtual_host=self.vhost, ssl=self.ssl) self.chan = self.conn.channel() self.chan.exchange_declare(self.exch_name, type=self.exch_type) self.chan.queue_declare(self.qname) self.chan.queue_bind(self.qname, self.exch_name) def consume(self, callback): self.chan.basic_consume(self.qname, callback=callback) while True: self.chan.wait() class Munger(object): def munge(self,msg): if msg % 2 == 0: yield msg Why is this a generator function? From what I understand looking at channel.py in py-amqplib this should just be a callable that processes the message. If you want to notify the Sender that the message has been processed, I would either make another Queue to pass messages back, or give the Munger a callback function to pass successful messages to. The difference between them is that a Queue is asynchronous and you would have to process the output in another thread; a callback is synchronous and will run in the same thread as the munger. Either of these can be handled in a base class leaving subclasses to just implement the message handling. For example, using a callback (a Queue would be similar): class MungerBase(object): def __init__(self, callback): self.callback = callback def munge(self, msg): if self.process(msg): self.callback(msg) A real munger looks like this: class Munger(MungerBase): def process(self, msg): if msg % 2 == 0: return True return False class Sender(object): def run(self): p = Processor() m = Munger() for msg in p.consume(m.munge): I know this doesn't work right now. This piece of the code should send 'msg' to another queue. pass This would look like class Sender(object): def run(self): p = Processor() m = Munger(self.handle_processed_message) p.consume(m.munge) def handle_processed_message(self, msg): # send 'msg' to another queue or whatever Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] interactive questions
On Sat, 2009-12-26 at 03:03 +0100, tutor-requ...@python.org wrote: which works as advertised in an interactive session, but not in a script. Yes, I tried tossing the script to both versions of interpreter, it doesn't work with either 2.6 or 3.1. Somehow you are picking up an older v2 interpreter. How are you running the script? From within IDLE? Or from an OS command? If the latter try using the full path to the v3 Python interpreter. HTH, Hi Alan, from within geany. The first line is either #!/usr/bin/python or #!/usr/bin/python3 r...@rick-desktop:~$ file /usr/bin/python /usr/bin/python: symbolic link to `python2.6' r...@rick-desktop:~$ file /usr/bin/python3 /usr/bin/python3: symbolic link to `python3.1' I just think it odd that there is one behaviour in an interactive session, and a different behaviour when run from a script. interesting again, running it right from bash, it works just fine, as long as the first line calls v3.1. Could geany be calling the 2.6 interpreter, even with v3 in the first line? oh my, that is unexpected, just tried it. #!/usr/bin/python3 import sys print(sys.version) from geany yields: 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] but from bash yields: 3.1.1+ (r311:74480, Nov 2 2009, 15:45:00) [GCC 4.4.1] Rick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor