Re: counting items

2005-01-12 Thread Steven Bethard
Mark McEahern wrote: It's me wrote: Okay, I give up. What's the best way to count number of items in a list [that may contain lists]? a = [[1,2,4],4,5,[2,3]] def iterall(seq): for item in seq: try: for subitem in iterall(item): yield subitem except Typ

Re: Iteration over two sequences

2005-01-12 Thread Steven Bethard
Henrik Holm wrote: John Lenton <[EMAIL PROTECTED]> wrote: def dotproduct(a, b): psum = 0 for i in range(len(a)): psum += a[i]*b[i] return psum for this particular example, the most pythonic way is to do nothing at all, or, if you must call it dotproduct, from Numeric import dot as dotp

Re: counting items

2005-01-12 Thread Steven Bethard
Michael Hartl wrote: (Once you can iterate over an arbitrary sequence, the flattened version is just [element for element in walk(sequence)].) Or, better yet: list(walk(sequence)) Steve -- http://mail.python.org/mailman/listinfo/python-list

Re: dict.updated

2005-01-12 Thread Steven Bethard
Rick Morrison wrote: Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? Are you looking for updated() to parallel sorted(), where sorted() returns a *new* list? I doubt you'll be able to rally much

list and generators (WAS: counting items)

2005-01-12 Thread Steven Bethard
Michael Hartl wrote: That's cool! Of course, walk returns a generator, so using a list comprehension to turn it into a list seems natural, but I didn't realize that list() does the same thing (and neither, apparently, did the original implementor) -- although, with a little reflection, it obviousl

Re: else condition in list comprehension

2005-01-12 Thread Steven Bethard
Steve Holden wrote: Nick Coghlan wrote: z = [newval(i) for i in range(10)] using: def newval(x): if x % 2: return x - 2 else: return x + 2 Just some more mental twiddling relating to the thread on statement local namespaces. I presume the point of this

Re: reference or pointer to some object?

