Re: multi split function taking delimiter list
On Nov 14, 7:56 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I'm looking for something like: multi_split( 'a:=b+c' , [':=','+'] ) returning: ['a', ':=', 'b', '+', 'c'] whats the python way to achieve this, preferably without regexp? pyparsing http://pyparsing.wikispaces.com/ is quite a cool package for doing this sort of thing. Using your example: #untested from pyparsing import * splitat = Or(:=, +) lexeme = Word(alphas) grammar = splitat | lexeme grammar.parseString(a:=b+c) #returns (the equivalent of) ['a', ':=', 'b', '+', 'c']. --Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Specify string with uniform indentation ignored
tobiah wrote: Like a docstring, I would like to specify a string such as: def thing: string = function otherlang(){ doit() } And have the string end up actually being defined as: function otherlang(){ doit() } Is there a built in way to do this? I don't much care for: string = function otherlang(){ string += doit() string += } textwrap.dedent ought to do exactly what you want. --Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting value of an int-derived class
Ken Schutte wrote: So, that's good. But, how can I change the value of x from 5 to something else, without creating a new instance? I suppose I could create a function that creates a new foo and copies its attributes, but is there a more direct way? Is the value 5 stored in some special attribute I can just directly modify? In short, no. In long, ints (and longs, for that matter) are immutable types implemented in a way that Python can't peek at their internals easily, and so are very resistant to mutability. Imagine the results if you mutated 5 to 6 or similar; in fact, you don't want regular numbers to change without some serious hackage. As for subclasses, a similar thing holds: Python programs can't see the internal details. Subclasses just forward the method calls like __add__, __xor__ etc (providing they're not overriden) to the int class, which in turn pokes around at the C level and returns an answer. What you probably want is a proxy class, that forwards all number methods to a wrapped int, and also has a means of setting the wrapped int. A minimal untested implementation: class IntWrapper(object): def __init__(self, num): self.num = num def __getattr__(self, attr): if attr == 'num': return object.__getattr__(self, 'num') return getattr(self.num, attr) Of course, this isn't actually what you asked for, a subclass of int. But, bar hacking on the C level, which is possible but a bit extreme, this is the closest thing to a mutable number. But, personally, I happen to like the memory-wastetastic, new-instance-returning but functionally purer style. It tends to lead to less irreplicable bizarre bugs because of objects seemingley semi-randomly changing state, and Python's garbage collection systems are fairly good at picking up unused objects. ;) --Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding style and else statements
Bruno Desthuilliers wrote: foo = lambda thing: thing and thing + 1 or -1 The and ... or trick is buggy (what if thing == -1?) and bad style. If you -do- want a conditional expression, 2.5 provides one: thing + 1 if thing else -1 No subtle logical bugs, and a good deal more obvious. On the topic of the original posting, I personally prefer the latter (no else clause), because too deep a level of indentation is not a Good Thing. However, if a redundant else: would make the code clearer somehow, by all means use one, because this is more a matter of personal taste than anything. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting started, .py file
python -i source_file.py will do what you want. -Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Spelling mistakes!
[EMAIL PROTECTED] wrote: In fact, googling for referer and referrer reports a similar number of hits, unlike most misspellings. Terry You know, I almost mentioned that myself. Drives me crazy. Me too. I'm one of those people who, for better or worse, is a good speller. Words just look right or wrong to me and it bothers me when they look wrong. What's worse is the closely related problem of British/American English, though you sort of get used to it after typing s/colour/color/g or s/serialise/serialize/g for the thousandth time. The words look wrong to me, but they're correct in the context. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex anomaly
Would this particular inconsistency be candidate for change in Py3k? Seems to me the pos and endpos arguments are redundant with slicing, and the re.match function would benefit from having the same arguments as pattern.match. Of course, this is a backwards-incompatible change; that's why I suggested Py3k. -- http://mail.python.org/mailman/listinfo/python-list
Re: Line replace
Hello I need some help I have a text file which changes dynamically and has 200-1800 lines. I need to replace a line , this line can be located via a text marker like : somelines # THIS IS MY MARKER This is the line to be replaced somemorelines My question is how to do this in place without a temporary file , so that the line after the marker is being replaced with mynewlinetext. Thanks Nx You will either have to read the whole file into memory (at 1800 lines, this shouldn't be too bad) or read piecementally from the input file, write the processed output to a new file, delete the input file and rename the new file to the original file (yes, that's using a temporary file, but it'll be more memory friendly). The first solution would look something like this: #Untested import sre input_file = file('/your/path/here') input_file_content = input_file.read() input_file.close() pat = sre.compile(r'^#THIS IS MY MARKER\n.*$') mat = pat.search(input_file_content) while mat: input_file_content = pat.sub('New text goes here', input_file_content) mat = pat.search(input_file_content) file('/your/path/here', 'w').write(input_file_content) The second one might be cleaner to do using a shell script (assuming you're on a *nix) - awk or sed are perfect for this type of job - but the python solution will look like this: #Untested import os input_file = file('/your/path/goes/here') output_file = file('/tmp/temp_python_file', 'w') marked = False for line in input_file: if line == '#THIS IS MY MARKER': marked = True elif marked: output_file.write('New line goes here\n') else: output_file.write(line) input_file.close() os.system('rm /your/path/goes/here') os.system('mv /tmp/temp_python_file /your/path/goes/here') -- http://mail.python.org/mailman/listinfo/python-list
Re: loops breaks and returns
rbt wrote: Is it more appropriate to do this: while 1: if x: return x Or this: while 1: if x: break return x Or, does it matter? I would pick the first form if that's the only place where x would be returned from the function. However, if there would be redundant 'return x'-es in the function because of this, then the second form becomes preferable. It's not set in stone, though - if you have a compelling reason to break the rule-of-thumb, do so. -- http://mail.python.org/mailman/listinfo/python-list
Re: problems binding a dictionary
You're not 'exploding' the dict to the param1='blah' etc form - you-re actually passing it in as a single dict object. To solve this, add a ** to the front of a dict you want to explode in a function, just as you'd add a * to explode a sequence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Checking length of each argument - seems like I'm fighting Python
It depends what you mean by 'scalar'. If you mean in the Perlish sense (ie, numbers, strings and references), then that's really the only way to do it in Python - there's no such thing as 'scalar context' or anything - a list is an object just as much as a number is. So, assuming you want a Things object to break if either a) all three arguments aren't sequences of the same length, or b) all three arguments aren't a number (or string, or whatever), this should work: #Not tested. class Things(object): def __init__(self, x, y, z): try: if not (len(x) == len(y) and len(y) == len(z)): raise ValueError('Things don't match up.') except TypeError: #one of x, y or z doesn't do __len__ #check if they're all ints, then. if not (isinstance(x, int) and isinstance(y, int) and isinstance(z, int)): raise ValuError('Things don't match up') #do stuff. Personally, I find nothing wrong with having a separate Thing object that can do validation for itself, and I think it's a pleasantly object oriented solution I'm also wondering why something like this could accept something other than sequences if it depends on their length. If you just want to treat non-sequences as lists with one value, then something like this is more appropriate, and might lead to less redundancy in other places: def listify(obj): try: return list(obj) except TypeError return [obj] class Things(object): def __init__(self, *args): x, y, z = [listify(arg) for arg in args] if not (len(x) == len(y) and len(y) == len(z)): raise ValueError('Things don't match up') -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp non-greedy matching bug?
My understanding of .*? and its ilk is that they will match as little as is possible for the rest of the pattern to match, like .* will match as much as possible. In the first instance, the first (.*?) did not have to match anything, because all of the rest of the pattern can be matched 0 or more times. I think that such a situation (non-greedy operator followed by operators that match 0 or more times) will never match. However, in the second instance, it has to match something later on in the string, so it will capture something. I believe that this is an operator precedence problem (greedy ? losing to .*?), but is to be expected. So, if this is the case, by all means it should be added in a note to the docs. However, I am not a regular expression expert, so my analysis of the situation may be well off the mark. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to do new_variable = (variable) ? True : False; (php) on python?
Daniel Crespo wrote: Hello to all, How can I do new_variable = (variable) ? True : False; in Python in one line? I want to do something like this: dic = {'item1': (variable) ? True-part : False-part} Any suggestions? Daniel There's a trick using the short-circuiting boolean logic operators to emulate the ternary operator in Python. Basically, you do TEST and TRUE_PART or FALSE_PART However, this fails if TRUE_PART evaluates to a False value; you end up with FALSE_PART's value instead. This is a trick/hack, though, and shouldn't really be used much - use an if statement instead, or wait til 2.5 when an if expression is coming in. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multikey Dict?
If I could just say to Python: john and graham (and ...) are all a part of a superdict and either their id or their name can be used as keys. Can I do that somehow? Sure you can. There are two obvious ways to do this - enlist the aid of a Superdict (or similar) class to take care of the details. A simple implementation would be: class Superdict(object): def __init__(self, by_id, by_name): self.by_id = by_id self.by_name = by_name def __getitem__(self, value): if value.isdigit(): return self.by_id[value] else: return self.by_name[value] The alternative is to use some sort of database for storing these values. It doesn't really matter which (hell, you could even reinvent a relational wheel pretty simply in Python), as any DB worth its salt will do exactly what you need. Hope that helps, -Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing Modules
On the second point, a combination of sys.path, os.listdir and __import__ should do what you're after, although sifting through the whole of sys.path and subfolders from Python, rather than the interpreter itself, could be slow. (And it'll be redundant as well - __import__ will have do the same thing, though you could fix that by using the imp module). -Should- work, but not tested, so don't blame me if it doesn't: import sys, os, re def find_modules(str_pat): pat = re.compile(str_pat + '.py[co]?') init_pat = re.compile('__init__.py[co]?') for dir in sys.path: files = [n for n in os.listdir(path) if pat.search(n)] [__import__(name.rspit('.')) for name in files] for possible_dir in os.listdir(path): try: if True in [init_pat.match(n) for n in os.listdir(name + '/' + possible_dir): find_modules(str_pat) except OSError: #does os.listdir raise this? pass -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickling and unpickling inherited attributes
The reason the state of obj.A and obj.B aren't preserved is because your __getstate__ and __setstate__ don't preserve them - they only save obj.C, and you don't make a call to the parent class's respective methods. Here's what I mean: import pickle class Child(Parent): __slots__=['C',] def __init__(self, c): self.C=c def __getstate__(self): return Parent.__getstate__(self) + (self.C) def __setstate__(self, tup): self.C = tup.pop() Parent.__setstate__(self, tup) obj = Child('foo') obj.A = 'bar' obj.B = 'baz' objct = pickle.loads(pickle.dumps(obj)) objct.A 'bar' objct.B 'baz' objct.C 'foo' -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickling and unpickling inherited attributes
Of course, in __setstate__, there should be a tup = list(tup) as well - sheer forgetfulness and a confusing name in one. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I sort these?
unzip doesn't seem to work for me... It's not a part of the standard Python distribution, but this is a naive implementation (it doesn't react well to the list's contents having different lengths). def unzip(seq): result = [[] for i in range(len(seq[0]))] for item in seq: for index in range(len(item)): result[index].append(item[index]) return result unzip(zip(range(5), 'abcde')) [[0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e']] -- http://mail.python.org/mailman/listinfo/python-list
Re: High Order Messages in Python
This can be suitably applied to Python with the use of Higher Order Functions, though. It's not quite the Ruby version because Python allows you to use functions as first-class objects, complicating the All-You-Can-Do-Is-Pass-A-Message philosophy. This is my 5-minute implementation: class HigherOrderList(list): def do(self, func): return HigherOrderList(each(self, func)) def where(self, pred): return HigherOrderList(mass_test(self, pred)) def mass_test(iterable, pred): for item in iterable: if pred(item): yield item def each(iterable, method): for item in iterable: yield method(item) -- http://mail.python.org/mailman/listinfo/python-list
Re: index and find
s = 'foobar' s.find('z') -1 s.index('z') Traceback (most recent call last): File pyshell#32, line 1, in -toplevel- s.index('z') ValueError: substring not found Pretty self explanatory. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling an exe from Python?
from subprocess import Popen proc = Popen('my_programme.exe') Use proc.communicate(input) to send input to stdin, and get a tuple of (stdout, stderr) back. If you need the returncode, use proc.poll() or proc.wait(), depending on if you want it to block or not. -- http://mail.python.org/mailman/listinfo/python-list
Re: wierd threading behavior
thread is a low-level threading module, and start_new is deprecated. Aside from that, thread.start_new(test.()) is syntaxically wrong (a pair of brackets can't follow a dot). However, your example does work for me once I fix the syntax, and it prints hello but then hangs. I can't explain the other results, though - possibly undefined behaviour or more likely me not having much experience with the low-level thread interface. Use threading instead, like so: import threading def test(): print 'Test successful!' def main(): thread = threading.Thread(target = test) thread.start() main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Works only in interactive mode
That looks like a different module named pcop getting in the way. If there's another pcop.py in the directory where you're running it as a script, then that gets priority and you'll end up with an error like the one you got. However, if you run it interactively, then that directory is not checked, or is (normally) checked lower-down than, say, Python's standard library. Try checking if help(pcop) and dir(pcop) are what you expect in the script, and looking at where sys.path is looking for scripts. -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you pronounce wxpython
I'd always assumed it was doubleyew-ecks python, but it could be wicks python, or similar. -- http://mail.python.org/mailman/listinfo/python-list
Re: Function decorator that caches function results
What about not storing args at all? Something like this: def cache_function(func, args_list): cache = {} def cached_result(*args, **kwargs): kwargs.update(dict(zip(args_list, args))) if kwargs in cache: return cache[kwargs] result = func(**kwargs) cache[kwargs] = result return result return cached_result args_list is a list of all the argument names, so that they can be converted into keyword arguments. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is self?
self is the class instance that the bound function being called belongs to. This example should illustrate a bit. class Foo(object): def __init__(self, value): self.value = value # so the Foo instance now has an attribute, value def get_value(self): return self.value # This gets the previously-set value attribute of the Foo instance bar = Foo(42) baz = Foo('101010') print bar.get_value() #Note that the self argument is implicit since this is a bound method. print print baz.get_value() The output is (or should be, as this is untested): 42 101010 -- http://mail.python.org/mailman/listinfo/python-list
Re: Redundant code in multiple methods
How about using a class, with __call__, as a wrapper instead of the function itself? class FunctionWrapper(object): def __init__(self, cls, function): self._function = function self._cls = cls def __call__(self, *args, **kwargs): REQUEST = self.REQUEST SESSION = REQUEST.SESSION dbConnection = self._cls.getDBConnection() logger = self._cls.getLogger() trackStatsHere() # set up some local variables here # change some global variables here try: return self._function(self._cls, *args, **kwargs) except: raise handle the error here finally: dbConnection.close() class User(object): def __init__(self): def View(cls, self, localvariables): #Needs the cls argument before self to take the FunctionWrapper first argument myHtmlDoc = make the htmldocument here using all of the previous variables # play with data here return myHtmlDoc self.View = FunctionWrapper(self, View) def Edit(cls, self): #Ditto myHtmlDoc = make the htmldocument here using all of the previous variables # play with data here return myHtmlDoc self.Edit = FunctionWrapper(self, Edit) #the rest of the class -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about consistency in python language
update updates the dictionary in place - it actually returns None, not the updated dict. However, you can construct a dictionary from a list of (key, value) pairs using dict(list). Example: l = [('foo', 'bar'), ('baz', 'qig')] d = dict(l) print d {'foo': 'bar', 'baz': 'qig'} -- http://mail.python.org/mailman/listinfo/python-list