Re: Is there any nice way to unpack a list of unknown size??

2008-09-14 Thread Arnaud Delobelle
//mail.python.org/mailman/listinfo/python-list In python >= 2.4, you can define a function like this: def truncate(iterable, n=1): iterator = iter(iterable) for i in iterator: if n == 0: yield iterator return yield i n -= 1 >>> a

Re: Function getting a reference to its own module

2008-09-14 Thread Arnaud Delobelle
On Sep 14, 5:10 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Sep 14, 4:43 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > > > > > On Sep 14, 10:29 am, Steven D'Aprano <[EMAIL PROTECTED] > > > cybersource.c

Re: Question about sorted in Python 3.0rc1

2008-09-22 Thread Arnaud Delobelle
d another sorting order, where we > want to sort by decreasing score and then by DECREASING last name > (instead of increasing last name, defined above). Now that the > comparison function argument is taken away from the sorted builtin, > how do we accomplish this with the "key"

Re: A bit weird dictionary behavior

2008-09-22 Thread Arnaud Delobelle
's exactly the reason! > but it still doesn't feel exactly right. Would it be worth submitting a bug? I don't think it can be considered as a bug, for the reason you gave above and because dictionary keys are by definition unique with respect to equality. Perhaps you could call it a "surprising feature" :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Question about sorted in Python 3.0rc1

2008-09-22 Thread Arnaud Delobelle
On 22 Sep, 11:52, josh logan <[EMAIL PROTECTED]> wrote: > On Sep 22, 3:41 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote: > > > > > On 22 Sep, 04:05, josh logan <[EMAIL PROTECTED]> wrote: > > > > Hello, > > > > I have 2 questions. Say I

Re: What do you call a class not intended to be instantiated

2008-09-22 Thread Arnaud Delobelle
te: def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f >>> @bindfunction ... def foo(me, x): ... me.attr.append(x) ... return me.attr ... >>> foo.attr = [] >>> foo

Re: Detecting the first time I open/append to a file

2008-09-23 Thread Arnaud Delobelle
ppending: writer.writerow(header) writer.writerow(Sigma) But if you only write to the file in one code location, you can set a flag. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Missing collections

2009-12-27 Thread Arnaud Delobelle
eas/2009-July/005219.html The OP implemented both: http://code.google.com/p/python-data-structures/ [...] Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: lightweight encryption of text file

2010-01-09 Thread Arnaud Delobelle
7; encrypted:'&2\xa5\xd4\x17i+E\x01k\xfa\x94\xf80\xa8\x8f\xea.w\x128\xf1\xd9\x0f9\xf2t\xc9\r`\x90%\xd6\xf3~\x1f\x00%u&\x8a\xe4\xe0\xa7\xb8\xb0ec)S>\xcb\xf2>\xec' decrypted:'This encryption scheme is definitely unbreakable.' -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Different number of matches from re.findall and re.split

2010-01-11 Thread Arnaud Delobelle
ifferent by 1, but not 6000!) > > Thanks, > Jeremy When in doubt, the documentation is a good place to start :) http://docs.python.org/library/re.html#re.split re.split(pattern, string[, maxsplit=0]) http://docs.python.org/library/re.html#re.findall re.findall(pattern, str

Re: Procedural API inside class--scoping questions

2010-01-11 Thread Arnaud Delobelle
         self.searchterm=string >          self.servertree.selection_set('Default') >          self.getInfo() > > When I test this command, I get an error from Python: "self" is not > defined. > Is runcommand is method of your class? In that case you should

Re: Interesting (?) problem

2010-01-11 Thread Arnaud Delobelle
list comprehension preserves order: > > hostips_limited = [ h for h in hostips if h in thread_results ] That's ok, but why not keep thread_results as a set instead of a list if the ordering in that container is not significant but you are testing membership a lot? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: integer and string compare, is that correct?

2010-01-11 Thread Arnaud Delobelle
if 3<2 so long as the axioms for a total ordering hold. It won't work for several reasons. Offhand I can think of two: 1. lists, tuples: >>> [1] < ['a'] Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() < str() 2. Partially ordered or unordered builtin types: >>> 1j < 1+1j Traceback (most recent call last): File "", line 1, in TypeError: no ordering relation is defined for complex numbers -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: What is built-in method sub