2005-01-12 Thread Steven Bethard
Jeff Shannon wrote: Torsten Mohr wrote: I still wonder why a concept like "references" was not implemented in Python. I think it is (even if small) an overhead to wrap an object in a list or a dictionary. Because Python uses a fundamentally different concept for variable names than C/C++/Java (an

Re: dict.updated

2005-01-12 Thread Steven Bethard
Rick Morrison wrote: I could live with creating a new dict, sure (although it seems wasteful). I realize that something like this probably doesn't stand a chance of ever making it into the std library for what might be called "philosophical" reasons. I just want it for me (my personal philosophy ru

Re: reference or pointer to some object?

2005-01-12 Thread Steven Bethard
Torsten Mohr wrote: I still wonder why a concept like "references" was not implemented in Python. I think it is (even if small) an overhead to wrap an object in a list or a dictionary. Isn't it possible to extend Python in a way to use real references? Or isn't that regarded as necessary? IMHO it

Re: Why would I get a TypeEror?

2005-01-12 Thread Steven Bethard
It's me wrote: For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? You're looking for lazy evaluation or short-circuiting behavior. Python provides one form of short circuiting behavior with 'and' and 'or', though you need

Re: [perl-python] 20050112 while statement

2005-01-13 Thread Steven Bethard
Xah Lee wrote: # here's a while statement in python. a,b = 0,1 while b < 20: print b a,b = b,a+b --- # here's the same code in perl ($a,$b)=(0,1); while ($b<20) { print $b, "\n"; ($a,$b)= ($b, $a+$b); } Because you're posting this to newsgroups, it would be advisable to use only spaces

sorted (WAS: lambda)

2005-01-13 Thread Steven Bethard
Paul Rubin wrote: That completely depends on the objects in question. Compare temp = all_posters[:] temp.sort() top_five_posters = temp[-5:] to: top_five_posters = all_posters.sorted()[-5:] which became possible only when .sorted() was added to Python 2.4. I believe you mean "when sort

Re: Refactoring; arbitrary expression in lists

2005-01-13 Thread Steven Bethard
BJörn Lindqvist wrote: # do other non-extension-related tests here if basename.find( "Makefile" ) != -1: return "text/x-makefile" I believe this can be nicelier written as: if "Makefile" in basename: +1 for "nicelier" as VOTW (Vocabulation of the week) =) Steve -- http://mail.python.o

Re: porting C code

2005-01-13 Thread Steven Bethard
Lucas Raab wrote: I am currently in the process of porting some C code into Python and am stuck. I don't claim to be the greatest C/C++ programmer; in fact, my skills at C are rudimentary at best. My question is I have the statement: "typedef unsigned long int word32" and later on: "word32 b

Re: Why would I get a TypeEror?

2005-01-14 Thread Steven Bethard
It's me wrote: Say again??? Please stop top-posting -- it makes it hard to reply in context. "Reinhold Birkenfeld" wrote... It's me wrote: If this is true, I would run into trouble real quick if I do a: (1/x,1.0e99)[x==0] Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! If you want short-circu

Re: (objects as) mutable dictionary keys

2005-01-14 Thread Steven Bethard
Peter Maas wrote: I have summarized the discussion about the usability of lists (and and other mutable types) as dictionary keys and put it into the Python wiki.URL: http://www.python.org/moin/DictionaryKeys. Antoon Pardon wrote: > I had a look and I think you should correct the followingr: > > D

Re: Why would I get a TypeEror?

2005-01-16 Thread Steven Bethard
Stian Soiland wrote: På 14. jan 2005 kl. 22:58 skrev Steven Bethard: (Any mac users? How do I fix this to appear in Norwegian? =) Note that if you're not comfortable with short-circuiting behavior, you can also code this using lazy evaluation: (lambda: 1/x, lambda: 1.0e99)[x==0]() .

Re: Executing a script created by the end user

2005-01-16 Thread Steven Bethard
Craig Howard wrote: I am working on a python project where an object will have a script that can be edited by the end user: object.script If the script is a simple one with no functions, I can easily execute it using: exec object.script But if the object script is a bit more complicated, su

Re: [perl-python] 20050117, filter, map

2005-01-16 Thread Steven Bethard
Xah Lee wrote: © Note: this post is from the Perl-Python © a-day mailing list at © http://groups.yahoo.com/group/perl-python/ Is there any chance you could post these all as part of the same thread? That would be really nice for those of us who aren't interested -- then we could just ignore the

Re: dynamic data types

2005-01-17 Thread Steven Bethard
Paul Simmonds wrote: I would assume that they're refering to the fact that even the basic data types such as int are derived from object, and hence have methods: int.__class__.__base__ Java, for example, has both an Integer object and a basic int data type. One word. Yuck. Heh heh. Yeah, I can re

Re: lambda

2005-01-18 Thread Steven Bethard
Antoon Pardon wrote: In this case for example there are a number of people who flat out assert that muatble dict keys in pyhthon is impossible. If you run into any of these folks, please point them to: http://www.python.org/moin/DictionaryKeys It's a pretty good summary of one of the more recent th

Re: generator expressions: performance anomaly?

2005-01-18 Thread Steven Bethard
Bengt Richter wrote: Which make me wonder what plans there are for providing a better mechanism than default arguments as a way of initializing local function variables. Nested def's to create a closure with initialized values is pretty crufty for that, IMO. What about using a class? Associating f

Re: generator expressions: performance anomaly?

2005-01-18 Thread Steven Bethard
Bengt Richter wrote: On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: Bengt Richter wrote: Which make me wonder what plans there are for providing a better mechanism than default arguments as a way of initializing local function variables. Nested def's

Re: generator expressions: performance anomaly?

2005-01-19 Thread Steven Bethard
Stephen Thorne wrote: On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: @with_consts(i=1, deftime=time.ctime()) def foo(x, y=123, *args, **kw): return x*y, kw.get('which_time')=='now' and time.ctime() or deftime Then you don't have to

Re: Dictionary keys (again) (was Re: lambda)

2005-01-19 Thread Steven Bethard
David Eppstein wrote: In article <[EMAIL PROTECTED]>, Nick Coghlan <[EMAIL PROTECTED]> wrote: For a 'mutable key' to make sense, the following: lst = [] dct = {l: "Hi!"} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi Yes, and what should the fo

Re: Dictionary keys (again) (was Re: lambda)

2005-01-19 Thread Steven Bethard
Nick Coghlan wrote: For a 'mutable key' to make sense, the following: lst = [] dct = {l: "Hi!"} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi And here's an implementation that does so: py> class sillydict(dict): ... def __getitem__(self, key)

Re: list item's position

2005-01-19 Thread Steven Bethard
Bill Mill wrote: 2 solutions: In [98]: bars = ["str", "foobaz", "barbaz", "foobar"] In [99]: for bar in bars: : if 'bar' in bar and 'baz' in bar: : print bar : print bars.index(bar) : barbaz 2 In [100]: for i in range(len(bars)): .: if 'bar

Re: [Python-Dev] Updated Monkey Typing pre-PEP

2005-01-20 Thread Steven Bethard
On Thu, 20 Jan 2005 18:21:17 -0500, Raymond Hettinger <[EMAIL PROTECTED]> wrote: > > Instead of a __getattr__ solution, I recommend subclassing from a mixin: > > class RichMap(SomePartialMapping, UserDict.DictMixin): pass > > class RichFile(SomePartialFileClass, Mixins.FileMixin): pass

Re: problems with duplicating and slicing an array

2005-01-20 Thread Steven Bethard
Yun Mao wrote: Hi python gurus, I have some questions when I'm using python numeric: 1. When I do v = u[:, :], it seems u and v still point to the same memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. What's the right way to duplicate an array? Now I have to do v = dot(u, identi

Re: Print a string in binary format

2005-01-21 Thread Steven Bethard
Stephen Thorne wrote: On Fri, 21 Jan 2005 01:54:34 GMT, Kartic <[EMAIL PROTECTED]> wrote: Aha..I guess I posted too soon. You might want to take a look at this cookbook entry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 Defines lambdas to convert integer to binary. The one you pr

Re: Unbinding multiple variables

2005-01-21 Thread Steven Bethard
Johnny Lin wrote: my understanding about locals() from the nutshell book was that i should treat that dictionary as read-only. is it safe to use it to delete entries? No it's not: py> def f(): ... x = 1 ... del locals()['x'] ... print x ... py> f() 1 py> def f(): ... x = 1 ...

Re: problems with duplicating and slicing an array

2005-01-21 Thread Steven Bethard
py> import numarray as na py> a = na.array([[1,2,3],[4,5,6]]) Yun Mao wrote: Thanks for the help. numarray doesn't provide what I look for either. e.g. a = array( [[1,2,3],[4,5,6]] ) I sometimes what this: a[ [1,0], :], py> a[[1,0]] array([[4, 5, 6], [1, 2, 3]]) or even a[ [1,0], [0,1] ]

Re: default value in a list

2005-01-21 Thread Steven Bethard
Paul McGuire wrote: expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] Or if you're afraid of lambda like me: def expand(lst,default,minlen):return (lst + [default]*minlen)[0:minlen] or perhaps more readably: def expand(lst, default, minlen): return (lst + [default]*minlen)

Re: Unbinding multiple variables

2005-01-21 Thread Steven Bethard
Alex Martelli wrote: Nevertheless, any modifications to locals() are utterly futile (within a function). Evil hack that makes modifications to locals() not quite as futile: py> import sys py> import ctypes py> def f(): ... x = 1 ... locals()['x'] = 2 ... ctypes.pythonapi.PyFrame_LocalsT

Re: finding name of instances created

2005-01-21 Thread Steven Bethard
André wrote: Given the statement a = public_class() I would like to generate my_dict['a'] = private_class() so that one could write a.apparently_simple_method() and that, behind the scene, I could translate that as my_dict['a'].not_so_simple_method() as well as do things like for name in my_dict:

specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-21 Thread Steven Bethard
I wrote: > If you really want locals that don't contribute to arguments, I'd be > much happier with something like a decorator, e.g.[1]: > > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): >return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > Then yo

