Re: multiple inheritance super()

2005-08-01 Thread Steven Bethard
Michele Simionato wrote: > I have found out that the more I use OOP, the less I > use inheritance" > > Just curious if others had a similar experience. Definitely. Though I think that's partly because I came from a Java background where it's a little more ingrained. Since Python relies heavil

Re: Comparison of functions

2005-08-01 Thread Steven Bethard
Steven D'Aprano wrote: > You are confusing mathematical ordering with sorting a list. Here, I will > sort some mixed complex and real numbers for you. If you look at them > closely, you will even be able to work out the algorithm I used to sort > them. > > 1 > 1+0j > 1+7j > 2 > 2+3j > 3+3j > 3-3j

Re: HTML/text formatting question

2005-08-03 Thread Steven Bethard
Dr. Who wrote: > I have a tool that outputs data in either html or text output. > > Currently I'm writing chucnks like: > > if html: > print '' > print '' > print '' > print 'Differences %s: %s' % (htypestr, lbl1) > if html: > ... I'd create two Formatter classes, one for HTML

Re: Bug in slice type

2005-08-11 Thread Steven Bethard
Bryan Olson wrote: > > class BuggerAll: > > def __init__(self, somelist): > self.sequence = somelist[:] > > def __getitem__(self, key): > if isinstance(key, slice): > start, stop, step = key.indices(len(self.sequence)) >

Re: performance of recursive generator

2005-08-11 Thread Steven Bethard
aurora wrote: > I love generator and I use it a lot. Lately I've been writing some > recursive generator to traverse tree structures. After taking closer > look I have some concern on its performance. > > Let's take the inorder traversal from > http://www.python.org/peps/pep-0255.html as an

Re: Why does __init__ not get called?

2005-08-11 Thread Steven Bethard
Rob Conner wrote: > By chance... does anyone know, if I wrote a class, and just wanted to > override __new__ just for the fun of it. What would __new__ look like > so that it behaves exactly the same as it does any other time. Simple: class C(object): def __new__(cls, *args, **kwargs):

Re: performance of recursive generator

2005-08-11 Thread Steven Bethard
aurora wrote: > This test somehow water down the n^2 issue. The problem is in the depth > of recursion, in this case it is only log(n). It is probably more > interesting to test: > > def gen(n): > if n: > yield n > for i in gen(n-1): > yield i You should be

Re: Why does __init__ not get called?

2005-08-11 Thread Steven Bethard
Steven Bethard wrote: > def __call__(cls, *args, **kwargs): > obj = cls.__new__() > if not isinstance(obj.__class__, cls): ^^ issubclass > return obj > obj.__class__.__init__(obj, *args, **kwargs) > return o

Re: How do these Java concepts translate to Python?

2005-08-11 Thread Steven Bethard
Ray wrote: > 1. Where are the access specifiers? (public, protected, private) There's no enforceable way of doing these. The convention is that names that begin with a single underscore are private to the class/module/function/etc. Hence why sys._getframe() is considered a hack -- it's not of

Re: How to Adding Functionality to a Class by metaclass(not by inherit)

2005-08-11 Thread Steven Bethard
kyo guan wrote: > How to Adding Functionality to a Class by metaclass(not by inherit) > [snip] > > class MetaFoo(type): > def __init__(cls, name, bases, dic): > super(MetaFoo, cls).__init__(name, bases, dic) > > for n, f in inspect.ge

Re: How do these Java concepts translate to Python?

2005-08-12 Thread Steven Bethard
bruno modulix wrote: >>but technically >>speaking, there are no public, protected, or private things. > > Yes there are: > object.name is public > object._name is protected > object.__name is private The double-underscore name-mangling is almost never worth it. It's supposed to stop name collis

Re: __getattribute__ for class object