2010-01-11 Thread Arnaud Delobelle
makes. The re module caches regex strings: >>> import re >>> foo = 'foo+' >>> key = str, foo, 0 >>> re._cache.get(key) >>> re.findall(foo, 'foo bar f') ['foo', 'f'] >>> re._cache.get(key) <_sre.SRE_

Re: shell access

2010-01-11 Thread Arnaud Delobelle
monkeys paw writes: > How do you access the command line from the > python interpreter? > > on unix: > > type python > >>>> print 'hey' > 'hey' >>>> # I want to access the shell here, how do i do that? Like this? >

Re: Code Generator written in python

2010-01-13 Thread Arnaud Delobelle
27;+x+'"''""'))("""(lambda x:x%%('"''""'+x+'"''""'))(%s)""") v = (lambda x:x%('r\"'+x+'\"'))(r"(lambda x:x%%('r\"'+x+&#x

Re: dict's as dict's key.

2010-01-13 Thread Arnaud Delobelle
def __eq__(self, other): return isinstance(other, ctype) and self.propdict == other.propdict Note: you should capitalize your class names if you want to comply with PEP 8. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Code Generator written in python

2010-01-14 Thread Arnaud Delobelle
trzewiczek writes: > On 01/13/2010 05:09 PM, Arnaud Delobelle wrote: [...] >> Sure, here are some example of self-evaluating python objects, >> i.e. for each v below, >> >> v == eval(v) >> >> I'm quite proud of the last one. [...] >> v =

Re: Writing a string.ishex function

2010-01-14 Thread Arnaud Delobelle
ex1. E.g. >>> ishex1(['abc', '123']) True >>> ishex2(['abc', '123']) False -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Writing a string.ishex function

2010-01-14 Thread Arnaud Delobelle
MRAB writes: > Arnaud Delobelle wrote: >> "D'Arcy J.M. Cain" writes: >> >>> On Thu, 14 Jan 2010 09:07:47 -0800 >>> Chris Rebert wrote: >>>> Even more succinctly: >>>> >>>> def ishex(s): >>>

Re: Changing Lutz's mydir from Edition 2, Learning Python

2010-01-17 Thread Arnaud Delobelle
t("Enter module name: ") module = __import__(module_name) > listing(module) > HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: not and is not problem

2010-01-18 Thread Arnaud Delobelle
e is not "seq": >      print "WTF! WHY DOES IT PRINT?" > > help please. > > bye is and == are different operators. * A == B means A.__eq__(B) * A is B means that A and B are the same object, living at the same physical location in the computer's memory. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Python decorator syntax limitations

2010-01-18 Thread Arnaud Delobelle
e place for this python-ideas, > and even there people are not likely to invest much time: > > http://www.python.org/dev/peps/pep-3003/ In actual fact there is a recent discussion of this on python-ideas: http://groups.google.co.uk/group/python-ideas/browse_thread/thread/1eebf486969c39a1/ -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: using super

2010-01-18 Thread Arnaud Delobelle
... def foo(self): ... super(D, self).foo() ... print 'D' ... >>> d = D() >>> d.foo() A C B D >>> D.mro() [, , , , ] The reason why super() may be necessary is that if an object is an instance of say class C, its method resolution order above class C is not known at compile time. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Performance of lists vs. list comprehensions

2010-01-19 Thread Arnaud Delobelle
uilt from the elements of seq. So no, it doesn't guess the size of the joined string and yes, it iterates twice over the "sequence" (I would have thought it should be called an iterable) by copying it into a tuple. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Performance of lists vs. list comprehensions

2010-01-19 Thread Arnaud Delobelle
the most appropriate. Later, when things like generator functions and generator expressions were introduced, perhaps str.join wasn't optimized to accomodate them. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Py 3: How to switch application to Unicode strings?

2010-01-19 Thread Arnaud Delobelle
save your file 'as unicode'. You should save your file with UTF-8 encoding. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
hat there are plenty of discussions of this issue in the archives of c.l.python. I just can't think of a good keyword to google it ATM. However, I am usure about why you are using a metaclass. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
On Jan 21, 6:37 pm, Falcolas wrote: > On Jan 21, 11:24 am, Arnaud Delobelle wrote: > > > > > > > Falcolas writes: > > > I'm running into an issue with closures in metaclasses - that is, if I > > > create a function with a closure in a metacla

Re: Sorted dictionary

2010-01-21 Thread Arnaud Delobelle
#x27;t it take O(log n) time? Insertion and deletion are still O(n) as all items to the right of the inserted/deleted one have to be shifted by one place. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Closures in metaclasses

2010-01-21 Thread Arnaud Delobelle
Falcolas writes: > On Jan 21, 12:10 pm, Arnaud Delobelle wrote: [...] >> Or you could override __getattr__ >> >> -- >> Arnaud > > I tried overriding __getattr__ and got an error at runtime (the > instance did not have xyz key, etc), and the Tag dict is no

Re: Rounding up to the next 100

2010-01-21 Thread Arnaud Delobelle
t; round(float(XstrNmbr), -2) 3600.0 >>> HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Rounding up to the next 100

2010-01-21 Thread Arnaud Delobelle
Arnaud Delobelle writes: > >>> XstrNmbr = 3579.127893 I meant >>> XstrNmbr = "3579.127893" > >>> round(float(XstrNmbr), -2) > 3600.0 -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Consume an iterable

2010-01-22 Thread Arnaud Delobelle
gt; What is the advantage of using a collections.deque against, say, the > following code? > > def consume(iterator, n): > for _ in islice(iterator, n): pass > deque is written in C, and so is islice, so it's less work for the bytecode interpreter? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: [2.5.1.1/dictionary] Change sorting order?

2010-01-22 Thread Arnaud Delobelle
htforward way to do it, taking advantage of negative indices (no doubt there are many others): >>> connected = '0dummy aa bb cc'.split() >>> connected ['0dummy', 'aa', 'bb', 'cc'] >>> startindex = random.randrange(len(c

Re: Consume an iterable

2010-01-22 Thread Arnaud Delobelle
think there was an optional parameter for the number of elements consumed. I hadn't realised it had been deemed useful by others! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: list.pop(0) vs. collections.dequeue

2010-01-22 Thread Arnaud Delobelle
meit(1) 1.8452401161193848 >>> timeit.Timer('while t:del t[-1]', 't=[0]*10').timeit(1) 0.017747163772583008 >>> timeit.Timer( 'while t:del t[0]', 'from collections import deque; t=deque([0]*10)' ).timeit(1) 0.022077083587646484 >>> timeit.Timer( 'while t:del t[-1]', 'from collections import deque; t=deque([0]*10)' ).timeit(1) 0.027813911437988281 -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Using dictionary key as a regular expression class

2010-01-22 Thread Arnaud Delobelle
s sense, or should I look elsewhere? > > Suggestions to improve the above snippet are also welcome. > > Thanks, > > CJ Why not just start with (untested): import codecs from collections import defaultdict tcounters = defaultdict(int) f = codecs.open('/home/gavron/

Re: list.pop(0) vs. collections.dequeue

2010-01-23 Thread Arnaud Delobelle
Dave Angel writes: > Arnaud Delobelle wrote: >> Steve Howell writes: >> >> >>> On Jan 22, 12:14 pm, Chris Rebert wrote: >>> >> I made the comment you quoted. In CPython, it is O(n) to delete/insert >> an element at the st

Re: medians for degree measurements

2010-01-23 Thread Arnaud Delobelle
ata couldn't be like this as then it would be ill-advised to try to apply a notion of median to it. But it will work well I believe with quite localized data set with a few, even wildly inaccurate, outliers. E.g. >>> median_bearing([123, 124, 125, 125, 126, 10, 240]) 125 HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: iterating lists

2010-01-23 Thread Arnaud Delobelle
The behaviour you are observing should then be clearly explained. And you should also realise that it's a really bad idea to mutate a list that you are iterating on! HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: how can i know if a python object have a attribute such as 'attr1'?

2010-01-23 Thread Arnaud Delobelle
can i know whether an object have an attribute named attr1? hasattr(a, 'attr1') -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: how to generate random numbers that satisfy certain distribution

2010-01-23 Thread Arnaud Delobelle
ndom import itertools def poisson(l): e = random.expovariate acc = 0.0 for n in itertools.count(): acc += e(l) if acc >= 1.0: return n -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: [2.5.1.1/dictionary] Change sorting order?

2010-01-24 Thread Arnaud Delobelle
0] >= startch] + [name > for name in connected if name[0] < startch] It would make sense to keep track of the indices where the first word starting with a certain letter starts in the earlier part of the code and to use it now to 'rotate' the list. > print result > == > > Thanks again. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: [2.5.1.1/dictionary] Change sorting order?

2010-01-24 Thread Arnaud Delobelle
Arnaud Delobelle writes: > Gilles Ganault writes: > >> On Fri, 22 Jan 2010 13:17:44 +0100, Gilles Ganault >> wrote: >>>To avoid users from creating login names that start with digits in >>>order to be listed at the top, I'd like to sort the list differ

Re: list.pop(0) vs. collections.dequeue

2010-01-25 Thread Arnaud Delobelle
Steve Howell writes: [...] > My algorithm does exactly N pops and roughly N list accesses, so I > would be going from N*N + N to N + N log N if switched to blist. Can you post your algorithm? It would be interesting to have a concrete use case to base this discussion on. -- Arnaud --

Re: list.pop(0) vs. collections.dequeue

2010-01-26 Thread Arnaud Delobelle
Steve Howell writes: > On Jan 25, 1:32 pm, Arnaud Delobelle wrote: >> Steve Howell writes: >> >> [...] >> >> > My algorithm does exactly N pops and roughly N list accesses, so I >> > would be going from N*N + N to N + N log N if switched to blist.

Re: Generic proxy (that proxies methods like __iter__)

2010-01-27 Thread Arnaud Delobelle
he fly, if you don't mind changing the class of the object (untested): def noguardproxy(obj): class NoGuardProxy(type(obj)): def __enter__(self): return self def __exit__(self, type, value, traceback): return False obj.__class__ = NoGuardProxy

Re: site.py confusion

2010-01-27 Thread Arnaud Delobelle
site.main() line the output is > $ python try.py > In Main() > Hi Now you explicitely call site.main(), so it executes it! > If I change import site to import sitecustomize the output is as > above. What gives? It's normal, this time it's the first time you import it so its content is executed. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: List weirdness - what the heck is going on here?

2010-01-27 Thread Arnaud Delobelle
data > [[0, 0, 0], [0, 0, 0]] > > But suppose I replace the line > > self.data = [[0]]*2 > > with > > self.data = [[0] for c in xrange(2)] > > Then it works fine: > >>>> x = sound() >>>> y = sound() >>>> x.f() >>>&

Re: Need help with a program

2010-01-28 Thread Arnaud Delobelle
agen=(str(i+1)+'\n'+part[0]+'\n' >for i,part in enumerate(partgen) >if len(part)>1 and part[1]!='0') >outfile.writelines(dnagen) I think that generator expressions are overrated :) What's wrong with: with open('dnain.dat') as infile, open('dnaout.dat','w') as outfile: for i, line in enumerate(infile): parts = line.split() if len(parts) > 1 and parts[1] != '0': outfile.write(">seq%s\n%s\n" % (i+1, parts[0])) (untested) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Need help with a program

2010-01-28 Thread Arnaud Delobelle
ot;. > Probably damage from too much Unix scripting. This is funny, I did think *exactly* this when I saw your code :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: slicing return iter?

2009-10-17 Thread Arnaud Delobelle
to do this? (a buit-in function? a > module?) >   - are there any better implements? > > thanks for attention :-) Check the itertools module. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: slicing return iter?