Re: finding name of instances created

2005-01-21 Thread Steven Bethard
André wrote: Using the method suggested by Steven Bethard, I *almost* got it working the way I would like. Here's my program: === .class PrivateClass(object): .dict = {} .def not_so_simple_method(self): .for name in PrivateClass.dict.keys(): .if PrivateClass.dict

Re: finding name of instances created

2005-01-21 Thread Steven Bethard
Andrà Roberge wrote: Behind the scene, I have something like: robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } and have mapped move() to correspond to robot_dict['robot'].move() (which does lots of stuff behind the scene.) I have tested robot_dict[] with more than one robot (each with i

Re: finding name of instances created

2005-01-21 Thread Steven Bethard
André wrote: Steven Bethard wrote: André wrote: Using the method suggested by Steven Bethard, I *almost* got it working the way I would like. [snip] It looks like you want PrivateClass.dict updated every time that globals() is updated. yes, that is what I would like to do. You can just use

Re: finding name of instances created

2005-01-21 Thread Steven Bethard
Andrà Roberge wrote: Behind the scene, I have something like: robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } and have mapped move() to correspond to robot_dict['robot'].move() (which does lots of stuff behind the scene.) I have tested robot_dict[] with more than one robot (each with i

Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-23 Thread Steven Bethard
Nick Coghlan wrote: Steven Bethard wrote: I wrote: > If you really want locals that don't contribute to arguments, I'd be > much happier with something like a decorator, e.g.[1]: > > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): >re

Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-23 Thread Steven Bethard
Bengt Richter wrote: On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote: Steven Bethard wrote: I wrote: > If you really want locals that don't contribute to arguments, I'd be > much happier with something like a decorator, e.g.[1]: > > @with_co