2005-08-12 Thread Steven Bethard
Dan wrote: > Depending on what you want to do, it might be better to use properties > instead: > > class Meta(type): > x = property(lambda klass: 'Called for '+str(klass)) > > class Foo(object): > __metaclass__=Meta Also worth noting that you can inline the metaclass if you don't n

Re: Loading classes dynamically

2005-08-14 Thread Steven Bethard
Ramza Brown wrote: > try: > load = eval('%s(props)' % (props['plugin.generate'])) > except: > > It works, doesnt seem very safe. Where props['plugin.generate'] is a > class name string. And 'props' is the first arg in the constructor. Where is the class defined? The right answer to this

Re: class-call a function in a function -problem

2005-08-16 Thread Steven Bethard
wierus wrote: > class ludzik: > x=1 > y=2 > l=0 > def l(self): > ludzik.l=ludzik.x+ludzik.y > print ludzik.l > > def ala(self): > print ludzik.x > print ludzik.y > ludzik.l() Methods defined in a class expect an instance of that class as the first argument. When you write: l

Re: class-call a function in a function -problem

2005-08-16 Thread Steven Bethard
Larry Bates wrote: > def __init__(self, x=1, y=2) [snip] > self.x=x > self.y=y > self.a=0 > return > > def l(self): [snip] > self.a=self.x+self.y > print "In ludzik.l a=',self.a > return > > def ala(self): [snip] > self.l

Re: Bug in slice type

2005-08-18 Thread Steven Bethard
Michael Hudson wrote: > [EMAIL PROTECTED] writes: >> I'm fine with your favored behavior. What do we do next to get >> the doc fixed? > > I guess one of us comes up with some less misleading words. It's not > totally obvious to me what to do, seeing as the returned values *are* > indices is a sen

Re: Bug in slice type

2005-08-18 Thread Steven Bethard
I wrote: > I wanted to say something about what happens with a negative stride, to > indicate that it produces (9, -1, -2) instead of (-1, -11, -2), but I > wasn't able to navigate the Python documentation well enough. > > Looking at the Language Reference section on the slice type[1] (section

Re: dict duplicity

2005-08-18 Thread Steven Bethard
Randy Bush wrote: >for pKey, pVal in dict.iteritems(): > print \ > pKey[0], hash(pKey[0]), \ > pKey[1], hash(pKey[1]), \ > pKey[2], hash(pKey[2]), \ > "hash=", hash(pKey), \ > pVal[0], hash(pVal[0]), \ > pVal[1], hash(pVal[1]) > > whe

Re: Really virtual properties

2005-08-18 Thread Steven Bethard
Ben Finney wrote: > Not using the built-in property type. Here is a recipe for a > LateBindingProperty that does what you ask: > > Steven Bethard: > "This recipe provides a LateBindingProperty callable which allows > the getter and setter methods associated

Re: while c = f.read(1)

2005-08-19 Thread Steven Bethard
Antoon Pardon wrote: > But '', {}, [] and () are not nothing. They are empty containers. > And 0 is not nothing either it is a number. Suppose I have > a variable that is either None if I'm not registered and a > registration number if I am. In this case 0 should be treated > as any other number.

Re: stdin -> stdout

2005-08-19 Thread Steven Bethard
max(01)* wrote: > i was wondering, what's the simplest way to echo the standard input to > the standard output, with no modification. import sys for line in iter(sys.stdin.readline, ''): sys.stdout.write(line) Note that this uses the second form of iter(), which calls its first argument re

Re: stdin -> stdout

2005-08-19 Thread Steven Bethard
gry@ll.mit.edu wrote: > import sys > for l in sys.stdin: > sys.stdout.write(l) This is fine if you don't need the reads and writes of lines to run in lockstep. File iterators read into a buffer, so you'll probably read 4096 bytes from stdin before you ever write a line to stdout. If th

sequence slicing documentation

2005-08-19 Thread Steven Bethard
In trying to work out what's different between the start, stop and step of slice.indices() and the start, stop and step of sequence slicing[1] I found that some of the list slicing documentation[2] is vague. I'd like to submit a documentation fix, but I want to make sure I have it right. Her