2009-10-17 Thread Arnaud Delobelle
On Oct 17, 6:05 pm, StarWing wrote: > On 10月17日, 下午11时56分, Arnaud Delobelle wrote: > > thanks for attention :-) > > > Check the itertools module. > > > HTH > > > -- > > Arnaud > > I had checked it for serval times. maybe it's my inattent

NetCDF to ascii file

2009-11-12 Thread Arnaud Vandecasteele
x27;, 'time', 'lat', 'tos' print "# Var Dim #" tos = ncFile.variables["tos"] print tos.dimensions #return : ('time', 'lat', 'lon') tosValue = tos.getValue() except : ncFile.close() Do you know how I can get for each tos feature the lat, lon and time values. Best regards Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Python and Ruby

2010-01-31 Thread Arnaud Delobelle
eturn the same value. So, from a non-functional point of vue, f is both the function and its value. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Iterating over a function call

2010-02-01 Thread Arnaud Delobelle
nction, value_iterator) > > or something similar thing in 3.x, but that just adds an additional > function def that I have to include whenever I want to do something > like this. > You have itertools.consume which is close to what you want: consume(imap(func, iterable)) # 2.x consume(map(func, iterable)) # 3.x HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: No return to the parent function

2010-02-02 Thread Arnaud Delobelle
throw raises an exception, it will go through foo. Is this what you want? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: What's this vText() annotation mean?