Re: finding name of instances created

2005-01-23 Thread Steven Bethard
Michael Tobis wrote: I have a similar problem. Here's what I do: .def new_robot_named(name,indict=globals()): . execstr = name + " = robot('" + name + "')" . exec(execstr,indict) .class robot(object): . def __init__(self,name): . self.name = name . def sayhi(self): . print "Hi! I

Re: finding name of instances created

2005-01-23 Thread Steven Bethard
Nick Coghlan wrote: It also directly addresses the question of aliasing. Think about how Steven's modified dictionary would react to this code: pete = CreateRobot(2, 3) dad = pete dad.move() pete.move() If you'd like to handle these cases, but you don't want to have to explain aliasing right off

Re: What is print? A function?

2005-01-23 Thread Steven Bethard
Frans Englich wrote: The reason I thinks about this is I need to implement a debug print for my program; very simple, a function/print statement that conditionally prints its message whether a bool is true. Not overly complex. Sounds like you want to override sys.stdout: py> class ConditionalWrit

Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-23 Thread Steven Bethard
Bengt Richter wrote: So, e.g., for >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) in the decorator args, the next version will act as if the decorated function had the source code >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) a, b, deftime = __frompresets__ for

Re: best way to do a series of regexp checks with groups

2005-01-24 Thread Steven Bethard
Alex Martelli wrote: class ReWithMemory(object): def search(self, are, aline): self.mo = re.search(are, aline) return self.mo def group(self, n): return self.mo.group(n) m = ReWithMemory() if m.search(r'add (\d+) (\d+)', line): do_add(m.group(1), m.group(2)) elif

"private" variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-24 Thread Steven Bethard
Philippe C. Martin wrote: > class Debug_Stderr: > __m_text = '' > __m_log_text = None > __m_dbg = None > __m_refresh_count = 0 I don't see the benefit in 99.9% of cases for making class variables like this "private". If you don't want people to use them, simply use the standard conventi

Re: Tuple slices