Re: Proposed PEP: New style indexing, was Re: Bug in slice type

2005-08-20 Thread Steven Bethard
Bryan Olson wrote: > Steven Bethard wrote: > > Well, I couldn't find where the general semantics of a negative stride > > index are defined, but for sequences at least[1]: > > > > "The slice of s from i to j with step k is defined as the sequence of >

Re: trictionary?

2005-08-28 Thread Steven Bethard
Randy Bush wrote: > now i want to add a second count column, kinda like > > bin = {} > for whatever: >for [a, b] in foo: > x = 42 - a > if bin.has_key(x): >bin[x.b] += 1 > else: >bin[x.b] = 1 >bin[x.not b] = 0 > for x,

Re: trictionary?

2005-08-28 Thread Steven Bethard
Adam Tomjack wrote: > Steven Bethard wrote: > ... >> Using a two element list to store a pair of counts has a bad code >> smell to me. > ... > > Why is that? Note that "code smell"[1] doesn't mean that something is actually wrong, just that it might

Re: trictionary?

2005-08-29 Thread Steven Bethard
Adam Tomjack wrote: > I'd write it like this: > >bin = {} >for start, end, AS, full in heard: > week = int((start-startDate)/aWeek) > counters = bin.setdefault(week, [0, 0]) > if full: > counters[0] += 1 > else: > counters[1] += 1 > >for week,

Re: trictionary?