2010-02-02 Thread Arnaud Delobelle
e more details about the context. A quick google for "vtext python" yields something about an iCalendar package for python. Is it what you are using? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Your beloved python features

2010-02-04 Thread Arnaud Delobelle
ed python features. > > So, may you help me please? If there's a similar thread/blogpost/ > whatever, please give it to me, google couldn't. > > Regards > Julian * simplicity * documentation - some criticise it, I love it. * duck typing * batteries included And lots more! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Dreaming of new generation IDE

2010-02-05 Thread Arnaud Delobelle
olean arguments, would you have eight functions? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Code snippet: dualmethod descriptor

2010-02-06 Thread Arnaud Delobelle
Python 3 you can achieve something a bit similar very simply: >>> class A: ... def foo(self=None): ... return "Instance" if self else "Class" ... >>> A.foo() 'Class' >>> a = A() >>> a.foo() 'Instance' It works in python 3 because unbound methods are plain functions. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Dreaming of new generation IDE

2010-02-06 Thread Arnaud Delobelle
"Gabriel Genellina" writes: > En Fri, 05 Feb 2010 19:22:39 -0300, bartc escribió: >> "Steve Holden" wrote in message >> news:[email protected]... >>> Arnaud Delobelle wrote: >>>> Robert Kern writes: &

