Re: Decorator Base Class: Needs improvement.

2005-04-05 Thread Bengt Richter
e): ... return lambda f: (name, f) ... >>> @keydeco('pooh_foo') ... def foo(): pass ... >>> @keydeco('tigger_bar') ... def bar(): pass ... >>> dict([foo, bar]) {'pooh_foo': , 'tigger_bar': } ... nah ;-) Anyway, I think a different name for what comes after the "@" and the callable that that (very limited) expression is supposed to return would clarify things. My conceptual model is @decorator_expression # => decorator def decorating_target(...): ... Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Docorator Disected

2005-04-05 Thread Bengt Richter
On Tue, 05 Apr 2005 18:59:32 GMT, Ron_Adam <[EMAIL PROTECTED]> wrote: >On Tue, 05 Apr 2005 06:52:58 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: > >>>Ok, yes, besides the globals, but I figured that part is obvious so I >>>didn't feel I needed to mention it

Re: unittest vs py.test?

2005-04-05 Thread Bengt Richter
On Tue, 5 Apr 2005 14:02:49 GMT, Michael Hudson <[EMAIL PROTECTED]> wrote: >Roy Smith <[EMAIL PROTECTED]> writes: > >> In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Bengt Richter) >> > Is there a package that is accessible without svn? >>

Re: Decorator Base Class: Needs improvement.

2005-04-06 Thread Bengt Richter
tor expression for short? vs the decorator callable produced. >>> @deco.one ... def foo(): pass ... >>> foo >>> @deco.three ... @deco.two ... def bar():pass ... >>> bar Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Decorator Base Class: Needs improvement.

2005-04-06 Thread Bengt Richter
actual @-line expression has to abide by the language grammar, and that does not allow arbitrary expressions. But it does provide enough rope. E.g. see my most recent reply to El Pitonero. > >But this is just a few of my current thoughts which may very well >change. It's an ever changing list. > I can see that ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Does IronPython indicate MS interest in dynamic languages?

2005-04-06 Thread Bengt Richter
MS's PR approves all messages >that leave the building, I'm wondering if this foray into dynamic >languages doesn't signal something greater on MS' part. While Sun and >Java (and C# for the most part) have remained statically-typed, do you >think IronPython might

Re: How to name Exceptions that aren't Errors

2005-04-07 Thread Bengt Richter
than indicate something rejected. E.g., you can terminate a recursive search via an exception. If no exception occurs, you have gone through the entire search space and not met the solution criterion. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: curious problem with large numbers

2005-04-08 Thread Bengt Richter
d', 1e1) > '\x00\x00\x00\x00\x00\x00\xf0?' >(which is actually 1.0) > >python via command line (readline support): > >>> 1e1 > 1.#INF > >>> import struct; struct.pack('d', 1e1) > '\x00\x00\x00\x00\x00\x00\xf0\x7f' > >Note the difference in the final byte. Same results (command >line vs. Idle) for 2.4.1. > Good aha, but ISTM one of them is more missing than different ;-) (I.e., returned packed string is length 7 vs 8) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Can dictionary values access their keys?

2005-04-08 Thread Bengt Richter
t thinking about defining a class for the graph you are concerned with and giving it methods to add children to nodes, and automatically maintain the parent references as you walk your graph and add or delete nodes. Then you should easily be able to define more methods to get various info as you may w

Re: curious problem with large numbers

2005-04-08 Thread Bengt Richter
On Fri, 08 Apr 2005 10:18:05 -0700, Scott David Daniels <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >>>Aha! Same version (2.3.4): >>> >>>Idle: >>>>>> 1e1 >>>1.0 >>>>>> import struct; struct.pa

Re: Puzzling OO design problem

2005-04-10 Thread Bengt Richter
# test.py # command: python test.py <#version> def NamespaceFactory(version): return __import__("version_%d" % version).Namespace print NamespaceFactory(2).B().foo() # "version_2.foo()" print NamespaceFactory(3).C().bar() # "version_3.bar()" import sys, inspect namespace = NamespaceFactory(int(sys.argv[1])) # print the __mro__ of each 'inner' class for name,cls in inspect.getmembers(namespace, inspect.isclass): #for name, cls in (t for t in namespace.__dict__.items() if isinstance(t[1], type)): print cls for ancestor in cls.__mro__: print "\t", ancestor #== - Run: [ 5:33] C:\pywk\clp\sakkis\meta>py24 vermeta.py 3 version_2.foo() version_3.bar() Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: workaround for generating gui tools

2005-04-10 Thread Bengt Richter
an't wait for it to be replaced with something better, not because it's the best thing. Sort of like how MSDOS got its place in the world. Alternatively, GUI elements could have registrable encode/decode methods with some kind of UniGUIcode abstract core ;-) I kind of like that, off hand... Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Doubt regarding sorting functions

2005-04-10 Thread Bengt Richter
l help someone avoid a seemingly helpless or lazy post like yours. BTW, a request to "mail me as early as possible" is more likely to get favorable consideration if you explain why you can't monitor the newsgroup postings for a reply. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: args attribute of Exception objects