2005-01-24 Thread Steven Bethard
Fredrik Lundh wrote: George Sakkis wrote: Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that tuples are immutable ? really? a = 1, 2, 3 b = a[:] a is b True My impression was that full tuple copies didn't actually copy, but that slicing a subset of a t

Re: Tuple slices

2005-01-24 Thread Steven Bethard
Fredrik Lundh wrote: Steven Bethard wrote: My impression was that full tuple copies didn't actually copy, but that slicing a subset of a tuple might. Not exactly sure how to test this, but: py> a = 1, 2, 3 py> a[:2] is a[:2] False yup. and to figure out why things are done this wa

Re: Instances of class object not modifiable?

2005-01-24 Thread Steven Bethard
given me a PEP number for it yet, but a patch is available[1] and I've included the current draft of the PEP below. [1]http://sourceforge.net/tracker/?func=detail&atid=305470&aid=1094542&group_id=5470 Steve ---------- PEP: XXX Title: G

Re: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?)

2005-01-24 Thread Steven Bethard
Philippe C. Martin wrote: I used double underscore because I thought it was the correct way to name private variables/methods - I will have to change those to single underscore since that it the current methodology. A private variable to me: 1) is internal to the processing of a class and needs not

Re: Classical FP problem in python : Hamming problem

2005-01-25 Thread Steven Bethard
Nick Craig-Wood wrote: Thinking about this some more leads me to believe a general purpose imerge taking any number of arguments will look neater, eg def imerge(*generators): values = [ g.next() for g in generators ] while True: x = min(values) yield x for i in range

Re: Classical FP problem in python : Hamming problem

2005-01-25 Thread Steven Bethard
Nick Craig-Wood wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: Nick Craig-Wood wrote: Thinking about this some more leads me to believe a general purpose imerge taking any number of arguments will look neater, eg def imerge(*generators): values = [ g.next() for g in generators ] whil

Re: specifying constants for a function (WAS: generator expressions: performance anomaly?)

2005-01-25 Thread Steven Bethard
Bengt Richter wrote: On Mon, 24 Jan 2005 20:35:09 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote: from presets import presets, curry @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) ... def foo(): ...print (a, b) ...print deftime ... presets: -- "name(?)" means name may be

Re: "private" variables a.k.a. name mangling (WAS: What is print? A function?)

2005-01-25 Thread Steven Bethard
Toby Dickenson wrote: I have a counterexample. Consider refactoring a class from class B(A): etc into class C(A): etc class B(C): etc Usage of some double-undescore attributes moved from B to the new intermediate base class C. Unit tests on B still passed, so that change is

limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Steven Bethard
Fuzzyman wrote: > Cameron Laird wrote: > [snip..] > >>This is a serious issue. >> >>It's also one that brings Tcl, mentioned several >>times in this thread, back into focus. Tcl presents >>the notion of "safe interpreter", that is, a sub- >>ordinate virtual machine which can interpret only >>speci

Re: How to input one char at a time from stdin?