Re: Modifying Class Object

2010-02-07 Thread Arnaud Delobelle
gt;> of what Python does use. > > Hm. While most everything I've seen at effbot.org has been clear and > to the point, that particular article reads like a ton of obfuscation. > > Python passes pointers by value, just as e.g. Java does. Please! Not this again!

EAFP gone wrong

2010-02-09 Thread Arnaud Delobelle
... do if hasattr(val, 'latex'): return val.latex() else: ... So was it wrong to say it's EAFP in this case? Should I have known to LBYL from the start? How do you decide which one to use? Up to now, I thought it was more or less a matter of taste b

Re: EAFP gone wrong

2010-02-10 Thread Arnaud Delobelle
Malte Helmert writes: > Arnaud Delobelle wrote: > >> This means that EAFP made me hide a typo which would have been obviously >> detected had I LBYLed, i.e. instead of >> >> try: >> return val.latex() >> except AttributeError: >>

Re: Creating formatted output using picture strings

2010-02-10 Thread Arnaud Delobelle
Regards, > Malcolm def picture(s, pic, placeholder='@'): nextchar=iter(s).next return ''.join(nextchar() if i == placeholder else i for i in pic) passes all your test cases I think (I can't be sure because you didn't post the expected output). The trick is that when nextchar reaches the end of the string 's', it raises a StopIteration which is caught by the generator expression. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Function attributes

2010-02-10 Thread Arnaud Delobelle
(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f >>> @bindfunction ... def factorial(this_function, n): ... if n > 0: ... return n * this_function(n - 1) ... else: ... return 1 ... >>> factorial(15) 1307674368000L >>> fac = factorial >>> fac(15) 1307674368000L >>> factorial = 'foobar' >>> fac(15) 1307674368000L -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Function attributes

2010-02-10 Thread Arnaud Delobelle
Steven D'Aprano writes: > On Wed, 10 Feb 2010 18:31:23 +, Arnaud Delobelle wrote: > >> It's not ideal, but you can use a decorator like this to solve this >> problem: >> >> def bindfunction(f): >> def bound_f(*args, **kwargs): >>

Re: Function attributes

2010-02-10 Thread Arnaud Delobelle
MRAB writes: > Does this mean that Python needs, say, __function__ (and perhaps also > __module__)? See PEP 3130 "Access to Current Module/Class/Function" (rejected) (http://www.python.org/dev/peps/pep-3130/) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Modifying Class Object

2010-02-11 Thread Arnaud Delobelle
cked almost any of your recent endeavours. I've come to the conclusion that you're not a cute furry alien with a long nose. You're a big bad troll! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: calculating a string equation

2010-02-11 Thread Arnaud Delobelle
7;:4} >>> eqat = "(var_a/2.0) <= var_b" >>> result = "(var_a+var_b)/7" >>> eval(eqat, vars) False >>> eval(result, vars) 2 (Note that I have slightly modified your vars dictionary) See a recent thread about the dangers of eval(). -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Function attributes

2010-02-11 Thread Arnaud Delobelle
27;f' inside the function > body "magically" refer to the function itself. I posted an example of a decorator that does just this in this thread a couple of days ago: http://mail.python.org/pipermail/python-list/2010-February/1235742.html It doesn't require any bytecode hacking, although it requires breaking apart the function object and making a new one from the bits. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: constructor overwrite

2010-02-15 Thread Arnaud Delobelle
ava. > is there a way to do it? > thanks Your problem doesn't seem very well defined (e.g. do you ever call obj with two arguments?), but as I understand it you can do this: def __init__(self, x=100): if isinstance(x, int): self.x, self.y = x, None else: self.x, self.y = None, x HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Loop problem while generating a new value with random.randint()

2010-02-15 Thread Arnaud Delobelle
) # generate a new number, that's the > missing line in your script > > JM And a more idiomatic way of writing this in Python would be, I guess: import random var = 65 while True: ranum = random.randint(1, 100) if var == ranum: print var, 'equals to:', ranum break else: print var, 'does not equal to:', ranum (following up from a FU as I can't see the OP) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Modifying Class Object

