Re: do as a keyword
I also started to ponder about the 'do something' if 'true' else 'do this', and pondered if perhaps this statement could do with the including of the keyword do. Python has support for this in versions = 2.5: a = range(0, 5) b = range(5, 8) min(a) if sum(a) sum(b) else min(b) 0 In prior versions, you can use the and/or trick: (sum(a) sum(b) and [min(a)] or [min(b)])[0] 0 -Tor Erik -- http://mail.python.org/mailman/listinfo/python-list
Simple eval
Hi, A while ago I asked a question on the list about a simple eval function, capable of eval'ing simple python constructs (tuples, dicts, lists, strings, numbers etc) in a secure manner: http://groups.google.com/group/comp.lang.python/browse_thread/thread/58a01273441d445f/ From the answers I got I chose to use simplejson... However, I was also pointed to a simple eval function by Fredrik Lundh: http://effbot.org/zone/simple-iterator-parser.htm. His solution, using module tokenize, was short and elegant. So I used his code as a starting point for simple evaluation of dicts, tuples, lists, strings, unicode strings, integers, floats, None, True, and False. I've included the code below, together with some basic tests, and profiling... On my computer (winXP, python 2.5), simple eval is about 5 times slower than builtin eval... Comments, speedups, improvements in general, etc are appreciated. As this is a contribution to the community I suggest that any improvements are posted in this thread... -Tor Erik Code (tested on 2.5, but should work for versions = 2.3): ''' Recursive evaluation of: tuples, lists, dicts, strings, unicode strings, ints, floats, True, False, and None ''' import cStringIO, tokenize, itertools KEYWORDS = {'None': None, 'False': False, 'True': True} def atom(next, token): if token[1] == '(': out = [] token = next() while token[1] != ')': out.append(atom(next, token)) token = next() if token[1] == ',': token = next() return tuple(out) elif token[1] == '[': out = [] token = next() while token[1] != ']': out.append(atom(next, token)) token = next() if token[1] == ',': token = next() return out elif token[1] == '{': out = {} token = next() while token[1] != '}': key = atom(next, token) next() # Skip key-value delimiter token = next() out[key] = atom(next, token) token = next() if token[1] == ',': token = next() return out elif token[1].startswith('u'): return token[1][2:-1].decode('unicode-escape') elif token[0] is tokenize.STRING: return token[1][1:-1].decode('string-escape') elif token[0] is tokenize.NUMBER: try: return int(token[1], 0) except ValueError: return float(token[1]) elif token[1] in KEYWORDS: return KEYWORDS[token[1]] raise SyntaxError('malformed expression (%r)¨' % token[1]) def simple_eval(source): src = cStringIO.StringIO(source).readline src = tokenize.generate_tokens(src) src = itertools.ifilter(lambda x: x[0] is not tokenize.NL, src) res = atom(src.next, src.next()) if src.next()[0] is not tokenize.ENDMARKER: raise SyntaxError(bogus data after expression) return res if __name__ == '__main__': expr = (1, 2.3, u'h\xf8h\n', 'h\xc3\xa6', ['a', 1], {'list': [], 'tuple': (), 'dict': {}}, False, True, None) rexpr = repr(expr) a = simple_eval(rexpr) b = eval(rexpr) assert a == b import timeit print timeit.Timer('eval(rexpr)', 'from __main__ import rexpr').repeat(number=1000) print timeit.Timer('simple_eval(rexpr)', 'from __main__ import rexpr, simple_eval').repeat(number=1000) -- http://mail.python.org/mailman/listinfo/python-list
Convert obejct string repr to actual object
Hi, I've tried locating some code that can recreate an object from it's string representation... The object in question is really a dictionary containing other dictionaries, lists, unicode strings, floats, ints, None, and booleans. I don't want to use eval, since I can't trust the source sending the object I'm sure someone must have had the same need and created code for it... Maybe Pypy has what I need??? Haven't looked though... Regards, Tor Erik PS: The string repr is created by a server outside of my control... -- http://mail.python.org/mailman/listinfo/python-list
Tapping into the access of an int instance
Hi, Does anyone know how to interrupt the lookup of an integer value? I know I need to subclass int, since builtin types can't be altered directly... Below is how far I've come... What I want is to tap into the access of instance i's value 1... class Int(int): def __init__(self, *a, **k): super(Int, self).__init__(self, *a, **k) i = Int(1) i 1 Regards, Tor Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: Just bought Python in a Nutshell
Python in a nutshell also comes in a second edition: http://www.oreilly.com/catalog/pythonian2/index.html. Here, many of the new features in Python 2.5 are included. I haven't read through the first the edition, but I can honestly say that reading through the second edition has made me a better programmer, not just a better Python programmer. I only wish I'd read through it earlier, which would have saved me a lot of agony:) -Tor Erik -- http://mail.python.org/mailman/listinfo/python-list
The reverse of encode('...', 'backslashreplace')
Hi, How can I transform b so that the assertion holds? I.e., how can I reverse the backslash-replaced encoding, while retaining the str-type? a = u'æ' b = a.encode('ascii', 'backslashreplace') b '\\xe6' assert isinstance(b, str) and b == 'æ' Traceback (most recent call last): File pyshell#59, line 1, in module assert isinstance(b, str) and b == 'æ' AssertionError Regards, tores -- http://mail.python.org/mailman/listinfo/python-list
How can I set the size of a window with tkinter?
Hi I create a canvas that is to big for the default window-size, so it gets cut to fit... How can I increase the window-size to make sure the canvas fits? regards tores -- http://mail.python.org/mailman/listinfo/python-list
using variable-value
Hi In php I can assign a value to a variable and use this varaible to access a property in some object: $var = 'property'; $object-{$var} This will transelate to $object-property... Is this possible in Python? # Prints help on methods in Canvas-instance for method in dir(self.canvas): print method print help(self.canvas.method) gives me AttributeError: Canvas instance has no attribute 'method' ... regards tores -- http://mail.python.org/mailman/listinfo/python-list
Socket options
Hi For an online game I'm developing I need some advice concerning tcp-sockets, and especially which socket options to set and not. What I want is a connection where nothing is buffered (but are sent immediatly), and I also want to keep the connections persistent until explicitly closed. The server-side socket will receive multiple incomming requests from clients... regards tores -- http://mail.python.org/mailman/listinfo/python-list
logging to two files
Hi Have the following code: import logging logging.basicConfig(level = logging.DEBUG, format = '[%(levelname)-8s %(asctime)s] %(message)s', filename = 'rfs.log', filemode = 'w') When using logging.(debug, info etc) stuff is logged to rfs.log. How may I specify another log with different charateristics, such as a different file regards -- http://mail.python.org/mailman/listinfo/python-list
EOF-file missing
Hi From a client I read a file into a string using read(). On the server-side (it's a HTTPServer) i access the same string through the input stream rfile. However all useful read-methods (readlines, readline, read) expect an EOF before terminating. And for some reason the stream doesn't have the seek method either, so it's impossible to set the file-pointer to the end of the stream. how can I access the whole string then? Is it possible to add an EOF to the string before sending it from the client? Or maybe there are other solutions? regards -- http://mail.python.org/mailman/listinfo/python-list
select random entry from dictionary
Hi How can I select a random entry from a dictionary, regardless of its key-values? regards tores -- http://mail.python.org/mailman/listinfo/python-list
Delete first line from file
Hi How can I read the first line of a file and then delete this line, so that line 2 is line 1 on next read? regards -- http://mail.python.org/mailman/listinfo/python-list
kill a process in XP
Hi. From my Python-program I spawn a new process. When using P_NOWAIT spawnl returns the pid but in windows it returns a process handle. Later I want to kill this process. How can I do this when I only have the process handle? -tores- -- http://mail.python.org/mailman/listinfo/python-list