2005-01-25 Thread Steven Bethard
Swaroop C H wrote: On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes <[EMAIL PROTECTED]> wrote: I'd like to get a character from stdin, perform some action, get another character, etc. If I just use stdin.read(1), it waits until I finish typing a whole line before I can get the first character.

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Steven Bethard
Michael Spencer wrote: Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 This recipe only evaluates constant expressions: "Description: Evaluate constant expressions, including list, dict and tuple using the abstract syntax tree created by compiler

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-25 Thread Steven Bethard
Michael Spencer wrote: Steven Bethard wrote: Michael Spencer wrote: Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 This recipe only evaluates constant expressions [snip Indeed. But it's easy to extend this to arbitrary constructs. You

Re: python without OO

2005-01-25 Thread Steven Bethard
Davor wrote: Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Hmmm... sorta depends on how you define write procedural code... If you mean, can you write Python code w

Re: string.atoi and string.atol broken?

2005-01-25 Thread Steven Bethard
Mike Moum wrote: s.atoi('4',3) Traceback (most recent call last): File "", line 1, in -toplevel- s.atoi('4',3) File "/usr/lib/python2.3/string.py", line 220, in atoi return _int(s, base) ValueError: invalid literal for int(): 4 What did you expect the value of '4' in base 3 to be? Ther

Re: Where can I find Mk4py.dll for python24 ?

2005-01-25 Thread Steven Bethard
Jose Rivera wrote: I installed the new release and I have not been able to make work metakit. Please give me some help to enjoy metakit and python 24. Repeating your request every 10 minutes is not likely to get you help quicker. On the contrary, it's more likely to make people ignore your threa

Re: Help With Python

2005-01-26 Thread Steven Bethard
Thomas Guettler wrote: Am Wed, 26 Jan 2005 15:55:28 + schrieb Judi Keplar: I am currently taking a course to learn Python and was looking for some help. I need to write a Python statement to print a comma- separated repetition of the word, "Spam", written 511 times ("Spam, Spam, ï Spam").

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-26 Thread Steven Bethard
Jack Diederich wrote: Yes, this comes up every couple months and there is only one answer: This is the job of the OS. Java largely succeeds at doing sandboxy things because it was written that way from the ground up (to behave both like a program interpreter and an OS). Python the language was not

Re: inherit without calling parent class constructor?

2005-01-26 Thread Steven Bethard
Christian Dieterich wrote: Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does s

Re: inherit without calling parent class constructor?

2005-01-26 Thread Steven Bethard
Christian Dieterich wrote: The size attribute only needs to be computed once and stays constant after that. The lazy property recipe of Scott David Daniels looks promising. I'll try that, when I've installed Python 2.4. However, I need my package to work on machines where there is Python 2.2 and

Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-26 Thread Steven Bethard
Jack Diederich wrote: On Wed, Jan 26, 2005 at 10:23:03AM -0700, Steven Bethard wrote: Jack Diederich wrote: Yes, this comes up every couple months and there is only one answer: This is the job of the OS. Java largely succeeds at doing sandboxy things because it was written that way from the

Re: access private field in python 2.4

2005-01-26 Thread Steven Bethard
[EMAIL PROTECTED] wrote: Hello, if we want to access the private member of object we use the classname, it doesn't make sense. For example: I have class A: class A: def __init__(self, i): self.__i = i; pass __i = 0 a = A(22); b = A(33); How can I get field i in object a and how can I get field i i

Re: can not use __methods__

2005-01-26 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I try to use __methods__ in python 2.4 and 2.2 it always fail. Can some one tell me if I want to itterate the methods in a class and print it in a string format ( it is possible using __methods__ ). Is there any replacement? py> class C(object): ... a = 1 ... b = 2

Re: Help With Python

2005-01-26 Thread Steven Bethard
Nick Vargish wrote: Here's my Monty Pythonic answer: ## cut here class Viking(): def __init__(): pass def order(): return 'Spam' # this is one viking making one order repeated 511 times. if you want # 511 vikings making seperate orders, you'll have to write a loop. v = Vikin

Re: inherit without calling parent class constructor?

2005-01-26 Thread Steven Bethard
Christian Dieterich wrote: On Dé Céadaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard wrote: Note that: @deco def func(...): ... is basically just syntactic sugar for: def func(...): ... func = deco(func) Oh, I learned something new today :-) Nice

Re: Classical FP problem in python : Hamming problem

2005-01-26 Thread Steven Bethard
Francis Girard wrote: For the imerge function, what we really need to make the formulation clear is a way to look at the next element of an iteratable without consuming it. Or else, a way to put back "consumed" elements in the front an iteration flow, much like the list constructors in FP langua

Re: String Fomat Conversion

2005-01-26 Thread Steven Bethard
Stephen Thorne wrote: f = file('input', 'r') labels = f.readline() # consume the first line of the file. Easy Option: for line in f.readlines(): x, y = line.split() x = float(x) y = float(y) Or, more concisely: for line in f.readlines(): x, y = map(float, line.split()) Somewhat more memory

Re: String Fomat Conversion