2005-04-11 Thread Bengt Richter
d put getnames(expr) in the expression for symdep = dict(...) in place of sorted(eval('lambda:'+expr).func_code.co_names)) >variation on the theme can: > - check SyntaxError and give interlligent feedback to user (BTW, >SyntaxError args are much smarter) compiler.parse will raise SyntaxError in getnames, so you could make your own message, e.g., >>> try: getnames('a*b+c***foo(x)') # *** is syntax error ... except SyntaxError, e: ... print 'SyntaxError: %s<<--BROKE HERE-->>%s' % (e.text[:e.offset], e.text[e.offset:]) ... SyntaxError: a*b+c***<<--BROKE HERE-->>foo(x) > - find or/and eval recursively the whole tree and keep in cache >values,... > HTH Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: workaround for generating gui tools

2005-04-11 Thread Bengt Richter
On Mon, 11 Apr 2005 10:05:49 -0300, "Gabriel B." <[EMAIL PROTECTED]> wrote: >On Apr 10, 2005 11:08 PM, Bengt Richter <[EMAIL PROTECTED]> wrote: >> On Sat, 9 Apr 2005 19:22:16 +0200, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: >> open('

Re: singleton objects with decorators

2005-04-11 Thread Bengt Richter
_.Boobar object at 0x02F03DCC>] [123, 123] Gee: <__main__.Gee object at 0x02F03E8C> [<__main__.Gee object at 0x02F03E8C>, <__main__.Gee object at 0x02F03E8C>] {'args': (1, 2L, 3.5), 'kw': {'s': 'string', 'more': 'example'}} {'args': (1, 2L, 3.5), 'kw': {'s': 'string', 'more': 'example'}} [<__main__.Haw object at 0x02F03F0C>, <__main__.Haw object at 0x02F03F0C>] [1, 2L, 3.5] ['string', 'example'] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: args attribute of Exception objects

2005-04-12 Thread Bengt Richter
27;, ';-)') ('usual ordinary message form',) ((8+9j), ) (<__main__.AClass object at 0x02EF166C>, '<=[class instance]') ('',) Oops, left out the no-arg raises >>> try: raise XEasy ... except XEasy, e: print e.args ... () >>> try: raise XEasy() ... except XEasy, e: print e.args ... () Did I misunderstand the problem again? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: singleton objects with decorators

2005-04-12 Thread Bengt Richter
tance like a responsible adult ;-) But isn't bool supposed to be a singleton class/type ? >>> [bool(x) for x in 0, 0.0, [], {}, False] [False, False, False, False, False] >>> [id(bool(x)) for x in 0, 0.0, [], {}, False] [505014288, 505014288, 505014288, 505014288, 505014288] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: singleton objects with decorators

2005-04-12 Thread Bengt Richter
On Tue, 12 Apr 2005 13:26:54 +0200, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >> But isn't bool supposed to be a singleton class/type ? >> >> >>> [bool(x) for x in 0, 0.0, [], {}, False] >> [False, Fal

Re: Why won't someone step up and make use of the Free tools (was Re: Python 2.4 killing commercial Windows Python development ?)

2005-04-12 Thread Bengt Richter
of which I have on another old box which is too slow for X ;-) Trouble is, I have banged on the pinching spots in my old NT shoes long enough to where they are relatively comfy for my regular ambulations ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: singleton objects with decorators

2005-04-12 Thread Bengt Richter
quare(1234))...]: ten have same id: True T: True 49271436 F: False 49271884 [id(Bool(1..10))...]: ten have same id: True BTW, I found this page interesting: http://c2.com/cgi/wiki?SingletonPattern Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
45380634A90470354AAB303884B7B09B2037B95405BA145 704B19B14AA8028810881AB6072441194A875477836B37704B5199062319A336375437403562A663B835B891957883AB Hint: Lambert Meertens. Tweak the algorithm you find ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Python license (2.3)

