Re: newbie question: how to get the class instance given a module object?

2005-03-27 Thread Steven Bethard
Tian wrote: import ModuleA classname = "Dog" module = globals()["ModuleA"] classobj = ??? <---using classname instanct = classobj() classobj = getattr(module, classname) STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: save configuration information in a global class

2005-03-27 Thread Steven Bethard
Su Wei <[EMAIL PROTECTED]> wrote: > if i want to make a global class to save configuration information of > app that is read from a xml file,what can i do? Just put it in a module. Say, 'progconfig.py'. Your configuration code can then look like: import progconfig # parse configuration informat

Re: save configuration information in a global class

2005-03-27 Thread Steven Bethard
Su Wei <[EMAIL PROTECTED]> wrote: > if i have a xml file like this: > > > > > > i want to save this information,and used by other moduls later. > > how should i do it? ths First you need an xml library. There's one built into Python, but ElementTree is a simpler one: http://effbot.o

itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-28 Thread Steven Bethard
Jack Diederich wrote: > > itertools to iter transition, huh? I slipped that one in, I mentioned > it to Raymond at PyCon and he didn't flinch. It would be nice not to > have to sprinkle 'import itertools as it' in code. iter could also > become a type wrapper instead of a function, so an iter in

Re: String Splitter Brain Teaser

2005-03-28 Thread Steven Bethard
Michael Spencer wrote: def xgen(s): srciter = iter(s) item = [srciter.next()] for i in srciter: if i == '/': item.append(srciter.next()) else: yield item item = [i] yield item Note that the generator-based solution doesn't generate

Re: Calling __init__ with multiple inheritance

2005-03-28 Thread Steven Bethard
Axel Straschil wrote: I came to the following: For single inheritance, super is a nice tool if you will recfactoring the class later. For multiple inheritance, if you want to use super, you have to have very much knowledge of the classes you inheritance. And for multiple inheritance, if you don't

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Steven Bethard
Ville Vainio wrote: "Raymond" == Raymond Hettinger <[EMAIL PROTECTED]> writes: Raymond> If the experience works out, then all you're left with is Raymond> the trivial matter of convincing Guido that function Raymond> attributes are a sure cure for the burden of typing Raymond> impo

Re: Finding attributes in a list