2010-02-15 Thread Arnaud Delobelle
John Posner writes: [...] >> x = s[0] [...] > assigns the name *x* to the object that *s[0]* refers to s[0] does not refer to an object, it *is* an object (once evaluated of course, otherwise it's just a Python expression). -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: finding contents from string

2010-02-16 Thread Arnaud Delobelle
;http://www.example.com/foo?bar=42&spam=eggs' >>> parsed_url = urlparse.urlparse(url) >>> parsed_url.query 'bar=42&spam=eggs' >>> import cgi >>> parsed_query = cgi.parse_qs(parsed_url.query) >>> parsed_query {'bar': ['42'], 'spam': ['eggs']} In Python >= 2.6, parse_qs lives in the urlparse module as well. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Is there a simple way to find the list index to the max value?

2010-02-16 Thread Arnaud Delobelle
i, n in enumerate(a))[1] >>> max_index 2 >>> # Or: ... from itertools import * >>> max_index = max(izip(a, count()))[1] >>> max_index 2 -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Is there a simple way to find the list index to the max value?

2010-02-16 Thread Arnaud Delobelle
Arnaud Delobelle writes: > "W. eWatson" writes: > >> See Subject. a = [1,4,9,3]. Find max, 9, then index to it, 2. > > Here are a few ways. [...] My copy past went wrond and I forgot the first one: >>> a = [1,4,9,3] >>> max_index = a.inde

Re: Using class attributes

2010-02-16 Thread Arnaud Delobelle
return cls._body except AttributeError: cls._body = read_body_from(cls.template_filename) return cls._body class Foo(object): template_filename = TemplateFilename() template_body = TemplateBody() class FooA(Foo): pass class FooB(Foo): pass #

Re: Implicit __init__ execution in multiple inheritance

2010-02-16 Thread Arnaud Delobelle
rludwinowski writes: > class A: > def __init__(self): > print("A__init__") > > class B: > def __init__(self): > print("B__init__") > > class C(A, B): > pass > > C() > >>> A__init__ > > Why __init__ class B will not be automatic executed? Because it's documented behavi

Re: Using class attributes

2010-02-16 Thread Arnaud Delobelle
You might care if you have many instances but few classes, and the size of template_body is significant. Although with this design it is possible to cache template bodies within the 'read_body_from' function if necessary. Also I was under the impression that the OP wanted these attribute

Re: Is there a simple way to find the list index to the max value?

2010-02-16 Thread Arnaud Delobelle
ex(max(a)). Is that what you wanted ? > > The disadvantage of that is that it's O(2N) instead of O(N). :-) Joke aside, even though you traverse the list twice, it may still be quicker than other solutions because both max and list.index are C functions and no intermediate object is con

Re: Replacement for e.message() in python 2.6