2005-04-13 Thread Bengt Richter
rk up some paradigmatic examples and put them in the wiki? BTW, I dislike large legal boilerplate (that IIRC I've even seen occupying more lines than the code it was describing in a few cases). Is a simple one-line notice referring to the full license text somewhere legally sufficient? How d

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
On Wed, 13 Apr 2005 03:27:06 -0700, Dick Moores <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote at 03:19 4/13/2005: >>On Wed, 13 Apr 2005 02:06:11 -0700, Dick Moores <[EMAIL PROTECTED]> wrote: >> >> >I need to figure out how to compute pi to base 12, to as

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
On Wed, 13 Apr 2005 21:52:45 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: [...] > >If you replace >a, a1 = 10L*(a%b), 10L*(a1%b1) >with >a, a1 = 12L*(a%b), 12L*(a1%b1) > >and >sys.stdout.write(`int(d)`) >with >sys.std

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
wall size. Or pdf. I'm tempted to play with my pdf plotting toy and maybe make it work ;-) I'm kind of curious what the ear could pick up about pi from hearing the sequence as notes. Or intervals, or grouped to make chords even. Anyone have an easy python midi interface for windows to play on the sound card? I could generate a .wav file to play tones, but midi would be much more compact ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
s" who would cut off their thumbs and great >toes in order that they might better count in hexadecimal. > I suspect using four dates back to the nixie tribe, who practiced bi-quinary. And they would cut off little toes and fingers rather, because then the thumb was more significant and

Re: Compute pi to base 12 using Python?

2005-04-13 Thread Bengt Richter
def foo(): ...t0 = clock() ...open('pi12by60.txt','w').write( ... ''.join(c+'\n'[:(i+1)%60==0] for i,c in enumerate(pidigits(12, 3003)))+'\n') ...print clock()-t0 ... >>> foo() 22.3866400935 That's on a 300Mhz Pentium II using the Lambert Meertens algorithm for pi ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Inelegant

2005-04-14 Thread Bengt Richter
tring = Dedent(**kw)+\ ... """ ... This makes ...for a cleaner isolation ... of the string IMO. ... """ ... return mystring ... >>> print '\n%s'%foo() This makes for a cleaner isolation of the string IMO. >>> print '\n%s'%foo(margin=3) This makes for a cleaner isolation of the string IMO. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Bengt Richter
>>> type(a).__iter__ >>> type(a).__iter__(a) __iter__ Now if we get rid of the __iter__ method, __getattr__ can come into play again: >>> del Args.__iter__ >>> a.__iter__ __getattr__: __iter__ >>> a.__iter__() __getattr__: __iter__ &g

Re: Using python from a browser/security hole

2005-04-15 Thread Bengt Richter
va is my only >> >> way out ? See comment above. >> > >> >Java is designed to be safe and not allow access to client devices. >> > There is a mechanism where you can attempt to ask for permission from >> > Java but it looked complex to me and

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
ed keywords. For example, here is code as it would >> currently be written in Python: >> >> if a: >> x = 1 >> else: >> x = 2 >> f(x=x) >> >> When reading this code, one reaches the 'if' statment without knowing what >> it

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
replied to to you via James Stroud's reply (q.v.) ;-) BTW, I like this suite-based keword definition for calls better than the thunk stuff ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Simple Thunks

2005-04-16 Thread Bengt Richter
args): ... for specifying the thunk call parameters, and the already established decorator call mechanism make this attractive. Also, if you allow named thunks (I don't quite understand why they should "expire" if they can be bound to something. The "thunk-accepting fu

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Bengt Richter
> if (as func(x,y): x+y) (i,j) > 10: > print True if (def(x,y): x+y) (i,j) > 10: print true I haven't thought of all the uses for anonymous callable suites (thunks), but imagine as callback: (putting it as an unusual default parameter makes it bind in the same namspace as the definintion of foo) def foo(x, cb=(y):print y): cb(x) foo(3) # => prints 3 and assigns y=3 as local-to-foo-definer side effect (often main effect) foo(123, (z):print 'Setting z=%r'%z) => prints Setting z=123 and sets z=123 locally to foo caller. foo(456, lambda *ignore:None) # also legal, foo doesn't know what callable it's being passed The suite-based keyword call syntax foo(): x = 1 y = [1,2] def foo():pass can be handled with the more general foo(**kw) where: kw = dict(:: x = 1 y = [1,2] def foo():pass) This is a new rev on my thoughts. Expect contradictions with older stuff. Naturally I like my newest ideas best ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
On Sat, 16 Apr 2005 14:02:32 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> On Fri, 15 Apr 2005 19:32:02 -0700, James Stroud <[EMAIL PROTECTED]> wrote: >>>> Examples >>>> >>>> >>>> Using su

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
= 2 ).keys() => ['x', 'y'] or call foo foo(self, whatever, *(:: x = 1 y = 2).values()) Oh well, that's the way ideas evolve ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Bengt Richter
e to require >two suites: > >t = f(): > x = 1 >if t: > y = 1 It's a little clunky, but if self.f(self, z, *a) where: z=123 a = getarglist(): # ':' terminates transparent where: y = 1 # indentation as if where: were == '' > >In general, I think that anything more than just a function call with an >optional assignment should be disallowed: > >y = [f()]: # ? probably shouldn't be allowed > x = 1 y = [f(**:: x=1)] # sort form with single-line for :: or y = [f(**:: x = 1 )] isolates the suite better, in case it has logic and fancy stuff Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-16 Thread Bengt Richter
On Sun, 17 Apr 2005 01:10:47 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: [...] > >The "::" expression I'm proposing generalizes capturing suite bindings into an >ordered sequence of (key,value) >tuples, like an ordered vars().items() limited to the bindings produc

Re: pre-PEP: Simple Thunks

2005-04-17 Thread Bengt Richter
new syntax? > Ok, I agree this does not fit decorators well. And I do agree that a nice syntax that sugars over the creation and passing of thunks makes for clean simple cases, but I would like access to the non-sugar primitives too, which for do in (): IIUC translates to my < opt assignment> (((): ),) With possible paren dropping and white space insertion if you want to arrange things. With the primitives, I can pass multiple thunks to an accepter, and put them in specific arg positions. I also can also bind it and use it to get a side effect out of a generator expression that now has its own scope, e.g., count = 0 counter(count): count +=1 list(i for i in xrange(20) if counter() or True) Interestingly, this ought to work, right? stopper(i): if i>5: raise StopIteration list(stopper(i) or i for i in xrange(20)) All untested hadwaving, of course ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords

