Re: Need some simple coding help

2005-03-02 Thread Steven Bethard
mx2k wrote: ah, and sorry for that 'unreadable' code, but that was our first try of coding ever. we're working through the python documentaion right now - and - thanks to the post by STeVe we at last now that we have to construct a class for our purpose. Well, you don't *have* to -- it could be don

Re: yield_all needed in Python

2005-03-02 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] My suspicion is that if he doesn't like the * syntax when there's a close parallel to the argument parsing usage, he's not likely to like it when there isn't on

Re: passing lists

2005-03-02 Thread Steven Bethard
Earl Eiland wrote: def Match(..., Raw_packet_queue, ...): ... print 'in Match, Raw_Packet_queue is', Raw_packet_queue # this returns 'Reader object at 0xaaa' ... return [Last_Passed, Last_Dropped, Raw_packet_queue] # this causes 'unsubscriptable object'error message

Re: What is the best way to handle a command line argument that includes an escape sequence like \n?

2005-03-02 Thread Steven Bethard
Joe wrote: It appears that Python treats the comand line string as a raw string. what is the best way to work around the issue? You probably want to use str.decode with the encoding 'string_escape'[1] py> s = r'\n\t' py> s '\\n\\t' py> s.decode('string_escape') '\n\t' STeVe [1]http://docs.python.or

Re: Multiline regex help

2005-03-03 Thread Steven Bethard
Yatima wrote: Hey Folks, I've got some info in a bunch of files that kind of looks like so: Gibberish 53 MoreGarbage 12 RelevantInfo1 10/10/04 NothingImportant ThisDoesNotMatter 44 RelevantInfo2 22 BlahBlah 343 RelevantInfo3 23 Hubris Crap 34 and so on... Anyhow, these "fields" repeat several times