2005-01-27 Thread Steven Bethard
Stephen Thorne wrote: I did all I did in the name of clarity, considering the OP was on his first day with python. How I would actually write it would be: inputfile = file('input','r') inputfile.readline() data = [map(float, line.split()) for line in inputfile] Notice how you don't have to call ite

Re: Help With Python

2005-01-27 Thread Steven Bethard
Nick Craig-Wood wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: py> orders = [Viking().order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Thats still one Viking making 7 orders surely? So you want this... orders = [ Viking().order()

Re: String Fomat Conversion

2005-01-27 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: ... Beware of mixing iterator methods and readline: [snip] I hope this concisely indicates that the problem (in today's current implementations) is only with switching FROM iteration TO other approaches to reading, and (

Re: Question about 'None'

2005-01-27 Thread Steven Bethard
flamesrock wrote: The statement (1 > None) is false (or any other value above 0). Why is this? What code are you executing? I don't get this behavior at all: py> 100 > None True py> 1 > None True py> 0 > None True py> -1 > None True py> -100 > None True (The reason I ask is sortof unrelated. I wan

Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote: Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit : flamesrock wrote: The statement (1 > None) is false (or any other value above 0). Why is this? What code are you executing? I don't get this behavior at all: py> 100 > None True py> 1 > None True

Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote: Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit : So None being smaller than anything (except itself) is hard-coded into Python's compare routine. My suspicion is that even if/when objects of different types are no longer comparable by default (as has been sugg

Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote: I see. There is some rule stating that all the strings are greater than ints and smaller than lists, etc. Yes, that rule being to compare objects of different types by their type names (falling back to the address of the type object if the type names are the same, I believe

Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote: a = "10" b = 10 a > b True b > a False id(a) 1077467584 id(b) 134536516 Just to thoroughly explain this example, the current CPython implementation says that numbers are smaller than everything but None. The reason you get such a small id for 'b' is that there is only one 10

Re: String Fomat Conversion

2005-01-27 Thread Steven Bethard
enigma wrote: Do you really need to use the iter function here? As far as I can tell, a file object is already an iterator. The file object documentation says that, "[a] file object is its own iterator, for example iter(f) returns f (unless f is closed)." It doesn't look like it makes a differen

Re: Why do look-ahead and look-behind have to be fixed-width patterns?

2005-01-27 Thread Steven Bethard
John Machin wrote: To grab the text after the 2nd colon (if indeed there are two or more), it's much simpler to do this: import re q = re.compile(r'.*?:.*?:(.*)').search def grab(s): ...m = q(s) ...if m: ... print m.group(1) ...else: ... print 'not found!' ... grab('') not f

Re: limited python virtual machine

2005-01-28 Thread Steven Bethard
Alex Martelli wrote: Steven Bethard <[EMAIL PROTECTED]> wrote: ... If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) to 'eval' or '__import__', that would help out a lot... object.__subclasses__() [, , ,

Re: bound vs unbound functions

2005-01-29 Thread Steven Bethard
Michael Tobis wrote: Anyway, I'd like to dynamically add a method to an instance at instantiation time. Something like Nearly identical question from yesterday and a series of answers: http://mail.python.org/pipermail/python-list/2005-January/263024.html Steve -- http://mail.python.org/mailman/list

Re: how do i create such a thing?

2005-01-30 Thread Steven Bethard
Pedro Werneck wrote: If you need direct access to some atribute, use object.__getattribute__. class DefaultAttr(object): ... def __init__(self, default): ... self.default = default ... def __getattribute__(self, name): ... try: ... value = object.__getattribute_

Re: Problem with loading textfiles into dictionaries.

2005-01-30 Thread Steven Bethard
Kartic wrote: [EMAIL PROTECTED] said the following on 1/30/2005 7:43 PM: Hello, I want to do the following: def do_load(self, arg): sitefile = file('sitelist', 'r+', 1) while True: siteline = sitefile.readline() site_rawlist = siteline.split() sitelist[site_rawlist[0]] = site_rawlist[1:] if len(sit

Re: a Python bug in processing __del__ method ??

2005-01-30 Thread Steven Bethard
Baoqiu Cui wrote: Today I was playing with a small Python program using Python 2.4 on Cygwin (up-to-date version, on Windows XP), but ran into a strange error on the following small program (named bug.py): --- #!/usr/bin/python class Person: population = 0 def __del__(se

Re: a Python bug in processing __del__ method ??

2005-01-30 Thread Steven Bethard
Fredrik Lundh wrote: Baoqiu Cui wrote: The error returned is this: $ python bug.py Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored However, if I rename variable name 'peter' to something like 'peter1' or 'david', the error is gone. Looks to me th

Re: Nested scopes and class variables

2005-01-31 Thread Steven Bethard
Alex Martelli wrote: def f(x): ... class C: ... x = x ... return C ... [snip] def f(x): ... def g(): ... x = x ... return x ... return g ... [snip] See the difference? In a function, the 'x = x' compiles into LOAD_FAST, STORE_FAST, which only looks at locals and nowhere el

Re: re module - cannot make expression

2005-01-31 Thread Steven Bethard
Laszlo Zsolt Nagy wrote: I would like to match strings not beginning with '/webalizer'. How can I do this? Are you sure you need a regular expression? The str.startswith method is what I would normally use to solve this kind of problem: py> lst = ['aax', 'abx', 'acx', 'aay', 'aby', 'acy'] py> [

Re: how to access class methods via their name-as-string

2005-01-31 Thread Steven Bethard
[EMAIL PROTECTED] wrote: I'd like to be able to look up a method name by passing a string with the method name. Use getattr: py> class A(object): ... def f(self): ... pass ... def g(self): ... pass ... py> class B(A): ... def h(self): ... pass ... py> getattr(B()

Re: Python's idiom for function overloads

2005-01-31 Thread Steven Bethard
Frans Englich wrote: But in Python, when one wants to be able to pass different data types into a single "entry point" for functionality, how is that best done? To in a function do an if statement with the type() function? It often depends a lot on the specific use case... Do you have a partic

Re: Next step after pychecker

2005-01-31 Thread Steven Bethard
Philippe Fremy wrote: I would like to develop a tool that goes one step further than pychecker to ensure python program validity. The idea would be to get close to what people get on ocaml: a static verification of all types of the program, without any kind of variable declaration. This would de

Re: a sequence question

2005-01-31 Thread Steven Bethard
Nick Coghlan wrote: I'd definitely recommend hiding this trick inside a function. Perhaps something like (using Michael's function name): from itertools import izip, repeat, chain def partition(seq, part_len): return izip(*((iter(seq),) * part_len)) def padded_partition(seq, part_len, pad_val=N

Re: permutations, patterns, and probability

2005-02-01 Thread Steven Bethard
kpp9c wrote: Greetings, I am working on a program to produce patterns. What would like is for it to exhaustively produce all possible permutations of a sequence of items but for each permutation produce variations, and also a sort of stutter based on probability / weighted randomess. Let us say we

Re: Next step after pychecker

2005-02-01 Thread Steven Bethard
Terry Reedy wrote: > Nothing about bytecode is part of the language spec. And CPython > bytecode is version specific. If the CPython implementation changed > from a virtual stack machine to a virtual register machine, as was > once discussed, the stack-oriented byte code would be replaced by a >

Re: a quick question about namespaces

2005-02-01 Thread Steven Bethard
Jay donnell wrote: in the code below 'print locals()' shows mc2. What is the equivalent way to see the namespace that mc resides in? class myClass: --def func1(self): self.mc = 1 mc2 = 3 print 'in myClass.func1' print 'printing locals' print locals() print I think you're loo

Re: Hash of class from instance

2005-02-02 Thread Steven Bethard
Mick Krippendorf wrote: In Python there seems to be no guarantee that different objects also have different hash values. Well, it's true that you can override the __hash__ method to do whatever you want, but I believe the default for class __hash__ methods is to return the class id, which should

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