2005-04-17 Thread Bengt Richter
qqF46jprlU1%40individual.net > Apologies for lack of attibution, Andrey. And I'm not sure I used your "where" properly just recently. I added it to some other stuff in haste, without actually remembering exactly where it came from, believe it or not, even though I got heavi

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-17 Thread Bengt Richter
On 16 Apr 2005 23:43:03 -0700, "Kay Schluehr" <[EMAIL PROTECTED]> wrote: > >Robert Brewer wrote: >> Bengt Richter wrote: >> > The '::' unary suite operator should return an ordered dict >> > subtype representing the bindings >> &g

Re: Compute pi to base 12 using Python?

2005-04-17 Thread Bengt Richter
on myscript.py [whatever args here] > pi3003.txt If myscript.py is not in the current directory, use a sufficient path to it. If your windows is having that problem, the same will happen with a perl script or other script when you run it as just myscript.ext ... and depend on windows to start the right interpreter. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords

2005-04-17 Thread Bengt Richter
On Sun, 17 Apr 2005 15:25:04 +0200, Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >> Stretching for it, using my latest and greatest ;-) >> >> y = f(**:: >>x = 1 >>y = 'y for f' >>

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-17 Thread Bengt Richter
fset = None >fdel = None > doc = "I'm the 'x' property." > > >Evaluate conditions: > >if f(*args)==1 where args: > x = 1 > y = 2 > >I think this version is more mainstream syntax ( and without braces and >additional punctuation ) than the unary prefix operator '::' which >drops statements into expressions within expressions. > I like this mainstream syntax for ordinary use cases, but as mentioned, I'd still like to have primitives accessible. I don't see why both couldn't live in harmony ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Simple Thunks

2005-04-17 Thread Bengt Richter
On Sun, 17 Apr 2005 15:32:56 -0700, Brian Sabbey <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> Hm, one thing my syntax does, I just noticed, is allow you >> to pass several thunks to a thunk-accepter, if desired, e.g., >> (parenthesizing this time, rather than

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-18 Thread Bengt Richter
, x=1) > >and that is > > dict(**kw) where **kw: > x=1 so for foo(*args) where: args = dict(**kw).keys() where **kw: x=1 but it's much easier (now with explorations and ideas above ;-) to write foo(*args.values()) where args:: x=1 > >I don't see any case where this translation fails. Only if it comes to >functional composition like > > f(g(...(h(:: x=1)...)) > >it may be awkward to expand this into a nested where clauses. You might >probably define the argument not in a suite ;) There are probably some things that won't look reasonable no matter what ;-) But to summarize, I think we should try to write a real grammar for all this, and show how it would fit in with the real python grammar. I think I should make a separate post for this ;-) see grammar for where/letting/with and suite expressions (thunks etc) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

grammar for where/letting/with and suite expressions (thunks etc)

2005-04-18 Thread Bengt Richter
;-), the expression is parenthesized, and closes with the closing ')' f = (def(x=default()): pass ) letting: def default(): pass or uglier: f = (def(x=default()): pass) letting: def default(): pass You could even write a one-liner for this, since the suites are one-liner passes ;-) f = (def(x=default()):pass) letting default=(def():pass) So there was really only a problem with the decorator. But I gotta go for now. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords

2005-04-18 Thread Bengt Richter
On Mon, 18 Apr 2005 12:50:24 +0200, Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> On Sun, 17 Apr 2005 15:25:04 +0200, Reinhold Birkenfeld <[EMAIL PROTECTED]> >> wrote: > >>>> Note that there is no problem adding other paramet

Re: pre-PEP: Suite-Based Keywords

2005-04-18 Thread Bengt Richter
prettier, until you actually try to use them: > >>>> g( *args_from_somewhere, x=3D'x for g', y=3D'y for g', foo=3Dlambda: >return 'foo for g' ) >Traceback ( File "", line 1 >g( *args_from_somewhere, x=3D'x for g'

Re: Enumerating formatting strings

2005-04-18 Thread Bengt Richter
matter(a1=thevalue) # Formatter as base class knows how to do name lookup Or is this just idearrhea? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-19 Thread Bengt Richter
On 19 Apr 2005 00:16:32 -0700, "Kay Schluehr" <[EMAIL PROTECTED]> wrote: > >Bengt Richter wrote: > >[...] > >> Um, I think that's too narrow for where. Consider >> >> foo = f1; bar=f2; x=k1; y=k2 >> foo(x)*bar(y)[3]

Re: def a((b,c,d),e):

2005-04-19 Thread Bengt Richter
ults) method that would accept an unpacking spec like 'a, (x, y=%0))', [] And give its instances a __call__ method so you can use it like a,b,c = upk('a, (x, y=%0))', [555])((7,8)) => a,b,c == (7, 8, 555) How useful how often though? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Array of Chars to String

2005-04-19 Thread Bengt Richter
''.join([chr(i) for i in xrange(256) if chr(i) not in letters])) ... >>> some_func("Bob Carol Ted Alice", 'adB') 'Bad' see help(str.translate) If you want to use it in a loop, with the same "letters" I'd want to eliminate the repeated calculation of the deletions. You could make a factory function that returns a function that uses deletions from a closure cell. But don't optimize prematurely ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Array of Chars to String