replacing builtins (WAS: Regular Expressions: large amount of or's)

2005-03-03 Thread Steven Bethard
Manlio Perillo wrote: > Python allows to subclass builtin classes but the Python Interpreter > uses builtin types. > As an example keyword arguments are inserted in a dict but I would > like to use an user defined SortedDict. > > There are plans to add such a feature in a future version? Note that

Re: Multiline regex help

2005-03-03 Thread Steven Bethard
Yatima wrote: On Thu, 03 Mar 2005 09:54:02 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: A possible solution, using the re module: py> s = """\ ... Gibberish ... 53 ... MoreGarbage ... 12 ... RelevantInfo1 ... 10/10/04 ... NothingImportant ... ThisDoesNotMatter ... 44

Re: Multiline regex help

2005-03-03 Thread Steven Bethard
Kent Johnson wrote: for line in raw_data: if line.startswith('RelevantInfo1'): info1 = raw_data.next().strip() elif line.startswith('RelevantInfo2'): info2 = raw_data.next().strip() elif line.startswith('RelevantInfo3'): info3 = raw_data.next().strip() sc

Re: There's GOT to be a better way!

2005-03-03 Thread Steven Bethard
Earl Eiland wrote: module.py def A(): test = 1 for x in range(10): B() def B(): test = test + 1 main.py import module module.A() This will fail, unless test is passed and returned. (Sorry if this sent twice. I

Re: How would you program this?

2005-03-03 Thread Steven Bethard
engsol wrote: I don't fully understand this line of your code: return [(a,b,c) for a in ns for b in ns for c in ns if a + b + c == limit] If the "if" part is true, does it 'trigger' the return? This code is basically equivalent to: lc = [] for a in ns: for b in ns: for c in ns:

Re: Initializing subclasses of tuple

2005-03-03 Thread Steven Bethard
Nick Coghlan wrote: Any volunteers out there willing to put some words about __new__ together for the main Python docs, please consider posting them on SF :) Done. http://sourceforge.net/tracker/?func=detail&aid=1156412&group_id=5470&atid=105470 STeVe -- http://mail.python.org/mailman/listinfo/pyt

Re: Wishful thinking : unix to windows script?

2005-03-04 Thread Steven Bethard
Grant Edwards wrote: On 2005-03-04, Patrick Useldinger <[EMAIL PROTECTED]> wrote: John Leslie wrote: Or does anyone have a python script which takes a standard unix command as an argument and runs the pyton/windows equivalent on windows? There's not always an equivalent command. If you install cy

Re: Geneator/Iterator Nesting Problem - Any Ideas? 2.4

2005-03-04 Thread Steven Bethard
ChaosKCW wrote: For reasons of pure asthetics and my own learning I wanted it to look like this: def resultsetbatchgen(cursor, size=100): for results in (recordbatch for recordbatch in cursor.fetchmany(size)): for rec in results: yield rec Note that this is equivalent to:

Re: __contains__ inconsistencies between Python 2.2 and 2.3

2005-03-04 Thread Steven Bethard
Anand S Bisen wrote: For example (Python 2.3) >> x="Hello World" >> print x.__contains__("Hello") True (Python 2.2) >>> x="Hello world" >>> print x.__contains__("Hello") Traceback (most recent call last): File "", line 1, in ? TypeError: 'in ' requires character as left operand Is there any wo

Re: Wrong with this script?

2005-03-05 Thread Steven Bethard
R.Meijer wrote: Hi, I've been busy with an experimental script, and I can't seem to see what is wrong with it, can somebody tell me? For future notice, it's useful to (1) explain what it is you want your script to do, and (2) explain what it currently does (including an exception traceback if one

Re: GOTO (was Re: Appeal for python developers)

2005-03-05 Thread Steven Bethard
Dennis Lee Bieber wrote: On 5 Mar 2005 08:00:23 -0800, [EMAIL PROTECTED] declaimed the following in comp.lang.python: "explicit GOTO"'. Goto's are less dangerous when they are in the forward direction, to code appearing later. UGH... That is the one direction I always avoid (in FORTRAN 77). Typica

Re: How do I import everything in a subdir?

2005-03-06 Thread Steven Bethard
YL wrote: Try something like this: for x in plugs: cmd = "import %s" % x exec (cmd) For the sake of others who might have missed the rest of this thread, I'll point out that this is definitely not the way to go. No need to use exec when the builtin __import__ function is alre

Re: Possible to import a module whose name is contained in a variable?

2005-03-06 Thread Steven Bethard
Steven Reddie wrote: MODULES = [ 'module1', 'module2' ] def libinfo(): for m in MODULES: __import__('libinfo.'+m) m.libinfo() CFLAGS+=m.CFLAGS Does this do what you want? -- libinfo/__ini

Re: Possible to import a module whose name is contained in a variable?

2005-03-06 Thread Steven Bethard
Claudio Grondi wrote: "Steven Reddie" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] I want to do something like the following, which doesn't work: modulename = 'module' import modulename The error is that there is no module named 'modulename'. Is there a way to get that v

Re: Python 2.4 removes None data type?

2005-03-07 Thread Steven Bethard
Warren Postma wrote: Michael Hoffman wrote: The fact that True and False are not constants? Yowza. a = True b = False False = a True = b if (1==2)==True: print "Doom" Why stop there when you can really cause some doom: py> import __builtin__ as bltin py> bltin.True, bltin.False = bltin.False, b

Re: shuffle the lines of a large file

2005-03-07 Thread Steven Bethard
Joerg Schuster wrote: Thanks to all. This thread shows again that Python's best feature is comp.lang.python. +1 QOTW STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: Dictionaries of Lists

2005-03-07 Thread Steven Bethard
Tony Meyer wrote: [a for a in list] (or a[:]) makes a copy of a list. or list(a) STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: parameter name conflict. How to solve?

2005-03-07 Thread Steven Bethard
Bo Peng wrote: Dear list, If you ask: why do you choose these names? The answer is: they need to be conformable with other functions, parameter names. I have a function that pretty much like: def output(output=''): print output and now in another function, I need to call output function, with a

Re: looking for way to include many times some .py code from anotherpython code

2005-03-08 Thread Steven Bethard
Martin MOKREJŠ wrote: The data passed to an instance come from sql tables. I have the idea every table will be represented by an object. Have you looked at SQLObject? I've never used it, but it does seem like this is the sort of thing it was designed for: http://sqlobject.org/ STeVe -- http://ma

Re: python -i (interactive environment)

2005-03-08 Thread Steven Bethard
Joe wrote: Isn't this a bug? Here's the test program: import code def test_func(): lv = 1 print '\n\nBEFORE lv: %s\n' % (lv) code.interact(local=locals()) print '\n\nAFTER lv: %s\n' % (lv) return Check the documentation for locals() [1]: "Update and return a dictionary represen

Re: python -i (interactive environment)

2005-03-08 Thread Steven Bethard
Joe wrote: Thanks, I knew about that but my question is why is it not working consistently? At the module level, locals() is globals(): py> locals() is globals() True And the globals() dict is modifiable. HTH, STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: Sorting dictionary by 'sub' value

2005-03-08 Thread Steven Bethard
Rory Campbell-Lange wrote: Thank you all very much for your help. I did the following and it works: imgs=v.keys() imgs.sort(lambda a,b: cmp( time.strptime(str(v[a][9]['date']), '%Y:%m:%d %H:%M:%S'), time.strptime(str(v[b][9]['date']), '%Y:%m:%d %H:%M:%S'))

Re: None in string formatting

2005-03-08 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Was doing some string formatting, noticed the following: x = None "%s" % x 'None' Is there a reason it maps to 'None'? I had expected ''. Can you explain why you expected that? A few other examples that make me not expect what you do: py> '%s' % False 'False' py> '%s' %

Re: looking for way to include many times some .py code fromanotherpython code

2005-03-08 Thread Steven Bethard
Martin MOKREJŠ wrote: Basically, doing in a class method def(self, a, b, c): self.a = a self.b = b self.c = c sounds stupid. With next instance I'll loose a, b, c, so I have to save then to a variable, "self." prefix is generally proposed way. But it's not surprising a gets to self.a, righ

Re: Best way to make a list unique?

2005-03-08 Thread Steven Bethard
Delaney, Timothy C (Timothy) wrote: This is actually one thing that Java 1.5 has that I'd like to see in Python - the LinkedHashSet and LinkedHashMap. Very useful data structures. For those who don't know, these implement a hash set/map which iterates in the order that the keys were first added to

Re: Defining __getitem__() in a class that inherits from (dict)

2005-03-08 Thread Steven Bethard
Michael Hoffman wrote: Tobiah wrote: If within the __getitem__ method I attempt to get an item from self, the __getitem__ method is called in an infinite recursion. You need to explicitly use dict.__getitem__(self, key) instead of using self[key] directly. or super(bar, self).__getitem__(key) STeVe

Re: function namespaces

2005-03-08 Thread Steven Bethard
Darren Dale wrote: Hi, I have a variable saved in a file like this #contents of myfile.py: testvar = [1,2,3,4] and I am trying to write a function that does something like this: def myfunction(filename): execfile(filename) print testvar The problem I am running into is that the glob

Re: running programs from within python

2005-03-09 Thread Steven Bethard
M.N.A.Smadi wrote: M.N.A.Smadi wrote: hi; in general: how can i pass a string containing a concatenated sequcne of command line arguments to a unix system CLI? i guess i will answer myself: import os os.system(string) Also worth noting is that if you're using Python 2.4, you might want to look a

Re: running programs from within python

2005-03-09 Thread Steven Bethard
M.N.A.Smadi wrote: am getting an error in the script as follows: NameError: global name 'os' is not defined however i dont get the same error when running from the python CLI. (and yes i am importing the os module) Can you give the full exception message (i.e. copy-paste it from the output)? STe

Re: running programs from within python

2005-03-09 Thread Steven Bethard
M.N.A.Smadi wrote: > am getting an error in the script as follows: > > NameError: global name 'os' is not defined > > however i dont get the same error when running from the python CLI. > (and yes i am importing the os module) > Steven Bethard wrote: > Can you gi

Re: Problematic behavior of the import statement when several module files have the same name.

2005-03-09 Thread Steven Bethard
Xif wrote: Hello Everyone! Here's a problem with relative imports: Suppose I have a package called some_package (in a separate directory included in the PYTHONPATH, with an __init__.py file etc.) This package has a module inside the directory, called "database", and therefore residing in the file

Re: Is there a short-circuiting dictionary "get" method?

2005-03-09 Thread Steven Bethard
Bill Mill wrote: On 9 Mar 2005 10:05:21 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: Maybe this can help: value = d.get('x', lambda: bigscaryfunction()) def test(): print 'gbye' ... d = {} z = d.get('x', lambda: test()) z at 0x008D6870> So this seems to be merely an obfuscation of: z = d.g

Re: Second argument to super().

2005-03-09 Thread Steven Bethard
Tobiah wrote: What is the purpose of the second argument to super()? You probably want to check the docs[1] again. They give an example: class C(B): def meth(self, arg): super(C, self).meth(arg) What is meant by the returning of an 'unbound' object when the argument is omitted. If you

Re: popen2.Popen3 doesn't work well for me

2005-03-09 Thread Steven Bethard
alexrait1 wrote: It does but that's not what I want. I need a class which I can query for process termination for instance... Is there a way to overcome this problem with Popen3? If you're using Python 2.4 you should look into the subprocess module. I think these docs might be what you're looking

Re: PEP 309 (Partial Function Application) Idea

2005-03-11 Thread Steven Bethard
Chris Perkins wrote: Random idea of the day: How about having syntax support for currying/partial function application, like this: func(..., a, b) func(a, ..., b) func(a, b, ...) That is: 1) Make an Ellipsis literal legal syntax in an argument list. 2) Have the compiler recognize the Ellipsis liter

Re: how to absolute import?

2005-03-11 Thread Steven Bethard
Qiangning Hong wrote: From Guido's PEP8: - Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Does it mean I should put my develop directory into PYTHONPATH (e.g. /home/hongqn/devel/python) and use "import mypr

Re: head for grouped data - looking for best practice

2005-03-12 Thread Steven Bethard
Harald Massa wrote: def getdoublekey(row): return row[0:2] for key, bereich in groupby(eingabe,getdoublekey): print "Area:",key for data in bereich: print "--data--", data[2:] Why don't you just pass a slice to itemgetter? py> eingabe=[ ... ("Stuttgart","70197","Fernsehturm","20

Re: Add Properties to Instances?

2005-03-12 Thread Steven Bethard
Martin Miller wrote: I'm trying to create some read-only instance specific properties, but the following attempt didn't work: class Foobar(object): pass foobar = Foobar() foobar.x = property(fget=lambda: 42) print "foobar.x:", foobar.x [snip] Can anyone tell me what's wrong with this approach

Re: Generating data types automatically

2005-03-12 Thread Steven Bethard
Torsten Bronger wrote: Okay this works: def generate_type_dublett(visa_type, ctypes_type): return visa_type + "=" + ctypes_type + ";" + \ "ViP" + visa_type[2:] + "=POINTER(" + visa_type + ")" def generate_type_triplett(visa_type, ctypes_type): return generate_type_dublett(visa_type,

wishlist item: itertools.partition (WAS: Wishlist item: itertools.flatten)

2005-03-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: > window / cons / fencepost / slice functions: +1 > > (with a flag to say if you want to truncate or pad incomplete tuples > at end of input sequence. > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recip

Re: PEP 309 (Partial Function Application) Idea

2005-03-12 Thread Steven Bethard
Chris Perkins wrote: [snip implementation] While I think that func(x, ...) is more readable than partial(func, x), I'm not sure that I would use either of them often enough to warrant special syntax. Interesting. Thought it might be worth listing a few of the current places people use lambdas (an

Re: dinamically altering a function

2005-03-12 Thread Steven Bethard
vegetax wrote: I i need a decorator that adds a local variable in the function it decorates, probably related with nested scopes, for example: def dec(func): def wrapper(obj = None): if not obj : obj = Obj() return func() return wrapper() @dec() def fun(b): obj.desc = 'marke

Re: dinamically altering a function

2005-03-12 Thread Steven Bethard
vegetax wrote: Steven Bethard wrote: Have you considered using OO here? You might find that this is more easily written as: py> class Object(object): ... pass ... py> class fun(object): ... def __new__(self, *args): ... if len(args) == 2: ... obj, b

Re: Itertools wishlists

2005-03-14 Thread Steven Bethard
Ville Vainio wrote: A simpler API: def flatten(sequence, atomic_test = lambda o: isinstance(o,basestring)): """ don't recurse into iterables if atomic_test -> True """ Yes, this is also the API I would have suggested. Simple, but flexible enough to handle the odd cases with the occasional user-

Re: optparse alternative

2005-03-14 Thread Steven Bethard
Henry Ludemann wrote: I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. Looks interesting, but is it really that different from optparse? I do like the fact that you can specify a type with a conversion function. (In optparse

Re: optparse alternative

2005-03-14 Thread Steven Bethard
Henry Ludemann wrote: I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. Some more detailed comments: * The more I think about it, the more I like that you're basically constructing options to match a function signature. But I

super with only one argument

2005-03-14 Thread Steven Bethard
When would you call super with only one argument? The only examples I can find of doing this are in the test suite for super. Playing around with it: py> class A(object): ... x = 'a' ... py> class B(A): ... x = 'b' ... py> s = super(B) py> s.x Traceback (most recent call last): File

Re: Itertools wishlists

2005-03-14 Thread Steven Bethard
Robert Brewer wrote: Steven Bethard wrote: Ville Vainio wrote: A simpler API: def flatten(sequence, atomic_test = lambda o: isinstance(o,basestring)): """ don't recurse into iterables if atomic_test -> True """ Yes, this is also the API I would have sugge

Re: command line args

2005-03-14 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Hello, I have the following commands: testb -s testb -s -o testb -s -o How do i split the commands so that all three are valid. And how do i check for missing arguments? Use optparse. It's an improvement over the old getopt that makes writing option parsers easy:

Re: Python-list Digest, Vol 18, Issue 208

2005-03-14 Thread Steven Bethard
Jeff Shannon wrote: John Roth wrote: That's a reason, but I don't consider it a good reason. I cannot, in fact, think of a single time when I've wanted to enter an octal number. Hex numbers, yes, but not octal. [snip] I would agree with you, but it's there for historical reasons. [snip] now that a

Re: Python becoming less Lisp-like

2005-03-14 Thread Steven Bethard
Torsten Bronger wrote: the underlying constructs are utterly ugly, as are some of Python's features (e.g. __getattr__ and such, and decorators, in order to get nice class properties). What do you find ugly about __getattr__? I looked for a new language for my hobby programming. [snip] I want to go

Re: Second argument to super().

2005-03-14 Thread Steven Bethard
Steve Holden wrote: John Roth wrote: What happens with the second operand is a bit of sleight of hand. The object returned from super() gives you access to the methods on the next level up the mro, however when you use it to invoke a method, then the 'self' passed to that method is the second objec

RuntimeError: restricted attribute

2005-03-14 Thread Steven Bethard
Does anyone know where the documentation for "restricted environments" is? I see this referred to in the documentation for eval[1], but not explained. Does eval use rexec? I thought that was deprecated, but I get the following error: py> eval('sub.func_globals', dict(__builtins__=None, ...

Re: __getitem__ method on (meta)classes

2005-03-14 Thread Steven Bethard
Ron Garret wrote: What I'm really trying to do is to create enumerated types such that if: e1 = enum(lst) and v = e1(x) then (x in lst) and (e1[v] == x) Use a class with __call__ and __getitem__: py> class enum(object): ... def __init__(self, vals): ... self.vals = vals ... def __ca

Re: __getitem__ method on (meta)classes

2005-03-14 Thread Steven Bethard
Ron Garret wrote: And the code I ended up with is: # Inheriting from type, not object, is the key: class enum_metaclass(type): def __getitem__(self, index): return self.vals[index] def enum(vals): class enum(object): __metaclass__ = enum_metaclass def __init__(self, val): try:

Re: Python becoming less Lisp-like

2005-03-15 Thread Steven Bethard
Torsten Bronger wrote: [EMAIL PROTECTED] (Paul Boddie) writes: Well, I've been using Python for almost ten years, and I've managed to deliberately ignore descriptors and metaclasses quite successfully. I get the impression that descriptors in particular are a detail of the low-level implementation

Re: Turning String into Numerical Equation

2005-03-15 Thread Steven Bethard
Michael Spencer wrote: Giovanni Bajo wrote: I use something along these lines: def safe_eval(expr, symbols={}): return eval(expr, dict(__builtins__=None, True=True, False=False), symbols) import math def calc(expr): return safe_eval(expr, vars(math)) That offers only notional security: >

Re: Turning String into Numerical Equation

2005-03-15 Thread Steven Bethard
Steven Bethard wrote: Yeah, I was concerned about the same thing, but I realized that I can't actually access any of the func_globals attributes: py> eval('(1).__class__.mro()[-1].__subclasses__()[17]' ... '.substitute.func_globals', dict(__builtins__=None)) Trac

Re: __getitem__ method on (meta)classes

2005-03-15 Thread Steven Bethard
Ron Garret wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: Ron Garret wrote: What I'm really trying to do is to create enumerated types such that if: e1 = enum(lst) and v = e1(x) then (x in lst) and (e1[v] == x) Use a class with __call__ and __get

Re: Python-list Digest, Vol 18, Issue 208

2005-03-15 Thread Steven Bethard
Reinhold Birkenfeld wrote: So what's the current state of the "universal-base-prefix" syntax? Something like 10x10, 16xA and 8x12? An interesting thought -- I like the consistency. On the other hand, I have a hard time imagining that this is such a common need that it requires syntactic support.

Re: Python becoming less Lisp-like

2005-03-15 Thread Steven Bethard
Bruno Desthuilliers wrote: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. When was the last time you used Java? It has no support for using classes as callable objects. __call__ would have t

Re: Python becoming less Lisp-like

2005-03-15 Thread Steven Bethard
Kent Johnson wrote: Steven Bethard wrote: Bruno Desthuilliers wrote: class CommandMenuSelectionCallback: def __init__(self, key): self.key = key def __call__(self): print self.key Looks like Java. When was the last time you used Java? It has no support for using classes

Re: Turning String into Numerical Equation

2005-03-15 Thread Steven Bethard
Giovanni Bajo wrote: When __builtin__ is not the standard __builtin__, Python is in restricted execution mode. Do you know where this is documented? I looked around, but couldn't find anything. STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: Python Debug logging

2005-03-15 Thread Steven Bethard
gf gf wrote: Is there a simple way to log to a debug console in Python? Don't know exactly what you want, but you should check out the logging module: http://docs.python.org/lib/minimal-example.html STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: code for Computer Language Shootout

2005-03-15 Thread Steven Bethard
Jacob Lee wrote: There are a bunch of new tests up at shootout.alioth.debian.org for which Python does not yet have code. I've taken a crack at one of them, a task to print the reverse complement of a gene transcription. Since there are a lot of minds on this newsgroup that are much better at optim

Re: how to read a tab delimited file

2005-03-15 Thread Steven Bethard
> Peter Hansen wrote: > >>jrlen balane wrote: >> >>>how would i read a tab delimited file? at the same time put what i >>>read in an array, say for example that i know that the file is an >>>array with column= 5 and row=unknown. >> >>Use the "csv" module. Although that stands for "comma >>separate

Re: code for Computer Language Shootout

2005-03-15 Thread Steven Bethard
Jacob Lee wrote: So here's a tentative contest version of the code: import sys import string def show(seq, table=string.maketrans('ACBDGHK\nMNSRUTWVYacbdghkmnsrutwvy', 'TGVHCDM\nKNSYAAWBRTGVHCDMKNSYAAWBR')): seq = seq.translate(table)[::-1] for i in ra

Re: __getitem__ method on (meta)classes

2005-03-16 Thread Steven Bethard
Ron Garret wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: Yeah, except I actually left out one thing: I also want type(v)==e1. Why? In Python usually you rely on duck-typing and not explicit type checks. What is it that you're trying to gain

Re: __getitem__ method on (meta)classes

2005-03-16 Thread Steven Bethard
Steven Bethard wrote: py> class enum(object): ... class item(object): ... def __init__(self, val): ... self.val = val ... def __repr__(self): ... return 'enum.item(%r)' % self.val ... def __init__(self, vals): ... self.items

Re: Turning String into Numerical Equation

2005-03-16 Thread Steven Bethard
Giovanni Bajo wrote: In fact, the documentation for eval() could be improved to explain the benefits of setting __builtins__ in the globals. Well, if you think you're pretty clear on what's happening, a patch is always appreciated. =) I have a feeling that the docs are at least partially vague b

Re: Getting current variable name

2005-03-16 Thread Steven Bethard
pl wrote: I followed the mails entitled 'How to turn a variable name into a string?' in march 2005 posts as I have a similar problem. I have to get some list variable names at some point in my program. So I ended up looking into globals() to get them with a small function like this: #!/usr/bin/pyth

Re: computing a weighted sum

2005-03-16 Thread Steven Bethard
Will McGugan wrote: In Python 2.3 sum( [ _x * _w for _x, _w in zip( x, w ) ] ) or in 2.4 sum( _x * _w for _x, _w in zip( x, w ) ) Any reason for the leading underscores? If you're trying to avoid polluting your namespace, you should note that generator expressions don't leak their loop variables

Re: Why tuple with one item is no tuple

2005-03-16 Thread Steven Bethard
Daniel Dittmar wrote: But what the heck, I find list comprehension rather awful. Sacrilege! ;) STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: Mark attribute as read-only

2005-03-16 Thread Steven Bethard
Florian Lindner wrote: how can I mark a attribute of a class as read-only (for non classmembers)? Yes, stupid question, but the docu gave me no help. Declare it as such in the documentation. ;) If you want to provide error messages, you could alternatively define a property: py> class C(object):

Re: __getitem__ method on (meta)classes

2005-03-16 Thread Steven Bethard
Ron Garret wrote: Using a metaclass allows you to distinguish Fred the plumber from Fred the electrician. But that may or may not be what one actually wants. Not sure what you mean here. The non metaclass solution still has separate enum.item objects for each new enum. Consider your implementa

Re: code for Computer Language Shootout

2005-03-16 Thread Steven Bethard
Michael Spencer wrote: def output(seq, linelength = 60): if seq: iterseq = iter(seq) while iterseq: print "".join(islice(iterseq,linelength)) Worth noting: "while iterseq" only works because for this case, you have a list iterator, which provides a __len__ method.

Re: Turning String into Numerical Equation

2005-03-16 Thread Steven Bethard
Giovanni Bajo wrote: Then, I should start my usual rant about how is really sad to send patches to Python and have them ignored for years (not even an acknowledge). Really sad. This is why I'm not going to do that again. I don't know the last time you read python-dev, but a number of the senior Py

Re: list of unique non-subset sets

2005-03-17 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Hi, I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactly the same members. Tried to do th

Re: list of unique non-subset sets

2005-03-17 Thread Steven Bethard
Kent Johnson wrote: Raymond Hettinger wrote: [EMAIL PROTECTED] I have many set objects some of which can contain same group of object while others can be subset of the other. Given a list of sets, I need to get a list of unique sets such that non of the set is an subset of another or contain exactl

Re: Why tuple with one item is no tuple

2005-03-18 Thread Steven Bethard
Kay Schluehr wrote: On the other hand i find Mathematicas list operators very appealing: In =: [1,2,3]^2 Out=: [1,4,9] Compared with this suggar the list comprehension [x**2 for x in [1,2,3]] is ugly. py> import numarray py> a = numarray.array([1, 2, 3]) py> a**2 array([1, 4, 9]) STeVe -- http://ma

Re: slicing, mapping types, ellipsis etc.

2004-11-29 Thread Steven Bethard
Jerry Sievers wrote: 1. what the Ellipsis object or ... syntax is used for 2. what a slice [..., j:k:l] does My understanding is that the Ellipsis object is intended primarily for Numeric/numarray use. Take a look at: http://stsdas.stsci.edu/numarray/numarray-1.1.html/node26.html 3. how slices a

pre-PEP generic objects

2004-11-29 Thread Steven Bethard
Thanks! Steve -- Title: Generic Object Data Type Version: $Revision: 1.0 $ Last-Modified: $Date: 2004/11/29 16:00:00 $ Author: Steven Bethard <[EMAIL PROTECTED]> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Nov-2004 Python-Version: 2.5

documentation for PyArg_ParseTupleAndKeywords

2004-11-29 Thread Steven Bethard
I'm just starting to play around with the Python source. (Specifically, I'm looking at adding a key argument to max/min like sorted has.) Can anyone direct me to the documentation on how PyArg_ParseTupleAndKeywords, etc. work? In particular, I can't figure out how the format arg to vgetargsk