2010-02-17 Thread Arnaud Delobelle
ead of print e.message You can write print str(e) which in turn is equivalent to print e For more details see PEP 352 (http://www.python.org/dev/peps/pep-0352/) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Over(joy)riding

2010-02-17 Thread Arnaud Delobelle
e(self): > self.met() > > def overriden(self): > print "I'm really E's method" > > e = E(10) > print 'MRO:', ' '.join([c.__name__ for c in E.__mro__]) > e.some() > e.calling_overriden() > > > Result: > ... >

Re: Is automatic reload of a module available in Python?

2010-02-17 Thread Arnaud Delobelle
forward. Then when you move on to more sophisticated techniques, I think you will understand better the motivations behind them. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Referring to class methods in class attributes

2010-02-17 Thread Arnaud Delobelle
its" or "license" for more information. >>> class A: ...def f(self): pass ... >>> A.f >>> A.f is A.__dict__['f'] True -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Using class attributes

2010-02-18 Thread Arnaud Delobelle
Leo Breebaart writes: > Arnaud Delobelle writes: > >> Descriptors to the rescue :) >> >> def read_body_from(filename): >> print "** loading content **" >> return "" % filename >> >> # This is a kind of class property

Re: Help with lambda

2010-02-18 Thread Arnaud Delobelle
d so is bound to the same value, which by the end of the loop is 4. So each of the lambdas in the list f is the same as: lambdsa x; x**4 after the end of the list comprehension. The usual fix for this is to change f to: f = [lambda x, n=n: x ** n for n in xrange(2, 5)] I'll let you think why this works. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: How to make an empty generator?

2010-02-18 Thread Arnaud Delobelle
uot;", line 1, in >     StopIteration What about foo = iter('') Then there is the interesting foo = iter(int, 0) :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: How to make an empty generator?

2010-02-19 Thread Arnaud Delobelle
Ben Finney writes: > Arnaud Delobelle writes: > >> What about >> foo = iter('') > > That doesn't return a generator. > > >>> foo = iter('') > >>> foo > > > Whether the OP needs to create a gen

Re: Executing Python code on another computer

2010-02-19 Thread Arnaud Delobelle
unless you use something like Emacs - and also execute them remotely. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Avoid converting functions to methods in a class

2010-02-20 Thread Arnaud Delobelle
ave to make many edits to the test suite rather > than just one. > > Are there any better solutions? > > -- > Steven Why not define target in the TestCase.setUp() method? class AnotherTest(unittest.TestCase): def setUp(self): self.target = mymodule.function def test_foo(self): self.assertEquals(self.target('a', 'b'), 'foo') -- Arnaud class -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Scalable python dict {'key_is_a_string': [count, some_val]}

2010-02-20 Thread Arnaud Delobelle
x27;sort' command. > > Any suggestions, comments? > > By the way, is there a linux command that does the merging part? > > Thanks, > Krishna Have you looked here? http://docs.python.org/library/persistence.html -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Pure virtual functions in Python?

2010-02-20 Thread Arnaud Delobelle
on that calls 'cb' only if 'cb' is implemented in > child classes > def dispatcher(c): > if hasattr(c, 'cb'): > c.cb("Hello", "World") > > dispatcher(C2()) > dispatcher(C3()) > > What I want is the ability to have the dispatcher() not to call 'cb' > if it was not implemented in one of the child classes. If you don't define cb in the parent class, it'll work. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently building ordered dict

2010-02-22 Thread Arnaud Delobelle
uld not really work as unorderedDict is bound to remain empty whatever the values of all the other names. At any rate, why do you need an ordered dictionary? It seems suspect to me as you sort the keys before inserting the items. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Efficiently building ordered dict

2010-02-22 Thread Arnaud Delobelle
.) does, it is quite difficult to guess how to improve it! [1] http://docs.python.org/library/collections.html#collections.defaultdict -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Signature-based Function Overloading in Python

2010-02-23 Thread Arnaud Delobelle
a(x=None): > if x is None: > pass > else: > pass > There are a number of frameworks for function overloading out there. FWIW, there is actually one in the Python sandbox (for Python 3): http://svn.python.org/view/sandbox/trunk/Overload3K/ -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: Creating variables from dicts

2010-02-23 Thread Arnaud Delobelle
the values you want in the global namespace. However, it is almost always a bad idea to do this. Can you explain why you need to do this? -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

Re: while loop with the condition used in the body

2010-02-24 Thread Arnaud Delobelle
t rq: > break > handle_request(rq) > > in Python 2.6. Any suggestions how to rewrite that? > This is the common idiom. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list

<    5   6   7   8   9   10   11   12   >