2005-04-19 Thread Bengt Richter
On Tue, 19 Apr 2005 17:00:02 -0700, Michael Spencer <[EMAIL PROTECTED]> wrote: >Michael Spencer wrote: >> Bengt Richter wrote: >> > I think this will be worth it if your string to modify is _very_ long: >> >>> >>> >>> def some_func(s

Re: How to run Python in Windows w/o popping a DOS box?

2005-04-19 Thread Bengt Richter
es, then select the shortcut tab and edit the target string with s/python/pythonw/ and then click ok. Then try double clicking the shortcut icon again. If that does it, you're home ;-) If not, post more symptoms. HTH Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: How to Convert a makefile to Python Script

2005-04-19 Thread Bengt Richter
in python, so I'd try to find someone there to ask. They must have thought about it a lot. http://www.scons.org/ Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Enumerating formatting strings

2005-04-20 Thread Bengt Richter
string. > >Indeed. > Parse might be a big word for >> def tupreq(fmt): return sum(map(lambda s:list(s).count('%'), >> fmt.split('%%'))) .. >> tupreq('%s this %(x)s not %% but %s') (if it works in general ;-) Or maybe clearer and faster: >>> def tupreq(fmt): return sum(1 for c in fmt.replace('%%','') if c=='%') ... >>> tupreq('%s this %(x)s not %% but %s') 3 Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Python instances

2005-04-20 Thread Bengt Richter
are default methods inherited from object and/or type, the most primitive classes, so you don't have to define them except to customize for your purposes. At least, that's the way I think of it ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Behaviour of str.split

2005-04-20 Thread Bengt Richter
lit(arg))==s The second is not 1:1 nor reversible: '<>'.join(s.split()) == s ?? Not usually. I think you can do it with the equivalent whitespace regex, preserving the splitout whitespace substrings and ''.joining those back with the others, but not with split(). I.e., >>> def splitjoin(s, splitter=None): ... return (splitter is None and '<>' or splitter).join(s.split(splitter)) ... >>> splitjoin('a*b*c', '*') 'a*b*c' >>> splitjoin('a*b', '*') 'a*b' >>> splitjoin('a', '*') 'a' >>> splitjoin('', '*') '' >>> splitjoin('a bc') 'a<>b<>c' >>> splitjoin('a b') 'a<>b' >>> splitjoin(' b') 'b' >>> splitjoin('') '' >>> splitjoin('*','*') '*' Note why that works: >>> '*'.split('*') ['', '', '', '', '', ''] >>> '*a'.split('*') ['', 'a'] >>> 'a*'.split('*') ['a', ''] >>> splitjoin('*a','*') '*a' >>> splitjoin('a*','*') 'a*' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Enumerating formatting strings

2005-04-20 Thread Bengt Richter
On Wed, 20 Apr 2005 11:01:28 +0200, Peter Otten <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >> Parse might be a big word for >> >> >> def tupreq(fmt): return sum(map(lambda s:list(s).count('%'), >> >> fmt.split('%%')

Re: Python instances

2005-04-21 Thread Bengt Richter
MyClass: > def __init__(self): > self.list = [] > > def add(self, x): > self.list.append(x) > The following shows nothing static anywhere, yet a class has been defined, an instance created, and __init__ called with initial value, and the value retrieved as an

Re: Enumerating formatting strings

2005-04-21 Thread Bengt Richter
third -- expect " 012 ab" after colon:' -> '%5.3d' % (12,) => ' 012' -> '%4s' % ('ab',) => ' ab' third -- expect " 012 ab" after colon: 012 ab test with: '%(arg1)s %% %(arg2).

Re: Array of Chars to String

2005-04-21 Thread Bengt Richter
ter(letters.__contains__, astr) >'Bad' >>>> filter(set(letters).__contains__, astr) >'Bad' > Baaad ;-) But since I'm playing the other side of the table for the moment, isn't filter to be deprecated? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Python instances

2005-04-21 Thread Bengt Richter
On Thu, 21 Apr 2005 07:58:14 -0400, Kent Johnson <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> The following shows nothing static anywhere, yet a class has been defined, >> an instance created, and >> __init__ called with initial value, and the value retrieved

Re: Strings

2005-04-21 Thread Bengt Richter
\012' >>> list(s) ['e', 's', 'c', 'a', 'p', 'e', 's', ' ', '\\', 'n', ' ', '\n', ' ', '\n', ' ', '\n'] OTOH, don't try that with '\a': >>> list('\a \x07 \07') ['\x07', ' ', '\x07', ' ', '\x07'] Why not like \n above or like \t >>> list('\t \x09 \011') ['\t', ' ', '\t', ' ', '\t'] Is this fixed by now? It's not news ;-) >>> '\a' '\x07' Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: grouping subsequences with BIO tags

2005-04-21 Thread Bengt Richter
roups, just different from last ;-) >... elif self.last_label[2:] != label[2:]: >... raise ValueError('%s followed by %s' % >... (self.last_label, label)) >... self.last_label = label >... return self.last_result >... >py> def get_runs(lst): >... for _, item in itertools.groupby(lst, K()): >... result = list(item) >... if result != ['O']: >... yield result >... >py> list(get_runs(['O', 'B_X', 'B_Y', 'I_Y', 'O', 'B_X', 'I_X', 'B_X'])) >[['B_X'], ['B_Y', 'I_Y'], ['B_X', 'I_X'], ['B_X']] >py> list(get_runs(['O', 'I_Y'])) >Traceback (most recent call last): > ... >ValueError: O followed by I_Y >py> list(get_runs(['B_X', 'I_Y'])) >Traceback (most recent call last): > ... >ValueError: B_X followed by I_Y > >Can anyone see another way to do this? > Well, there's no end to "another way", but above is my .02USD ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Bengt Richter
interactive calculator that acts according to your taste, you can program one to prompt and read (use raw_input, not input BTW) what you type in and calculate and print whatever form of result you'd like. See the cmd module for one way not to reinvent some wheels. But why not spend some time with the tutorials, so have a few more cards in your deck before you try to play for real? ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: a=[ lambda t: t**n for n in range(4) ]