2005-08-29 Thread Steven Bethard
[EMAIL PROTECTED] wrote: > import csv > temp1 = [] > temp2 = [] > reader = csv.reader(file(r"py_monsters.csv")) > for rec in reader: > temp1.append(rec) > for i in temp1[1:]: > temp2.append((i[0],dict(zip(temp1[0][1:],i[1:] > monsters = dict(temp2) I would tend to write this as: i

Re: trictionary?

2005-08-29 Thread Steven Bethard
Randy Bush wrote: > Steven Bethard wrote: >> It would probably help if you explained what the real problem is >> you're trying to solve. > > actually, that code fragment was meant to do that. it's pretty much > what i needed to do at that point, just the vari

Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-08-29 Thread Steven Bethard
Antoon Pardon wrote: > I think a properly implented find is better than an index. See the current thread in python-dev[1], which proposes a new method, str.partition(). I believe that Raymond Hettinger has shown that almost all uses of str.find() can be more clearly be represented with his pro

Re: regular expression unicode character class trouble

2005-09-04 Thread Steven Bethard
Diez B. Roggisch wrote: > Hi, > > I need in a unicode-environment the character-class > > set("\w") - set("[0-9]") > > or aplha w/o num. Any ideas how to create that? I'd use something like r"[^_\d\W]", that is, all things that are neither underscores, digits or non-alphas. In action: py> re

Re: __dict__ of object, Was: Regular Expression IGNORECASE different for findall and split?

2005-09-06 Thread Steven Bethard
Chris wrote: > but more of a basic question following, I was doing the following before: > > method = 'split' # came from somewhere else of course > result = re.__dict__[method].(REGEX, TXT) > > precompiling the regex > > r = compile(REGEX) > > does give an regex object which has th

Re: PEP-able? Expressional conditions

2005-09-07 Thread Steven Bethard
Kay Schluehr wrote: > Terry Reedy wrote: >> *If* bool(result_expression_i) == True for all i, (except maybe last >> default expression), which is true for some actual use cases, then the >> following expression evaluates to the result corresponding to the first >> 'true' condition (if there is one

[pyparsing] make sure entire string was parsed

2005-09-10 Thread Steven Bethard
How do I make sure that my entire string was parsed when I call a pyparsing element's parseString method? Here's a dramatically simplified version of my problem: py> import pyparsing as pp py> match = pp.Word(pp.nums) py> def parse_num(s, loc, toks): ... n, = toks ... return int(n) + 10

Re: make sure entire string was parsed

2005-09-11 Thread Steven Bethard
Paul McGuire wrote: > Thanks for giving pyparsing a try! To see whether your input text > consumes the whole string, add a StringEnd() element to the end of your > BNF. Then if there is more text after the parsed text, parseString > will throw a ParseException. Thanks, that's exactly what I was

Re: make sure entire string was parsed

2005-09-12 Thread Steven Bethard
Paul McGuire wrote: >>>I have to differentiate between: >>> (NP -x-y) >>>and: >>> (NP-x -y) >>>I'm doing this now using Combine. Does that seem right? > > If your word char set is just alphanums+"-", then this will work > without doing anything unnatural with leaveWhitespace: > > from pyparsin

Re: which is more 'pythonic' / 'better' ?

2005-09-12 Thread Steven Bethard
Steven D'Aprano wrote: > try...except... blocks are quick to set up, but slow to catch the > exception. If you expect that most of your attempts will succeed, then the > try block will usually be faster than testing the length of the list > each time. > > But if you expect that the attempts to wri

Re: make sure entire string was parsed

2005-09-12 Thread Steven Bethard
Steven Bethard wrote: > Paul McGuire wrote: > >>>> I have to differentiate between: >>>> (NP -x-y) >>>> and: >>>> (NP-x -y) >>>> I'm doing this now using Combine. Does that seem right? >> >> >> If your wor

Re: make sure entire string was parsed

2005-09-13 Thread Steven Bethard
Paul McGuire wrote: > I still don't know the BNF you are working from Just to satisfy any curiosity you might have, it's the Penn TreeBank format: http://www.cis.upenn.edu/~treebank/ (Except that the actual Penn Treebank data unfortunately differs from the format spec in a few ways.) > 1. I'm s

Re: which is more 'pythonic' / 'better' ?

2005-09-13 Thread Steven Bethard
Peter Hansen wrote: > def meth(self, things=None): > self.things = things or [] > [snip] > > The alternative is fine too, but insisting on it would be pedantic, and > if you have more than one of these it is definitely less readable (and, > therefore, not Pythonic): > > def meth(self, thin

Re: Example Script to parse web page links and extract data?

2005-09-14 Thread Steven Bethard
livin wrote: > I'm looking for an easy way to automate the below web site browsing and pull > the data I'm searching for. This is a task that BeautifulSoup[1] is usually good for. > 4) After search, table shows many links (hundreds sometimes) to the actual > data I need. > Links are this fo

Re: Removing duplicates from a list

2005-09-14 Thread Steven Bethard
przemek drochomirecki wrote: > def unique(s): > e = {} > for x in s: > if not e.has_key(x): >e[x] = 1 > return e.keys() This is basically identical in functionality to the code: def unique(s): return list(set(s)) And with the new-and-improved C implementation of sets comin

Re: python-dev Summary for 2005-08-01 through 2005-08-15

2005-09-14 Thread Steven Bethard
Steve Tregidgo wrote: > on 2005-08-30 01:45 Tony Meyer said the following: > >> [The HTML version of this Summary is available at >> http://www.python.org/dev/summary/2005-08-01_2005-08-15.html] > ... >> Many revision control systems were extensively discussed, including >> `Subversion`_ (SVN), `P

Re: Removing duplicates from a list

2005-09-16 Thread Steven Bethard
drochom wrote: > i suppose this one is faster (but in most cases efficiency doesn't > matter) > def stable_unique(s): > > e = {} > ret = [] > for x in s: > if not e.has_key(x): > e[x] = 1 > ret.append(x) > retur

Re: C#3.0 and lambdas

2005-09-19 Thread Steven Bethard
Paul Rubin wrote: > "Fredrik Lundh" <[EMAIL PROTECTED]> writes: > >>"Is anyone truly attached to nested tuple function parameters; >>'def fxn((a,b)): print a,b'? /.../ >> >>Would anyone really throw a huge fit if they went away? I am willing >>to write a PEP for their removal in

Re: C#3.0 and lambdas

2005-09-19 Thread Steven Bethard
Steven D'Aprano wrote: > Consider this: > > def func(some_tuple): > > How many items should you pass in the tuple? If it takes variable > arguments, then that works, but if you always expect a fixed number, then > > def func((x, y)) > > is more explicit. > > The only problem I have is that onc

Re: Why is map() preferable in this case?

2005-09-19 Thread Steven Bethard
Delaney, Timothy (Tim) wrote: > Devan L wrote: > >>Map is in C. It's faster, but not as clear. Some people do think >>map(f, L) is nicer though. Google is your friend here, if you want to >>read the old arguments. > > map() will be faster if the function you are calling from map() is > *also* in

Re: Writing a parser the right way?

2005-09-21 Thread Steven Bethard
Christopher Subich wrote: > beza1e1 wrote: > >> Well, a declarative sentence is essentially subject-predicate-object, >> while a question is predicate-subject-object. This is important in >> further processing. So perhaps i should code this order into the >> classes? I need to think a little bit m

Re: C#3.0 and lambdas

2005-09-21 Thread Steven Bethard
Steven D'Aprano wrote: > I would love to see your test code and profiling results that demonstrate > that explicit tuple unpacking in the body of a function is faster than > tuple unpacking (implicit or explicit) in the header of a function. Should be pretty close. I believe the byte-code is near

Re: Writing a parser the right way?

2005-09-22 Thread Steven Bethard
beza1e1 wrote: > Verbs are the tricky part i think. There is no way to recognice them. > So i will have to get a database ... work to do. ;) Try the Brill tagger[1] or MXPOST[2]. STeVe [1] http://www.cs.jhu.edu/~brill/code.html [2] ftp://ftp.cis.upenn.edu/pub/adwait/jmx/jmx.tar.gz -- http://mai

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Nick Coghlan wrote: By assigning to __dict__ directly, you can use the attribute view either as it's own dictionary (by not supplying one, or supplying a new one), or as a convenient way to programmatically modify an existing one. For example, you could use it to easily bind globals without need

Re: Multiple constructors

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: If you want to do this all the time, you could even build appropriate infrastructure for this task -- a little custom descriptor and metaclass, and/or decorators. Such infrastructure building is in fact fun and instructive -- as long as you don't fall into the trap of *using* s

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I wrote this little piece of code to get a list of relative paths of all files in or below the current directory (*NIX): walkList = [(x[0], x[2]) for x in os.walk(".")] filenames = [] for dir, files in walkList: filenames.extend(["/".join([dir, f]) for

Re: remove duplicates from list *preserving order*

2005-02-06 Thread Steven Bethard
Francis Girard wrote: I think your last solution is not good unless your "list" is sorted (in which case the solution is trivial) since you certainly do have to see all the elements in the list before deciding that a given element is not a duplicate. You have to exhaust the iteratable before yie

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: I think this ``view'' or however you call it should be a classmethod too, for the same reason -- let someone handily subclass Bunch and still get this creational pattern w/o extra work. Maybe a good factoring could be something like: class Bunch(object): def __init__(self,

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
On 6 Feb 2005 11:28:37 -0800, <[EMAIL PROTECTED]> wrote: > > walkList = [(x[0], x[2]) for x in os.walk(".")] > filenames = [] > for dir, files in walkList: > filenames.extend(["/".join([dir, f]) for f in files]) Caleb Hattingh top-posted: I would be interested to see an example

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
Caleb Hattingh wrote: filenames = [os.path.join(dirpath, filename) # This is cool for dirpath, _, filenames in os.walk('.') # This is getting tricky, whats the '_' for? Nothing to do with the list comprehension really. '_' is a commonly used variable name

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I don't know what the right solution is here... I wonder if I should write a classmethod-style descriptor that disallows the calling of a function from an instance? Or maybe I should just document that the classmethods

Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: at the OP's original code, the line: [(x[0], x[2]) for x in os.walk(".")] is the equivalent of: [dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')] Just a nit: you need parenth

Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Michael Spencer wrote: ISTM that 'bunch' or 'namespace' is in effect the complement of vars i.e., while vars(object) => object.__dict__, namespace(somedict) gives an object whose __dict__ is somedict. Yeah, I kinda liked this application too, and I think the symmetry would be nice. Looked at th

Re: remove duplicates from list *preserving order*

2005-02-06 Thread Steven Bethard
John Machin wrote: So, just to remove ambiguity, WHICH one of the bunch should be retained? Short answer: "the first seen" is what the proverbial "man in the street" would expect For my purposes, it doesn't matter which instance is retained and which are removed, so yes, retaining the first one is

Re: overwriting method in baseclass

2005-02-06 Thread Steven Bethard
Harald Massa wrote: Hello! I am using a library (= code of so else) within Python. Somewhere in this library there is: class foo: def baa(self, parameters): print "something" self.baazanan(some other parameters) class mirbo(foo): def baazanan(self, lalala):

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Nick Coghlan wrote: Finally, I've just used normal names for the functions. I think the issue of function shadowing is best handled by recommending that all of the functions be called using the class explicitly - this works just as well for instance methods as it does for class or static methods

Re: Confused with methods

2005-02-07 Thread Steven Bethard
jfj wrote: I think the problem is that you know python so well that you are used to the way things are and everything seems natural the way it is. For a newbie, the behaviour I mentioned seems indeed a bit inconsistent. "Inconsistent" not as in mathematics but as in "wow! I'd thought this should wo

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: I'm very sorry that there is no good use case for the "reduce" function in Python, like Peter Otten pretends. That's an otherwise very useful tool for many use cases. At least on paper. Clarity aside[1], can you give an example of where reduce is as efficient as the eqival

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Michael Spencer wrote: Nick Coghlan wrote: Steven Bethard wrote: It was because these seem like two separate cases that I wanted two different functions for them (__init__ and, say, dictview)... I see this, but I think it weakens the case for a single implementation, given that each

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: Is there someone on this list using this tool and happy with it ? Or is my mind too much targeted on FP paradigm and most of you really think that all the functions that apply another function to each and every elements of a list are bad (like "reduce", "map", "filter") ? I

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
John Lenton wrote: For example, the fastest way to get the factorial of a (small enough) number in pure python is factorial = lambda n: reduce(operator.mul, range(1, n+1)) Gah! I'll never understand why people use lambda, which is intended to create _anonymous_ functions, to create named functi

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: Le lundi 7 Février 2005 20:30, Steven Bethard a écrit : especially since I avoid lambda usage, and would have to write these as: Why avoid "lambda" usage ? You find them too difficult to read (I mean in general) ? Yup, basically a readability thing. I also tend to

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Carlos Ribeiro wrote: On Mon, 07 Feb 2005 11:50:53 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: Michael Spencer wrote: We could use __add__, instead for combining namespaces I don't think this is a good idea. For the same reasons that dicts don't have an __add__ (how should

Re: loops -> list/generator comprehensions

2005-02-07 Thread Steven Bethard
Caleb Hattingh wrote: Would filenames = [os.path.join(dirpath, filename) for dirpath, dirnames, filenames in os.walk('.') for filename in filenames] have been clearer for you? Then all you have to do is remember the order of the for-loop execution: Bizarr

Re: returning True, False or None

2005-02-07 Thread Steven Bethard
Matteo Dell'Amico wrote: Since a function that doesn't return is equivalent to one that returns None, you can write it as: >>> def doit(lst): ... s = set(lst) - set([None]) ... if s: return max(s) that looks to me as the most elegant so far, but this is just because it's mine :-) Cool.

Re: "Collapsing" a list into a list of changes

2005-02-07 Thread Steven Bethard
Francis Girard wrote: I see. I personnaly use them frequently to bind an argument of a function with some fixed value. Modifying one of the example in http://mail.python.org/pipermail/python-list/2004-December/257990.html I frequently have something like : SimpleXMLRPCServer.py: server.register

Re: def __init__ question in a class definition rephrased

2005-02-07 Thread Steven Bethard
Jeffrey Borkent wrote: what is the significance ( if any ) of the __ in these self.xx assignments. Variables with preceding __ are a vague attempt to avoid some types of name collisions in inheritance hierarchies. Any name that starts with a __ will be mangled by prefixing it with _: py> cl

Re: empty classes as c structs?

2005-02-07 Thread Steven Bethard
Michael Spencer wrote: I see no problem in repeating the methods, or inheriting the implementation. However, if namespace and bunch are actually different concepts (one with reference semantics, the other with copy), then __repr__ at least would need to be specialized, to highlight the differen

Re: Name of type of object

2005-02-09 Thread Steven Bethard
Randall Smith wrote: Jive Dadson wrote: The traceback routine prints out stuff like, NameError: global name 'foo' is not defined NameError is a standard exception type. What if I want to print out something like that? I've determined that "global name 'foo' is not defined" comes from the __str

Re: convert list of tuples into several lists

2005-02-09 Thread Steven Bethard
Diez B. Roggisch wrote: zip(*[(1,4),(2,5),(3,6)]) While this is also the approach I would use, it is worth noting that Guido thinks of this as an abuse of the argument passing machinery: http://mail.python.org/pipermail/python-dev/2003-July/037346.html Steve -- http://mail.python.org/mailman/list

Re: convert list of tuples into several lists

2005-02-09 Thread Steven Bethard
Peter Hansen wrote: Steven Bethard wrote: Diez B. Roggisch wrote: zip(*[(1,4),(2,5),(3,6)]) While this is also the approach I would use, it is worth noting that Guido thinks of this as an abuse of the argument passing machinery: http://mail.python.org/pipermail/python-dev/2003-July/037346.html

Re: empty classes as c structs?

2005-02-09 Thread Steven Bethard
Alex Martelli wrote: Nick Coghlan <[EMAIL PROTECTED]> wrote: We could use __add__, instead for combining namespaces Update already let's us combine namespaces. To create a new object that merges two namespaces do: namespace.update(namespace(ns_1), ns_2) One thing I'd like to see in namespaces

Re: empty classes as c structs?

2005-02-09 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I didn't know what to do for __setattr__... Was that what you meant by "The best semantics for _bindings_ as opposed to lookups isn't clear though"? Yep. __delattr__ ain't too obvious to me either, th

Re: convert list of tuples into several lists

2005-02-10 Thread Steven Bethard
Cappy2112 wrote: What does the leading * do? Tells Python to use the following iterable as the (remainder of the) argument list: py> def f(x, y): ... print x, y ... py> f([1, 2]) Traceback (most recent call last): File "", line 1, in ? TypeError: f() takes exactly 2 arguments (1 given) py>

Re: empty classes as c structs?

2005-02-10 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: I like the idea of chain, though, so I'll probably add the class with just __init__ and __getattribute__ to the current implementation. I'm willing to be persuaded, of course, but for the moment, since I can see

namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-10 Thread Steven Bethard
d the current implementation of the module at the end of the PEP.) -- PEP: XXX Title: Attribute-Value Mapping Data Type Version: Last-Modified: Author: Steven Bethard <[EMAIL PROTECTED]> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 10-Feb-2005 P

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-10 Thread Steven Bethard
Jeremy Bowers wrote: On Thu, 10 Feb 2005 11:56:45 -0700, Steven Bethard wrote: In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that i

Re: convert list of tuples into several lists

2005-02-11 Thread Steven Bethard
Pierre Quentel wrote: Could someone explain why this doesn't work : Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def f(*args,**kw): ... print args, kw ... >>> f(*[1,2]) (1, 2) {} >>>

check if object is number

2005-02-11 Thread Steven Bethard
Is there a good way to determine if an object is a numeric type? Generally, I avoid type-checks in favor of try/except blocks, but I'm not sure what to do in this case: def f(i): ... if x < i: ... The problem is, no error will be thrown if 'i' is, say, a string: p

Re: check if object is number

2005-02-11 Thread Steven Bethard
Bill Mill wrote: On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: Is there a good way to determine if an object is a numeric type? How about: if type(variable) == type(1): print "is an integer" else: print "please input an integer"

Re: check if object is number

2005-02-11 Thread Steven Bethard
Dan Bishop wrote: Steven Bethard wrote: Is there a good way to determine if an object is a numeric type? How about this? ... def is_number(x): ...try: ... x + 1 ... return True ...except TypeError: ... return False Great, thanks! That's the kind of thing I was lo

Re: check if object is number

2005-02-11 Thread Steven Bethard
George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does your application consider to be numeric? Well, here's the basic code: def f(max=None):

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-12 Thread Steven Bethard
Nick Coghlan wrote: There *is* a problem with using __getattr__ though - any attribute in the chained namespaces that is shadowed by a class attribute (like 'update') will be picked up from the class, not from the chained namespaces. So we do need to use __getattribute__ to change that lookup o

Re: check if object is number

2005-02-12 Thread Steven Bethard
George Sakkis wrote: For the record, here's the arbitrary and undocumented (?) order among some main builtin types: None < 0 == 0.0 < {} < [] < "" < () If you're curious, you can check the source code. Look for default_3way_compare in object.c. Basically the rundown for dissimilar types is: *

Re: exception handling for a function returning several values

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: If a function that normally returns N values raises an exception, what should it return? Depends on what you want to do with the result of the function. N values of None seems reasonable to me, so I would write code such as def foo(x): try: # code setting y and z

Re: pre-check for string-to-number conversion

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I am reading an ASCII data file and converting some of the strings to integers or floats. However, some of the data is corrupted and the conversion doesn't work. I know that I can us exceptions, but they don't seem like the cleanest and simplest solution to me. You should r

Re: check if object is number

2005-02-12 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: Is there a good way to determine if an object is a numeric type? assert operator.isNumberType(i) Interesting, thanks! If I read the source right, PyNumber_Check (which operator.isNumberType is an alias for) basically just returns True if the object&#

Re: check if object is number

2005-02-12 Thread Steven Bethard
John Lenton wrote: On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote: George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does

Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-12 Thread Steven Bethard
Nick Coghlan wrote: Steven Bethard wrote: >>> ns = Namespace(eggs=1) >>> Namespace.update(ns, [('spam', 2)], ham=3) >>> ns Namespace(eggs=1, ham=3, spam=2) Note that update should be used through the class, not through the instances, to avoid

Re: check if object is number

2005-02-12 Thread Steven Bethard
George Sakkis wrote: George Sakkis wrote: "Steven Bethard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a good way to determine if an object is a numeric type? In your example, what does your application consider to be numeric? Well, here's the basic

Re: check if object is number

2005-02-12 Thread Steven Bethard
Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a number... would the OP's fun

Re: check if object is number

2005-02-12 Thread Steven Bethard
Michael Spencer wrote: Steven Bethard wrote: Peter Hansen wrote: Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. How about explicitly calling an

Re: help please

2005-02-12 Thread Steven Bethard
[EMAIL PROTECTED] wrote: t2="" def Proc(text): # "text" is some random text or use OrigText for word in text: for letter in word: if letter in std.keys(): letter=std[letter] t2=t2+letter # the problem is referene to this elif lett

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