2005-03-29 Thread Steven Bethard
infidel wrote: You can use the new 'sorted' built-in function and custom "compare" functions to return lists of players sorted according to any criteria: players = [ ... {'name' : 'joe', 'defense' : 8, 'attacking' : 5, 'midfield' : 6, 'goalkeeping' : 9}, ... {'name' : 'bob', 'defense'

automatically mapping builtins (WAS: itertools to iter transition)

2005-03-29 Thread Steven Bethard
Michael Spencer wrote: > While we're on the topic, what do you think of having unary, > non-summary builtins automatically map themselves when called with an > iterable that would otherwise be an illegal argument: > > e.g., > int(iterable) -> (int(i) for i in iterable) > ord(iterable) -> (ord(i) fo

Re: How to use "__new__"?

2005-03-29 Thread Steven Bethard
could ildg wrote: As there is already __init__, why need a __new__? What can __new__ give us while __init__ can't? In what situations we should use __new__? And in what situations we must use __new__? Can __new__ take the place of __init__? I believe the current documentation will be updated when 2

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Steven Bethard
Terry Reedy wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] True it's not a huge win. But I'd argue that for the same reasons that dict.fromkeys is a dict classmethod, the itertools methods could be iter classmethods (or staticme

Re: Weakrefs to classes that derive from str

2005-03-29 Thread Steven Bethard
Ron Garret wrote: Why doesn't this work? from weakref import ref class C(str): pass ... ref(C()) Traceback (most recent call last): File "", line 1, in ? TypeError: cannot create weak reference to 'C' object Note that you don't need the class redirection: py> ref('') Traceback (most recent call

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-29 Thread Steven Bethard
Terry Reedy wrote: But if classmethods are intended to provide alternate constructors But I do not remember that being given as a reason for classmethod(). But I am not sure what was. Well I haven't searched thoroughly, but I know one place that it's referenced is in descrintro[1]: "Factoid: __

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-30 Thread Steven Bethard
Ville Vainio wrote: The issue that really bothers me here is bloating the builtin space. We already have an uncomfortable amount of builtin functions. Of course the additions that have been suggested would not pollute the builtin namespace, but they would still be there, taking space. I'd rather se

Re: Weakrefs to classes that derive from str

2005-03-30 Thread Steven Bethard
Ron Garret wrote: Note that you don't need the class redirection: py> ref('') Traceback (most recent call last): File "", line 1, in ? TypeError: cannot create weak reference to 'str' object But I don't know why strings aren't valid arguments to ref... None of the native types (int, float, list,

Re: itertools to iter transition (WAS: Pre-PEP: Dictionary accumulator methods)

2005-03-30 Thread Steven Bethard
Ville Vainio wrote: A minimal set would not be that offensive, yes. But then we would have two places to look for itertools functionality, which may not be desirable. True, though this is currently necessary with str objects if you want to use, say string.maketrans, so it's not without some prece

Re: Weakrefs to classes that derive from str

2005-03-30 Thread Steven Bethard
Peter Hansen wrote: I believe it's here: http://docs.python.org/lib/module-weakref.html if you search for the string "Not all" and read the next two paragraphs. On the other hand, it says (there) only that "several builtin types such as list and dict ... can add support through subclassing", and do

Re: initialize a dictionary

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I need to iterate values by row and column as well. I tried this w,x = 32, 16 A = [ [0x0]*w for i in range(x)] print A py> import numarray py> print numarray.zeros((16, 8)) [[0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0] [

Re: returning a list: IndexError

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote: from Numeric import * # Initialize the 32x16 global array to zeros tbl = zeros((32, 16) def getValue( value): data = test(value) c1 = data[0] c2 = data[1] print tbl[c1, c2] def test( value): t1 = 0x0 t2 = 0x1 return tbl[t1, t2] In test, tbl[0x0,

Re: returning a list: IndexError

2005-03-30 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Steven Bethard wrote: py> import numarray as na py> tbl = na.zeros((32, 16)) py> def get_value(): ... data = test() ... c1 = data[0] ... c2 = data[1] ... print tbl[c1, c2] ... py> def test(): ... t1 = 0x0 ... t2 = 0x1 ... retur

Re: property and virtuality

2005-03-31 Thread Steven Bethard
Laszlo Zsolt Nagy wrote: My problem is about properties and the virtuality of the methods. I would like to create a property whose get and set methods are virtual. Perhaps you want to roll your own VirtualProperty descriptor? Here's one based off the property implementation in Raymond Hettinger'

Re: returning a list: IndexError

2005-03-31 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Thats right. I wanted c1 and c2 to retrieve the values returned by t1 and t2 . Values for t1 and t2 could be anything. Also tbl is global. Then you need to return t1 and t2 in test, e.g.: py> import numarray as na py> tbl = na.zeros((32, 16)) py> def test(): ... t1 = 0x

Re: Stylistic question about inheritance

2005-03-31 Thread Steven Bethard
Andrew Koenig wrote: "Carl Banks" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Well, Python seems to get along fine without the ability to do isinstance(foo,file_like_object); probably better off in the end for it. So I'd say you should generally not do it. Inheritence is for whe

Re: property and virtuality

2005-03-31 Thread Steven Bethard
Steven Bethard wrote: Laszlo Zsolt Nagy wrote: My problem is about properties and the virtuality of the methods. I would like to create a property whose get and set methods are virtual. Perhaps you want to roll your own VirtualProperty descriptor? Here's one based off the pro

Re: Pre-PEP: Dictionary accumulator methods

2005-04-01 Thread Steven Bethard
Greg Ewing wrote: Steven Bethard wrote: py> def defaultdict(*args, **kwargs): ... defaultfactory, args = args[0], args[1:] which can be written more succinctly as def defaultdict(defaultfactory, *args, **kwargs): ... Not if you want to allow the defaultfactory to be called wit

Re: Ternary Operator in Python

2005-04-01 Thread Steven Bethard
praba kar wrote: Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. http://www.python.org/peps/pep-0308.html -- http://mail.python.org/mailman/listinfo/python-list

Re: numeric module

2005-04-01 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Hello, What's the problem with this code? I get the following error message: File "test.py", line 26, in test print tbl[wi][bi] IndexError: index must be either an int or a sequence ---code snippet from Numeric import * tbl = zeros((32, 16)) def test(): val = t

Re: Ternary Operator in Python

2005-04-02 Thread Steven Bethard
Scott David Daniels wrote: Roy Smith wrote: ... How our tools warp our thinking. That is what it means to be human. I can think of no better reason for a programmer to regularly learn languages: "our tools warp our thinking." A programmer is a professionally warped thinker. --Scott David Daniels

Re: Performance issue

2005-04-02 Thread Steven Bethard
Marc 'BlackJack' Rintsch wrote: def make_anagram_map(words): anagram_map = dict() for word in imap(lambda w: w.strip().lower(), words): sorted_word = ''.join(sorted(list(word))) anagram_map.setdefault(sorted_word, list()).append(word) return dict(ifilter(lambda x: l

Re: StopIteration in the if clause of a generator expression

2005-04-03 Thread Steven Bethard
Raymond Hettinger wrote: [Peter Otten] Do you see any chance that list comprehensions will be redefined as an alternative spelling for list()? Not likely. It is possible that the latter spelling would make it possible for Py3.0. eliminate list comps entirely. However, they are very popular and p

Re: text analysis in python

2005-04-03 Thread Steven Bethard
Maurice Ling wrote: In the Java world, there is GATE (general architecture for text engineering) and it seems very impressive. Are there something like that for Python? I worked with GATE this last summer and really hated it. Can't decide whether that was just my growing distaste for Java or ac

Re: Silly question re: 'for i in sys.stdin'?

2005-04-03 Thread Steven Bethard
Jeff Epler wrote: The iterator for files is a little bit like this generator function: def lines(f): while 1: chunk = f.readlines(sizehint) for line in chunk: yield line Inside file.readlines, the read from the tty will block until sizehint bytes have been read o

Re: Silly question re: 'for i in sys.stdin'?

2005-04-04 Thread Steven Bethard
Jeff Epler wrote: On Sun, Apr 03, 2005 at 09:49:42PM -0600, Steven Bethard wrote: Slick. Thanks! does isatty() actually work on windows? I'm a tiny bit surprised! Hmm... I was just talking about using iter(f.readline, ''), but it does appear that isatty returns True for s

Re: Semi-newbie, rolling my own __deepcopy__

2005-04-04 Thread Steven Bethard
Michael Spencer wrote: def __deepcopy__(self, memo={}): from copy import deepcopy result = self.__class__() memo[id(self)] = result result.__init__(deepcopy(tuple(self), memo)) return result I know this is not your recipe, but is there any reason to use

Re: StopIteration in the if clause of a generator expression

2005-04-04 Thread Steven Bethard
Raymond Hettinger wrote: [Steven Bethard] and I often find myself alternating between the two when I can't decide which one seems more Pythonic. Both are pythonic. Use a genexp when you need a generator and use a listcomp when you need a list. So do I read this right in preferring [ fo

Re: Propagating poorly chosen idioms

2005-04-05 Thread Steven Bethard
Skip Montanaro wrote: Unittest's API is difficult enough for me to remember (at least the initial framework I need to put together) that I generally hunt down some previous unittest usage, clone it and start from there. I no longer have any idea what the original unittest example was that got me s

Re: "specialdict" module

2005-04-05 Thread Steven Bethard
Georg Brandl wrote: Georg Brandl wrote: Hello, in follow-up to the recent "dictionary accumulator" thread, I wrote a little module with several subclassed dicts. Comments (e.g. makes it sense to use super), corrections, etc.? Is this PEP material? Docstrings, Documentation and test cases are to be

Re: Semi-newbie, rolling my own __deepcopy__

2005-04-06 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Michael Spencer wrote: [EMAIL PROTECTED] wrote: [snip] Anyway, my present problem is that I want to make copies of instances of my own custom classes. I'm having a little trouble understanding the process. Not that I think that it matters -- but in case it does, I'll tell

Re: formatting file

2005-04-06 Thread Steven Bethard
SPJ wrote: Hi, I am new to python hence posing this question. I have a file with the following format: test11.1-1 installed test11.1-1 update test22.1-1 installed test22.1-2 update I want the file to be formatted in the following way: test11.1-1 1.1-2 test22.1-1

Re: Semi-newbie, rolling my own __deepcopy__

2005-04-06 Thread Steven Bethard
Michael Spencer wrote: BTW, as I mentioned in a previous comment, I believe this would be more plainly written as type(self).__new__(), to emphasize that you are constructing the object without initializing it. (There is a explanation of __new__'s behaviour at http://www.python.org/2.2/descrin

Re: Multiple inheritance: Interface problem workaround, please comment this

2005-04-07 Thread Steven Bethard
Axel Straschil wrote: I solved all my problems for pythons multiple inheritance with this ng, thaks to all again, but there is one think I still dislike: class A(object): def __init__(self, a=None, **__eat): print "A" super(A, self).__init__() class B(object): def __init__(self, b=None, **_

Re: Counting iterations

2005-04-08 Thread Steven Bethard
Derek Basch wrote: Is there a better way to count iterations that this?: pets = 0 for i in pets: pets += 1 print "pet" + "#" + pets for i, pet in enumerate(pets): print 'pet#%i' % (i + 1) STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: Equivalent string.find method for a list of strings

2005-04-08 Thread Steven Bethard
jeremit0 wrote: Steve Holden wrote: If you want line numbers,. of course, then you can use for linenum, line in enumerate(myfile.readlines()): ... Remember that true to Python's philosophy numbering will start at zero. Is this any better than: lines = myfile.readlines() for linenum

Re: Counting iterations

2005-04-09 Thread Steven Bethard
Andrew Dalke wrote: "pet#%i" % (i+1) (NOTE: most times that's written %d instead of %i) Any reason to prefer %d over %i? The library reference seems to suggest that they're the same thing[1]. I've typically used %i since I can remember it from the int type, like I can remember %f from the floa

Re: numarray.array can be VERY slow

2005-04-10 Thread Steven Bethard
Edward C. Jones wrote: #! /usr/bin/env python """Should this program take 4.3 seconds to run? I have a Linux PC with an AMD Athlon XP 2000+ chip (1.7Gh). I use Python 2.4.1 and numarray 1.2.3, both compliled from source.""" import time, numarray from numarray.numerictypes import * nested = []

Re: numarray.array can be VERY slow

2005-04-10 Thread Steven Bethard
Edward C. Jones wrote: Steven Bethard wrote: > As mentioned, this has nothing to do with numarray, and everything to > do with your inexplicable use of lists. Why don't you just write this > as: > > arr = numarray.ones((8, 8, 256, 256), Float64) The code I posted was simp

Re: Doubt regarding sorting functions

2005-04-11 Thread Steven Bethard
[EMAIL PROTECTED] wrote: def funcSort(myList): result = myList[:] result.sort() return result In Python 2.4, funcSort is called sorted: py> sorted([1.2,1.23,4.5,2]) [1.2, 1.23, 2, 4.5] py> sorted(["a","c","b","A","C","B"]) ['A', 'B', 'C', 'a', 'b', 'c'] STeVe -- http://mail.python.org/mailman

Re: variables exist

2005-04-11 Thread Steven Bethard
Brian van den Broek wrote: Fredrik Lundh said unto the world upon 2005-04-11 10:14: "fabian" wrote: how testing if a variable exists in python as isset in php?? try: variable except NameError: print "variable not set" but that is really lousy Python; better make sure you always assign to al

Re: singleton objects with decorators

2005-04-11 Thread Steven Bethard
Uwe Mayer wrote: Hi, I've been looking into ways of creating singleton objects. With Python2.3 I usually used a module-level variable and a factory function to implement singleton objects. With Python2.4 I was looking into decorators. The examples from PEP 318 http://www.python.org/peps/pep-0318.ht

Re: Creating a new instance of a class by what is sent in?

2005-04-11 Thread Steven Bethard
ChinStrap wrote: I am sorry if this is obvious, but I am not seeing it. How would I go about creating a new type that is of the same type as a class sent into the function? new = foo.__init__() refers to the current foo, not a new fresh instance of my class. The only way I can think of is to make

Re: singleton objects with decorators

2005-04-11 Thread Steven Bethard
Uwe Mayer wrote: I've been looking into ways of creating singleton objects. It strikes me that I've never wanted or needed a singleton object. Would you mind sharing your use case? I'm just curious. Thanks, STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: singleton objects with decorators

2005-04-12 Thread Steven Bethard
Uwe Mayer wrote: Tuesday 12 April 2005 06:36 am Steven Bethard wrote: Uwe Mayer wrote: I've been looking into ways of creating singleton objects. It strikes me that I've never wanted or needed a singleton object. Would you mind sharing your use case? I'm just curious. I am using a

Re: singleton objects with decorators

2005-04-12 Thread Steven Bethard
Fredrik Lundh wrote: Or if you're using an application object (you should), just add a config object to the application object (app.config.param = ...). Do you have a link or two that describe what you mean by an "application object"? The "you should" comment makes me think this is something of a

Re: singleton objects with decorators

2005-04-12 Thread Steven Bethard
Uwe Mayer wrote: Tuesday 12 April 2005 10:01 am Steven Bethard wrote: I am using a class to manage configuration settings in an application. This object should only existe once so that when the user changes a setting through a configuration dialog the change imminent in all locations where access

Re: variables exist

2005-04-12 Thread Steven Bethard
Scott David Daniels wrote: Brian van den Broek wrote: ... STeVe stressed that the try/except solution is only really appropriate for cases where the failure to have the variable defined is quite rare. Beware: C++ and Java have an immense overhead for exceptions. Python has a very lightweight ex

Re: singleton objects with decorators

2005-04-12 Thread Steven Bethard
James Stroud wrote: Other than using modules, I thought @classmethod took care of this kind of need: class SingleThing: some_values = {"fanciness":0} def __init__(self): raise Exception, "not enough preceding stars to be fancy enough" @classmethod def why_so_fancy(self): print "wh

Re: sort of a beginner question about globals

2005-04-12 Thread Steven Bethard
fred.dixon wrote: i have read the book and searched the group too -- im not gettin it. i want to read a global (OPTIONS) from file1 from a class method (func1) in file2 i want to understand how this works. -- #f

Re: Doubt regarding sorting of a list specific field

2005-04-13 Thread Steven Bethard
praba kar wrote: I have doubt regarding sorting. I have a list that list have another list (eg) list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] I want to sort only numeric value having array field. How I need to do for that. In Python 2.4: py> import operator py> seq = [(1234,'name1'),(2

Re: Doubt regarding sorting of a list specific field

2005-04-13 Thread Steven Bethard
vincent wehren wrote: "praba kar" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] | Dear All, | |I have doubt regarding sorting. I have a list | that list have another list (eg) | | list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] -> Be careful, 0432 is octal notation f

Re: Doubt regarding sorting of a list specific field

2005-04-13 Thread Steven Bethard
F. Petitjean wrote: Le Wed, 13 Apr 2005 01:13:40 -0600, Steven Bethard a écrit : praba kar wrote: list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] I want to sort only numeric value having array field. How I need to do for that. In Python 2.4: py> import

Re: Doubt regarding sorting of a list specific field

2005-04-13 Thread Steven Bethard
Steven Bethard wrote: See my other post in this thread. seq.sort() is not stable; Hmmm... That didn't come out right. list.sort *is* stable. It's just that if you want to sort only by the first element of each tuple in a list, then list.sort won't produce results that are st

Re: sort of a beginner question about globals

2005-04-13 Thread Steven Bethard
fred.dixon wrote: I want to use OPTIONS as a global var. In this particular case I am trying to set a global debug constant so I can have some debug logging happen when my program is run with a -debug option. what will actuall end up in OPTIONS is OPTIONS.debug = True as i am using optparse module.

Re: os.path.walk

2005-04-13 Thread Steven Bethard
Peter Hansen wrote: Micheal wrote: If I have os.path.walk(name, processDirectory, None) and processDirectory needs three arguments how can I ass them because walk only takes 3? The best answer to this is: if you aren't stuck using a version of Python prior to 2.4, don't use os.path.walk but use os.

Re: preallocate list

2005-04-13 Thread Steven Bethard
Jim wrote: Thanks for the suggestions. I guess I must ensure that this is my bottle neck. def readFactorsIntoList(self,filename,numberLoads): factors = [] f = open(self.basedir + filename,'r') line = f.readline() tokens = line.split() columns = len(tokens)

Re: Is socket.shutdown(1) useless

2005-04-13 Thread Steven Bethard
[EMAIL PROTECTED] wrote: In my python books I find exclusive use of socket.close(). From my other readings, I know about a "partial close operation". So, I figured it would be useful to post some code about how socket.close() has an implicit send in it and you can actually gain some clarity by bein

Re: sort of a beginner question about globals

2005-04-13 Thread Steven Bethard
fred.dixon wrote: how would i use the following if OPTIONS was in a module ? --- from optparse import OptionParser usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-d", "--debug", ction="store_true", dest="verbose") (OPTIONS = parser.parse_arg

Re: Codig style: " or """

2005-04-13 Thread Steven Bethard
Sara Khalatbari wrote: Hi! Suppose you're writing a module & writing the definition of each function in that module in " or """. for example: a) "This function does this & that" or: b) """This function does blah blah blah""" What are the differences between " and """ ? I'm using gedit & I wanna k

Re: preallocate list

2005-04-13 Thread Steven Bethard
Jim wrote: What I really want is a Numeric array but I don't think Numeric supports importing files. Hmmm... Maybe the scipy package? I think scipy.io.read_array might help, but I've never used it. STeVe -- http://mail.python.org/mailman/listinfo/python-list

Re: sort of a beginner question about globals

2005-04-13 Thread Steven Bethard
fred.dixon wrote: ok I'm sorry, I'm not sure what your doing there. if i have to guess it looks like yo might me modifying the imported modules dict with another dict. Yes, this takes all the atrributes of the options object and sets them as attributes of the module. If you're afraid of __dict__,

Re: sort of a beginner question about globals

2005-04-13 Thread Steven Bethard
fred.dixon wrote: #global1.py import global2 import global3 import sys constant = 'dumb' option = sys.argv[1:] pass #global2.func1() a=global2.class1() a.func1() print newvar #global2.py import __main__ pass class class1: def func1(self): __main__.newvar = "string" pass The othe

Re: New-style classes, iter and PySequence_Check

2005-04-14 Thread Steven Bethard
Tuure Laurinolli wrote: Someone pasted the original version of the following code snippet on #python today. I started investigating why the new-style class didn't work as expected, and found that at least some instances of new-style classes apparently don't return true for PyInstance_Check, whic

Re: pre-PEP: Suite-Based Keywords

2005-04-16 Thread Steven Bethard
Shane Hathaway wrote: I like this PEP a lot, but your concern is valid. Maybe Brian could modify the PEP slightly to disambiguate. How about using an ellipsis in the argument list to signify suite-based keywords? Examples: f(...): x = 1 class C(object): x = property(...): doc = "I'm

Re: pre-PEP: Simple Thunks

2005-04-17 Thread Steven Bethard
Brian Sabbey wrote: used, but rarely is because doing so would be awkward. Probably the simplest real-world example is opening and closing a file. Rarely will you see code like this: def with_file(callback, filename): f = open(filename) callback(f) f.close() def print_file(file):

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

2005-04-17 Thread Steven Bethard
Kay Schluehr wrote: Hmmm ... now You eliminate "where" completely in favor for '::'. This may be reasonable because '::' is stronger and less context dependent. But on the other hand it may be also reasonable to eliminate '::' towards a stronger "where" ;) x = property(**kw) where kw: d

Re: Removing dictionary-keys not in a set?

2005-04-18 Thread Steven Bethard
Tim N. van der Leeuw wrote: Hi, I'd like to remove keys from a dictionary, which are not found in a specific set. So it's kind of an intersection-operation. I can create a new dictionary, or a loop over all keys and test them for set-membership, but I was wondering if there was a smart way to expre

Re: How to get a Function object from a Frame object

2005-04-18 Thread Steven Bethard
Gigi wrote: I need access to a function object that corresponds to a frame object in a certain case from inside the function. I can get the frame object using: f = sys._getframe(0) But the resulting frame object doesn't contain the information I need. There is a lot of information in the code ob

Re: Removing dictionary-keys not in a set?

2005-04-18 Thread Steven Bethard
Tim N. van der Leeuw wrote: In my taste, using generator expressions with conditions actually doesn't look very readable; it hides the set-membership test under the syntactic clutter. You might try different indentation. I find that I write a lot of my list comprehensions and generator expression

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

2005-04-19 Thread Steven Bethard
Ron wrote: How about using ***name in the same way as *name, and **name are used? It extends the current argument options in a consistent manner and 'I believe' is easy to explain and visually says something different is happening here. This builds on the already present arg, *arg, **arg, and

Re: pre-PEP: Simple Thunks

2005-04-19 Thread Steven Bethard
Greg Ewing wrote: Brian Sabbey wrote: do f in with_file('file.txt'): print f.read() I don't like this syntax. Try to read it as an English sentence: "Do f in with file 'file.txt'". Say what??? To sound right it would have to be something like with_file('file.txt') as f do: print f.read()

Re: Define Constants

2005-04-20 Thread Steven Bethard
codecraig wrote: Hi, I have a question about how to define constants. My directory structure looks like... C:\ --> abc.py --> utils --> __init__.py --> CustomThing.py Ok, CustomThing looks like... TOP = 0 LEFT = 1 class CustomThing: def __init__(self): self

Re: inner sublist positions ?

2005-04-20 Thread Steven Bethard
Bernard A. wrote: hello, while trying to play with generator, i was looking for an idea to get the position of a inner list inside another one, here is my first idea : - first find position of first inner element, - and then see if the slice starting from here is equal to the inner -> def subPo

Re: deprecation of has_key?

2005-04-21 Thread Steven Bethard
Denis S. Otkidach wrote: I believe it's a bad idea to remove this method, since behavior of both "item in dict" and "for item in dict" (especially the later) in Python does't seem sane to me. Just look at reverse operations: dict.fromkeys(seq) <-> d.keys(), d.iterkeys() - OK dict(iterable) <-> d.i

Re: How can I verify that a passed argument is an interible collection?

2005-04-21 Thread Steven Bethard
Charles Krug wrote: List: I'm working on some methods that operate on (mathematical) vectors as in: def Convolution(x, y) """Returns a list containing the convolution of vectors x and y""" Is there any way to determine at runtime that x and y are iterible collections? Do I *coughs* simply *coughs*

Re: deprecation of has_key?

2005-04-21 Thread Steven Bethard
Denis S. Otkidach wrote: On Thu, 21 Apr 2005 08:50:25 -0600 Steven Bethard wrote: SB> Huh? I'm not following your logic. Why is "item in dict" less SB> readable than "dict.has_key(item)"? Something to do with expecting SB> inverses that don't exist? S

Re: deprecation of has_key?

2005-04-21 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: For me dictionary is a collection of key-value pairs, but not a collection of keys (that's what set is). Ahh, ok. Now I understand. I think you could probably search the python-dev archives and see why the decision was made as it was. For pretty

grouping subsequences with BIO tags

2005-04-21 Thread Steven Bethard
I have a list of strings that looks something like: ['O', 'B_X', 'B_Y', 'I_Y', 'O', 'B_X', 'I_X', 'B_X'] I need to group the strings into runs (lists) using the following rules based on the string prefix: 'O' is discarded 'B_...' starts a new run 'I_...' continues a run started by

Re: grouping subsequences with BIO tags

2005-04-22 Thread Steven Bethard
Michael Spencer wrote: Steven Bethard wrote: Bengt Richter wrote: On Thu, 21 Apr 2005 15:37:03 -0600, Steven Bethard <[EMAIL PROTECTED]> wrote: I have a list of strings that looks something like: ['O', 'B_X', 'B_Y', 'I_Y', 'O', 

Re: func_code vs. string problem

2005-04-23 Thread Steven Bethard
Filip Dreger wrote: Each function has a func_code property that is suposed to contain the pure bytecode of the function. All the context (including reference to relevant namespaces) is stored in different fields of the function object. Since 'exec' is able to execute any string or bytecode in th

Re: func_code vs. string problem

2005-04-23 Thread Steven Bethard
Filip Dreger wrote: I am trying to find a way of executing functions without creating a nested scope, so they can share local and global namespace (even if they are declared in some other module). Why? Can you explain what the use case is? STeVe -- http://mail.python.org/mailman/listinfo/python-

Re: func_code vs. string problem

2005-04-23 Thread Steven Bethard
Filip Dreger wrote: If I had a magic function 'exec in current scope' I would implement it like this: class actor: def __init__(): self.roles=[] def act(): for i in self.roles: exec i in current scope then the roles would simply be functions defined in any importable file. For

Re: func_code vs. string problem

2005-04-23 Thread Steven Bethard
Filip Dreger wrote: Uzytkownik "Steven Bethard" <[EMAIL PROTECTED]> napisal w wiadomosci news:[EMAIL PROTECTED] See the documentation: http://docs.python.org/ref/dynamic-features.html """The eval(), execfile(), and input() functions and the exec statement

Re: Variables

2005-04-23 Thread Steven Bethard
Richard Blackwood wrote: Indeed, this language is math. My friend says that foo is a constant and necessarily not a variable. If I had written foo = raw_input(), he would say that foo is a variable. Then what does he say if you write: foo = 5 foo = 6 ? STeVe -- http://mail.python.org/mailman/list

Re: Multiple tuples for one for statement

2005-04-24 Thread Steven Bethard
Harlin Seritt wrote: I have three tuples of the same size: tup1, tup2, tup3 I'd like to do something like this: for a,b,c in tup1, tup2, tup3: print a print b print c Of course, you get an error when you try to run the pseudocode above. What is the correct way to get this done? for a, b, c

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

2005-04-24 Thread Steven Bethard
Robert Kern wrote: Mike Meyer wrote: Ok, we've added list comprehensions to the language, and seen that they were good. We've added generator expressions to the language, and seen that they were good as well. I'm left a bit confused, though - when would I use a list comp instead of a generator expr

Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread Steven Bethard
James Stroud wrote: Oops, last one had a typo: a = ['bob', 'greg', 'cindy', 'alice'] b = ['fred','barney','betty','wilma','pebbles','bambam'] c = ['jed', 'granny', 'jethro', 'ellie-mae'] d = ['bob','carol','ted','alice'] e = [a,b,c,d] for ary in e: print ary e.sort(lambda x,y:cmp(x[1],y[1])) for

Re: how can I sort a bunch of lists over multiple fields?

2005-04-27 Thread Steven Bethard
Lonnie Princehouse wrote: Might as well make a class for Book instead of dealing with buckets of lists... class Book(object): def __init__(self, title, author, publisher, isbn, date):# add more fields according to CSV self.__dict__.update(locals()) # lazy! Just for any newbies not

Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
googleboy wrote: firstly, I am trying hard to figure out how to create a new file with the list rather than print to standard out. I haev done this: for book in books: print book # just to be sure it works as I expect sort1 = open(r'D:\path to\sort1.csv', 'w+') print >

Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
Lonnie Princehouse wrote: So far, we've been using the "key" parameter of list.sort. If you want sort criteria more complicated than a single attribute, you can sort based on a custom comparison function. Actually, the key= parameter can do anything the cmp= parameter can: class Key(object): d

Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
Lonnie Princehouse wrote: Likewise, the above is basically just an inefficient way of writing: def date_key(book): return book.data def author_and_date_key(book): return (author_key(book), date_key(book)) It's certainly more elegant, but I wanted to talk about the mechanics of comparison fun

Re: Working with method-wrapper objects

2005-04-28 Thread Steven Bethard
Dr. Peer Griebel wrote: Why has [].__str__ a different type than object.__str__? Why is object.__str__ a routine while object().__str__ not? Well, I don't know why inspect.isroutine does what it does, but if you really need to detect these, can you do something like: py> MethodWrapperType = type(

<    4   5   6   7   8   9   10   11   12   13   >