2005-04-23 Thread Bengt Richter
On 22 Apr 2005 20:45:55 -0700, "El Pitonero" <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> I still don't know what you are asking for, but here is a toy, >> ... >> But why not spend some time with the tutorials, so have a few more >cards in

Re: How to run Python in Windows w/o popping a DOS box?

2005-04-23 Thread Bengt Richter
(learn another whole set of methods to figure out how to >change startup). I don't disagree about the usefulness of various text data, I just want to distinguish data from metadata and container identifiers from data identifiers. > >hopefully I am making sense, > I think we were just looking a different aspects of the elephant ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: grouping subsequences with BIO tags

2005-04-22 Thread Bengt Richter
On Fri, 22 Apr 2005 16:01:42 -0700, Michael Spencer <[EMAIL PROTECTED]> wrote: >Steven Bethard wrote: >> Bengt Richter wrote: >> >>> On Thu, 21 Apr 2005 15:37:03 -0600, Steven Bethard >>> <[EMAIL PROTECTED]> wrote: >>> >>>> I ha

Re: Bounding box on clusters in a 2D list

2005-04-23 Thread Bengt Richter
_/ _/_/ / [1,/0, 0,/1,/0], _/ / [0, 0,/1,/0, 0]] Or should that be +-+ [[|0, 0, 1, 0, 0|], | | [|0, 1, 0, 0, 1|], | | [|1, 0, 0, 1, 0|], | | [|0, 0, 1, 0, 0|]] +-----+ s

Re: Variables

2005-04-23 Thread Bengt Richter
foo = 5 expresses the step of putting them into correspondence to define a mapping, not declaring them equal. Even in math notation, ISTM important to distinguish between a finger and what it may for the moment be pointing at. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Variables

2005-04-24 Thread Bengt Richter
On Sun, 24 Apr 2005 00:59:45 -0400, Richard Blackwood <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: > >>On Sat, 23 Apr 2005 22:45:14 -0400, Richard Blackwood <[EMAIL PROTECTED]> >>wrote: >> >> >> >>>Robert Kern wrote: >>> >

Re: Bounding box on clusters in a 2D list

2005-04-24 Thread Bengt Richter
| | 0 | 1 0 0 0 1 | | +---+ | 0 | 1 0 | 1 | 0 1 | | +---+ | 0 | 1 0 0 0 1 | | | 0 | 1 1 1 1 1 | +-------+ Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Injecting code into a function

2005-04-25 Thread Bengt Richter
-- t3' t1() t2() t2('hello ') - [22:42] C:\pywk\clp\sakkis\tracelocals>py24 tracelocals.py tmod t3 t1 t2 t3 ['tmod', 't3', 't1', 't2', 't3'] main( tmod t3 ('t1', 't2', 't3') ) -- t3 -- t1 -- t2 -- t2 t1: {'x': 't1'} t2: {'y': 246} t2: {'y': 'hello hello '} t3: {} [22:46] C:\pywk\clp\sakkis\tracelocals>py24 tracelocals.py tmod t3 t2 ['tmod', 't3', 't2'] main( tmod t3 ('t2',) ) -- t3 -- t1 -- t2 -- t2 t2: {'y': 246} t2: {'y': 'hello hello '} Notice that the -- side effects from all being called in the last, but only t2 being captured. Maybe this will give you something to expand to your needs. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: What's do list comprehensions do that generator expressions don't?

2005-04-25 Thread Bengt Richter
>spell list(genexp), and he should use it if he wants the entire list >constructed in memory. ISTM you have to account for >>> def foo(g): return g ... >>> foo(123) 123 >>> foo(c for c in 'abc') >>> [(c for c in 'abc')] [] &g

Re: Quote-aware string splitting

2005-04-26 Thread Bengt Richter
quot;'))] if r] or [''] ['sspam', '" ssthe life of brianss "', '42'] >>> x = ' "" "" ' >>> [r for r in [(i%2 and ['"'+z+'"'] or [z.strip()])[0] for i,z i

Re: Injecting code into a function

2005-04-26 Thread Bengt Richter
and later check also) pretty seriously, but it has to be pretty legal to start. Of course one could abuse magic-content strings, but metaclasses can already do a lot of that. That's not what I'm hoping to do. Just super-duper-decoration ;-) Anyway, that's a sketch of the idea. I won't have time for it or much else for a longish while now. If someone's interested, they can quote this and start another thread ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: What's do list comprehensions do that generator expressions don't?