keyword argument for min/max

2004-11-29 Thread Steven Bethard
So I've been playing around with trying to add a keyword argument to min and max that works similarly to the one for sorted. It wasn't too hard actually, but it does raise a few questions about proper handling of keyword arguments. Currently, help(max) gives: max(...) max(sequence) -> val

Python code and C code in the same module?

2004-11-29 Thread Steven Bethard
I'd like to merge a module written in C with a module written in Python so that the user can access objects from either module by importing the single, merged module. Specifically, I'm looking at the collections module, which is written in C, and my Bunch object, which is written in Python. I'

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: Currently, if a Python programmer makes this design decision, they are forced to declare a new class, and then build instances of this class. FORCED to create a new class, and FORCED to create instances of their own class instead of your class? I don&#

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Peter Otten wrote: Steven Bethard wrote: def __eq__(self, other): """x.__eq__(y) <==> x == y""" return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) This results in an asymmetry: [snip] Whether this is intended, I don

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Nick Craig-Wood wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). A

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Nick Coghlan wrote: The proposed use cases sound more appropriate for a "named tuple" than any sort of dictionary. (This may have been mentioned in previous discussions. I wasn't keeping track of those, though) For the return values, yeah, a "named tuple" is probably at least as appropriate. I'

Re: documentation for PyArg_ParseTupleAndKeywords

2004-11-30 Thread Steven Bethard
John Machin wrote: Well I just fired up the doco gadget and pasted "PyArg_ParseTupleAndKeywords" into the Search box and the 2nd reference it came up with was this: manual: Python/C API Reference Manual section: 5.5 Parsing arguments and building values The 1st, 3rd & 4th references were examples

Re: keyword argument for min/max

2004-11-30 Thread Steven Bethard
Steven Bethard wrote: So I've been playing around with trying to add a keyword argument to min and max that works similarly to the one for sorted. It wasn't too hard actually, but it does raise a few questions about proper handling of keyword arguments. Sorry to reply to my own p

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Scott David Daniels wrote: Nick Craig-Wood wrote: class Hash: def __init__(self, **kwargs): for key,value in kwargs.items(): setattr(self, key, value) def __getitem__(self, x): return getattr(self, x) def __setitem__(self, x, y): setattr(self, x, y)

PyArg_ParseKeywords?

2004-11-30 Thread Steven Bethard
Is there a PyArg_ParseKeywords along the lines of PyArg_ParseTupleAndKeywords? I want to parse only the keywords, ignoring the arguments. Currently I do this with something like: const char *format = "O:min"; static char *kwlist[] = {"key", 0}; PyObject *empty_args = Py_BuildValue("()"); if (!

Re: pre-PEP generic objects

2004-11-30 Thread Steven Bethard
Jp Calderone wrote: One thing I notice with both of these versions: >>> Hash(self=10) Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() got multiple values for keyword argument 'self' Good call. I've adjusted my methods to look like: def __init_

assymetry between a == b and a.__eq__(b) (WAS: pre-PEP generic objects)

2004-12-01 Thread Steven Bethard
Peter Otten wrote: Steven Bethard wrote: def __eq__(self, other): """x.__eq__(y) <==> x == y""" return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) This results in an asymmetry: from bunch import Bunch class B(Bunch)

<    1   2   3   4   5   6   7   8   9   10   >