2005-04-26 Thread Bengt Richter
s reasoning was both stylistic and technical, >but you'd have to check the archives for more. > Because it is too reminiscent of a lambda expression assignment? ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: regex over files

2005-04-26 Thread Bengt Richter
XXXX' '\n' [1] In some cases of regexes with lookahead context, you might have to check that the last piece not only exists but exceeds max lookahead length, in case there is a | kind of thing in the regex where would have succeeded with another chunk appended to buffer, but did the split. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Pythonic way to do static local variables?

2005-04-26 Thread Bengt Richter
x27;append will fail')) 2 0 LOAD_CONST 1 ('append will fail') 3 STORE_FAST 1 (state) 4 6 LOAD_FAST1 (state) 9 LOAD_ATTR1 (append) 12 LOAD_FAST0 (a) 15 CALL_FUNCTION1 18 POP_TOP 5 19 LOAD_FAST1 (state) 22 RETURN_VALUE Note that the function takes only one argument: >>> f2 >>> f2.func_code.co_argcount 1 >>> f2(10, 'fails') Traceback (most recent call last): File "", line 1, in ? TypeError: f() takes exactly 1 argument (2 given) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Pythonic way to do static local variables?

2005-04-26 Thread Bengt Richter
- > >>>> cumulative_sum(1) >1 >>>> cumulative_sum(1) >2 >>>> cumulative_sum(1) >3 > This default-value hack is what my presets decorator was motivated to replace (if you are willing to depend to a byte-code-hacking decorator ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: names of methods, exported functions

2005-04-27 Thread Bengt Richter
nd | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -- extend list by appending elements from the iterable | | index(...) | L.index(value, [start, [stop]]) -> integer -- return first index of value | | insert(...) | L.insert(index, object) -- insert object before index | | pop(...) | L.pop([index]) -> item -- remove and return item at index (default last) | | remove(...) | L.remove(value) -- remove first occurrence of value | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; | cmp(x, y) -> -1, 0, 1 | | -- | Data and other attributes inherited from __builtin__.list: | | __new__ = | T.__new__(S, ...) -> a new object with type S, a subtype of T >>> Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: suggestions on how to do this

2005-04-27 Thread Bengt Richter
(4) -> A**2/64 b(5) -> A/25 b(6) -> -A**3/2304 b(7) -> -29*A**2/4900 b(8) -> A**4/147456 b(9) -> 563*A**3/2116800 b(10) -> A**2/2500 -A**5/14745600 b(11) -> -5927*A**4/1024531200 b(12) -> -43*A**3/98 +A**6/2123366400 b(13) -> 824003*A**5/11081329459200 b(14) -> 16397*A**4/1037232 -A**7/416179814400 b(15) -> A**3/562500 -1260403*A**6/1994639302656000 Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: creating very small types

2005-04-27 Thread Bengt Richter
t; '\x0f' [1] '\x0f' [1] -(decode)-> 'F' [1] [22:02] C:\pywk\clp>py24 trivcodec.py 'abaFECbaabbDF' [13] -(encode)-> '\xf2;Q\xf7' [4] '\xf2;Q\xf7' [4] -(decode)-> 'abaFECbaabbDF' [13] [22:02] C:\pywk\clp>py24 trivcodec.py CC DD EE FF '' [8] -(encode)-> '\x00' [1] '\x00' [1] -(decode)-> '' [8] '' [4] -(encode)-> 'U' [1] 'U' [1] -(decode)-> '' [4] 'CC' [2] -(encode)-> '3' [1] '3' [1] -(decode)-> 'CC' [2] 'DD' [2] -(encode)-> 'w' [1] 'w' [1] -(decode)-> 'DD' [2] 'EE' [2] -(encode)-> '\xbb' [1] '\xbb' [1] -(decode)-> 'EE' [2] 'FF' [2] -(encode)-> '\x00' [1] '\x00' [1] -(decode)-> 'FF' [2] [22:03] C:\pywk\clp>py24 trivcodec.py CCDDEEFF 'CCDDEEFF' [20] -(encode)-> '\x00U3w\xbb\x00' [6] '\x00U3w\xbb\x00' [6] -(decode)-> 'CCDDEEFF' [20] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: regex over files

2005-04-27 Thread Bengt Richter
-) >version and we don't have to solve the problem of any corner cases (note the >different values of n). I'm happy to take the extra runtime in exchange for >simpler code. > Agree. Hm, I wonder if the OS notices sequential page faults and schedules speculative read-ahead. Hm2, I wonder if you can just touch bytes from another coordinated thread to cause that, if it isn't happening ;-) Not for 15% though ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: creating very small types

2005-04-28 Thread Bengt Richter
On Thu, 28 Apr 2005 05:07:34 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: ... some not quite correct code ;-/ (I copy/pasted and created an illusion. My code dict has no EOS, so I decode pad zero bits as code that a single zero stands for ('a' in this case) so that was an oversight

Re: regex over files

2005-04-28 Thread Bengt Richter
27;t have a delusion-busting gotcha lurking ;-) But this kind of partitioning of VM lru logic would take some kernel changes IWT. IIRC, don't mmap VM access ideas date back to multics at least? Anyway, what with fancy controllers as well as fancy file systems and kernels, it's easy

Re: Setting win32 console title from Python

2005-04-28 Thread Bengt Richter
f the function fails, the return value is FALSE. To get extended error information, call GetLastError. See Also GetConsoleTitle Alternatively, you could compile your own extension for title setting/getting called consoletitle.dll using the above API (assuming it works) and its companion GetConsoleTitle. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: anonymous function objects?

2005-04-29 Thread Bengt Richter
#x27;, <__main__.Foobar object at 0x02F0428C>) >>> f.real() ('real', <__main__.Foobar object at 0x02F0428C>) >>> g.real() ('real', <__main__.Foobar object at 0x02EF134C>) ^^ IOW, a plain callable has __get__ and gets bound to the instance, whereas a bound method doesn't have __get__ any more, so it gets retrieved as a plain attribute. BTW, to get an ordinary function call for a function attribute of a Foobar instance, you'd have to eliminate the function's __get__ effect one way or another, e.g. staticmethod (which really wraps the function with a descriptor, substituting its own __get__, which Foobar.__getattribute__ uses transparently) >>> def sm(firstarg='sm first arg', *args): return firstarg, args ... >>> g.sm = staticmethod(sm) >>> g.sm() ('sm first arg', ()) >>> g.sm >>> g.__dict__['sm'] >>> g.__dict__['sm'].__get__ >>> g.__dict__['sm'].__get__(g) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Working with method-wrapper objects

2005-04-29 Thread Bengt Richter
ow the same kind of logic to the final method call via __call__ >>> foo = [1, 2, 'this is a particular list instance'] >>> type(foo).mro() [, ] >>> type(foo).mro()[0].__dict__ >>> type(foo).mro()[0].__dict__['__str__'] Traceback (m

Re: Reusing object methods?

2005-04-29 Thread Bengt Richter
or an instance. What makes it a method is the attribute-retrieval mechanism. So what you want to do is possible, but A.a_lengthy_method is not the function, it is an unbound method (because it was retrieved as an attribute of the class as opposed to via an instance. For an ordinary method, you can get the function via the im_func attribute, but if you want to borrow something trickier, you may want to try the way class D does it. For new-style classes, you will run across some differences. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Micro-PEP: str.translate(None) to mean identity translation

2005-04-29 Thread Bengt Richter
Just thought None as the first argument would be both handy and mnemonic, signifying no translation, but allowing easy expression of deleting characters, e.g., s = s.translate(None, 'badcharshere') Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: module exports a property instead of a class -- Evil?

2005-04-29 Thread Bengt Richter
-> False 0 False True True Exception AttributeError: Legal names are: 'started', 'done', 'on_hold' -- not 'fini' 1 names: ['one', 'two', 'three'] 1 current: two 1 .one? -> False .two? -> True .three? -> False 1 ==one? -> False ==two? -> True ==three? -> False 1 >one? -> True >two? -> False >three? -> False 1 False False True Exception AttributeError: Legal names are: 'one', 'two', 'three' -- not 'fini' 2 names: ['UNK', 'running', 'stopped'] 2 current: stopped 2 .UNK? -> False .running? -> False .stopped? -> True 2 ==UNK? -> False ==running? -> False ==stopped? -> True 2 >UNK? -> True >running? -> True >stopped? -> False 2 False False False Exception AttributeError: Legal names are: 'UNK', 'running', 'stopped' -- not 'fini' Exception ValueError: 'this$' is not a valid name Exception ValueError: 'an#d' is not a valid name Exception ValueError: 'with space' is not a valid name Exception ValueError: '4digitstart' is not a valid name Exception ValueError: 'bad\x00' is not a valid name Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

Re: Micro-PEP: str.translate(None) to mean identity translation

2005-04-30 Thread Bengt Richter
On 29 Apr 2005 21:27:18 -0700, "M.E.Farmer" <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> Just thought None as the first argument would be both handy and >mnemonic, >> signifying no translation, but allowing easy expression of deleting >characters, &

Re: Sorting an Edge List

2005-04-30 Thread Bengt Richter
.append(curr) seen.add(curr) curr = nodes.get(curr[1]) if curr is None: break if sub: out.append(sub) return out if __name__ == '__main__': edges = set([('A','Y'), ('J','A'), ('Y

Re: Micro-PEP: str.translate(None) to mean identity translation

2005-04-30 Thread Bengt Richter
On Sat, 30 Apr 2005 08:44:21 GMT, "Raymond Hettinger" <[EMAIL PROTECTED]> wrote: >[Bengt Richter] >> Just thought None as the first argument would be both handy and mnemonic, >> signifying no translation, but allowing easy expression of deleting >characters, >

Re: slice notation as values?

2005-12-10 Thread Bengt Richter
erate in the >> first place. So eager to learn something new, how do you do this >> quite easily? > >>>> lst = ['ham','eggs','bacon','spam','foo','bar','baz'] >>>> list(enumerate(lst))[::2] >

Re: Proposal: Inline Import

2005-12-10 Thread Bengt Richter
accessible as builtins. > >Thoughts? > There are special caveats re imports in threads, but otherwise I don't know of any significant downsides to importing at various points of need in the code. The actual import is only done the first time, so it's effectively just a lookup in sys.modules from there on. Am I missing something? Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list

<    3   4   5   6   7   8   9   10   >