Re: Porting the 2-3 heap data-structure library from C to Python

2012-03-10 Thread Hrvoje Niksic
Stefan Behnel writes: >> which is the standard way of extending Python with high-performance >> (and/or system-specific) C code. > > Well, it's *one* way. Certainly not the easiest way, neither the most > portable and you'll have a hard time making it the fastest. I didn't say it was easy, but

Re: Porting the 2-3 heap data-structure library from C to Python

2012-03-07 Thread Hrvoje Niksic
Alec Taylor writes: > The source-code used has been made available: > http://www.cosc.canterbury.ac.nz/research/RG/alg/ttheap.h > http://www.cosc.canterbury.ac.nz/research/RG/alg/ttheap.c > > I plan on wrapping it in a class. You should get acquainted with the Python/C API, which is the standard

Re: round down to nearest number

2012-02-11 Thread Hrvoje Niksic
Terry Reedy writes: > On 2/9/2012 8:23 PM, noydb wrote: >> So how would you round UP always? Say the number is 3219, so you want (//100+1)*100 > 3400 Note that that doesn't work for numbers that are already round: >>> (3300//100+1)*100 3400# 3300 would be correct I'd go with Chri

Re: copy on write

2012-02-02 Thread Hrvoje Niksic
Steven D'Aprano writes: > Perhaps you are thinking that Python could determine ahead of time > whether x[1] += y involved a list or a tuple, and not perform the > finally assignment if x was a tuple. Well, maybe, but such an approach > (if possible!) is fraught with danger and mysterious errors e

Re: while True or while 1

2012-01-23 Thread Hrvoje Niksic
Dave Angel writes: > I do something similar when there's a portion of code that should > never be reached: > > assert("reason why I cannot get here") Shouldn't that be assert False, "reason why I cannot get here"? -- http://mail.python.org/mailman/listinfo/python-list

Re: unzip function?

2012-01-18 Thread Hrvoje Niksic
Neal Becker writes: > python has builtin zip, but not unzip > > A bit of googling found my answer for my decorate/sort/undecorate problem: > > a, b = zip (*sorted ((c,d) for c,d in zip (x,y))) > > That zip (*sorted... > > does the unzipping. > > But it's less than intuitively obvious. > > I'm thi

Re: order independent hash?

2011-12-09 Thread Hrvoje Niksic
Steven D'Aprano writes: > Except for people who needed dicts with tens of millions of items. Huge tree-based dicts would be somewhat slower than today's hash-based dicts, but they would be far from unusable. Trees are often used to organize large datasets for quick access. The case of dicts wh

Re: order independent hash?

2011-12-08 Thread Hrvoje Niksic
Tim Chase writes: > From an interface perspective, I suppose it would work. However one > of the main computer-science reasons for addressing by a hash is to > get O(1) access to items (modulo pessimal hash structures/algorithms > which can approach O(N) if everything hashes to the same > value/

Re: order independent hash?

2011-12-07 Thread Hrvoje Niksic
Chris Angelico writes: > 2011/12/5 Hrvoje Niksic : >> If a Python implementation tried to implement dict as a tree, >> instances of classes that define only __eq__ and __hash__ would not >> be correctly inserted in such a dict. > > Couldn't you just make a t

Re: order independent hash?

2011-12-04 Thread Hrvoje Niksic
Terry Reedy writes: >> [Hashing is] pretty much mandated because of the __hash__ protocol. > > Lib Ref 4.8. Mapping Types — dict > "A mapping object maps hashable values to arbitrary objects." > > This does not say that the mapping has to *use* the hash value ;-). > Even if it does, it could use

Re: order independent hash?

2011-12-02 Thread Hrvoje Niksic
Chris Angelico writes: >> The hash can grow with (k,v) pairs accumulated in the run time. >> An auto memory management mechanism is required for a hash of a non-fixed >> size of (k,v) pairs. > > That's a hash table In many contexts "hash table" is shortened to "hash" when there is no ambiguity.

Re: unpack('>f', b'\x00\x01\x00\x00')

2011-12-01 Thread Hrvoje Niksic
Chris Rebert writes: > C does not have a built-in fixed-point datatype, so the `struct` > module doesn't handle fixed-point numbers directly. The built-in decimal module supports fixed-point arithmetic, but the struct module doesn't know about it. A bug report (or patch) by someone who works wi

Re: Server Questions (2 of them)

2011-11-20 Thread Hrvoje Niksic
Andrew writes: > How to do you create a server that accepts a set of user code? [...] Look up the "exec" statement, the server can use it to execute any code received from the client as a string. Note "any code", though; exec runs in no sandbox and if a malicious client defines addition(1, 2) t

Re: Dictionary sorting

2011-11-04 Thread Hrvoje Niksic
Ben Finney writes: > Tim Chase writes: > >> On 11/03/11 16:36, Terry Reedy wrote: >> > CPython iterates (and prints) dict items in their arbitrary internal >> > hash table order, which depends on the number and entry order of the >> > items. It is a bug to depend on that arbitrary order in any w

Re: __dict__ attribute for built-in types

2011-10-28 Thread Hrvoje Niksic
candide writes: > Le 28/10/2011 00:57, Hrvoje Niksic a écrit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> > > Is it possible in the CPython implementation to write something

Re: __dict__ attribute for built-in types

2011-10-27 Thread Hrvoje Niksic
candide writes: > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? str, list and others aren't classes, they are types. While all (new-style) classes are types, not all types are classes. It's instances of classes (types created by executing the "cla

Re: list comprehension to do os.path.split_all ?

2011-07-30 Thread Hrvoje Niksic
Neil Cerutti writes: > On 2011-07-29, Dennis Lee Bieber wrote: >> Fine... So normpath it first... >> > os.path.normpath(r'C:/windows').split(os.sep) >> ['C:', 'windows'] That apparently doesn't distinguish between r'C:\windows' and r'C:windows'. On Windows the first is an absolute pat

Re: Convert '165.0' to int

2011-07-22 Thread Hrvoje Niksic
Frank Millman writes: > int(float(x)) does the job, and I am happy with that. I was just > asking if there were any alternatives. int(float(s)) will corrupt integers larger than 2**53, should you ever need them. int(decimal.Decimal(s)) works with numbers of arbitrary size. -- http://mail.pytho

Re: Possible File iteration bug

2011-07-14 Thread Hrvoje Niksic
Billy Mays writes: > Is there any way to just create a new generator that clears its > closed` status? You can define getLines in terms of the readline file method, which does return new data when it is available. def getLines(f): lines = [] while True: line = f.readline()

Re: How does CO_FUTURE_DIVISION compiler flag get propagated?

2011-07-02 Thread Hrvoje Niksic
Terry writes: > Future division ("from __future__ import division") works within > scripts executed by import or execfile(). However, it does not work > when entered interactively in the interpreter like this: > from __future__ import division a=2/3 Are you referring to the interactive

Re: Python and Lisp : car and cdr

2011-06-19 Thread Hrvoje Niksic
Ethan Furman writes: >> def car(L): >> return L[0] >> def cdr(L): >> return L[1] > > IANAL (I am not a Lisper), but shouldn't that be 'return L[1:]' ? Not for the linked list implementation he presented. >> def length(L): >> if not L: return 0 >> return 1 + length(cdr(L)) > > Ho

Re: What other languages use the same data model as Python?

2011-05-03 Thread Hrvoje Niksic
Steven D'Aprano writes: > "Python's data model is different from other languages" > > which is perfectly correct, if you think of C as "other languages". But > it's equally correct to say that Python's data model is the same as other > languages. As I understand it, Python and Ruby have the sam

Re: generator / iterator mystery

2011-03-13 Thread Hrvoje Niksic
Dave Abrahams writes: list(chain( *(((x,n) for n in range(3)) for x in 'abc') )) > [('c', 0), ('c', 1), ('c', 2), ('c', 0), ('c', 1), ('c', 2), ('c', 0), ('c', > 1), ('c', 2)] > > Huh? Can anyone explain why the last result is different? list(chain(*EXPR)) is constructing a tuple out of

Re: Use-cases for alternative iterator

2011-03-10 Thread Hrvoje Niksic
Steven D'Aprano writes: > I've never seen this second form in actual code. Does anyone use it, > and if so, what use-cases do you have? Since APIs that signal end-of-iteration by returning a sentinel have fallen out of favor in Python (with good reason), this form is rare, but still it's sometim

Re: Parameterized functions of no arguments?

2011-02-11 Thread Hrvoje Niksic
Chris Rebert writes: > It's a well-known problem due to the intricacies of Python's scoping > rules. Actually, it is not specific to Python's scoping rules (which mandate local, then module-level, then built-in name lookup). The root of the surprise is, as you correctly point out, the fact that

Re: Perl Hacker, Python Initiate

2011-02-03 Thread Hrvoje Niksic
Gary Chambers writes: > Will someone please provide some insight on how to accomplish that > task in Python? I am unable to continually (i.e. it stops after > displaying a single line) loop through the output while testing for > the matches on the two regular expressions. Thank you. If I under

Re: Resolve circular reference

2011-01-14 Thread Hrvoje Niksic
Magnus Lyckå writes: a = X() del a > Deleted <__main__.X instance at 0x00CCCF80> a=X() b=X() a.b=b b.a=a del a gc.collect() > 0 del b gc.collect() > 4 If your method has a __del__ at all, the automatic cyclic collector is disabled. It detects th

Re: list 2 dict?

2011-01-02 Thread Hrvoje Niksic
"Octavian Rasnita" writes: > If I want to create a dictionary from a list, is there a better way than the > long line below? > > l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b'] > > d = dict(zip([l[x] for x in range(len(l)) if x %2 == 0], [l[x] for x in > range(len(l)) if x %2 == 1])) > > print(d) > > {8

Re: Interning own classes like strings for speed and size?

2010-12-29 Thread Hrvoje Niksic
Christian Heimes writes: > You are right as long as you don't try to rebind the variable. And then only if you assign through an instance, which doesn't make sense for a class-level cache. Assignment like Example2._cache = {} would work. -- http://mail.python.org/mailman/listinfo/python-list

Re: Interning own classes like strings for speed and size?

2010-12-28 Thread Hrvoje Niksic
Christian Heimes writes: > Also this code is going to use much more memory than an ordinary tuple > since every instance of InternedTuple has a __dict__ attribute. This > code works but I had to move the cache outside the class because of > __slots__. Wouldn't it work inside the class as well?

Re: round in 2.6 and 2.7

2010-12-24 Thread Hrvoje Niksic
"Martin v. Loewis" writes: >> Type "help", "copyright", "credits" or "license" for more information. > 9.95 >> 9.9493 > "%.16g" % 9.95 >> '9.949' > round(9.95, 1) >> 10.0 >> >> So it seems that Python is going out of its way to intuitively round >> 9.95, while

round in 2.6 and 2.7

2010-12-23 Thread Hrvoje Niksic
I stumbled upon this. Python 2.6: Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 9.95 9.9493 >>> "%.16g" % 9.95 '9.949' >>> round(9.95, 1) 10.0 So it seems that Python is go

"encoding" attribute codecs.getwriter-produced streams

2010-12-20 Thread Hrvoje Niksic
Try this code: # foo.py import sys, codecs stream = codecs.getwriter('utf-8')(sys.stdout) print stream.encoding $ python foo.py | cat None I expected the `encoding' attribute to be "UTF-8", since the stream otherwise correctly functions as a utf-8 encoding stream. Is this a bug in the stream fa

Re: Exception handling in Python 3.x

2010-12-03 Thread Hrvoje Niksic
Peter Otten <__pete...@web.de> writes: >> Note that StopIteration is an internal detail of no relevance whatsoever >> to the caller. Expose this is unnecessary at best and confusing at worst. > > http://mail.python.org/pipermail/python-list/2010-October/1258606.html > http://mail.python.org/piperm

Re: Exception handling in Python 3.x

2010-12-03 Thread Hrvoje Niksic
Steven D'Aprano writes: > Consider the following common exception handling idiom: > > def func(iterable): > it = iter(iterable) > try: > x = next(it) > except StopIteration: > raise ValueError("can't process empty iterable") > print(x) Not exactly what you're look

Re: Collect output to string

2010-11-24 Thread Hrvoje Niksic
Burton Samograd writes: > Terry Reedy writes: > >> On 11/23/2010 3:02 PM, Chris Rebert wrote: >> If you are using print or print(), you can redirect output to the >> StringIO object with >>sfile or file=sfile. I use the latter in a >> custom test function where I normally want output to the scre

Re: what's the precision of fractions.Fraction?

2010-11-20 Thread Hrvoje Niksic
Mark Dickinson writes: > On Nov 19, 3:29 pm, RJB wrote: >> Does Fractions remove common factors the way it should? >> >> If it does and you want to find the closest fraction with a smaller >> denominator i think tou'll need some number theory and continued >> fractions. > > Or perhaps just use t

Re: with HTTPConnection as conn:

2010-11-18 Thread Hrvoje Niksic
Antoine Pitrou writes: > On Thu, 18 Nov 2010 12:46:07 +0100 > trylks wrote: >> Hi! >> >> Would it be possible to use a with statement with an HTTPConnection object? >> >> I know it is not possible at this moment, it doesn't implement an >> __exit__ method, at least in version 3.1.1. I was wond

Re: strange behavor....

2010-11-16 Thread Hrvoje Niksic
m...@distorted.org.uk (Mark Wooding) writes: >> So even if the globals() dictionary is custom, its __setitem__ method is >> *not* called. > > Fascinating. Thank you. In case it's not obvious, that is because CPython assumes the type for many of its internal or semi-internal structures, and calls

Re: Some syntactic sugar proposals

2010-11-15 Thread Hrvoje Niksic
Dmitry Groshev writes: > which looks almost like a natural language. But there is some > pitfalls: > if x in range(a, b): #wrong! > it feels so natural to check it that way, but we have to write > if a <= x <= b For the record, you have to write: if a <= x < b: Ranges are open on t

Re: Is Eval *always* Evil?

2010-11-10 Thread Hrvoje Niksic
Robert Kern writes: > On 2010-11-10 15:52 , Hrvoje Niksic wrote: >> Simon Mullis writes: >> >>> If "eval" is not the way forward, are there any suggestions for >>> another way to do this? >> >> ast.literal_eval might be the thing for you. &

Re: Is Eval *always* Evil?

2010-11-10 Thread Hrvoje Niksic
Simon Mullis writes: > If "eval" is not the way forward, are there any suggestions for > another way to do this? ast.literal_eval might be the thing for you. -- http://mail.python.org/mailman/listinfo/python-list

Re: Silly newbie question - Carrot character (^)

2010-11-06 Thread Hrvoje Niksic
Seebs writes: > On 2010-11-06, Hrvoje Niksic wrote: >> I don't speak for "Nobody", but to me a reference manual would be a >> document intended for the user of the language. The thing for the >> language lawyer is something intended for the implementor,

Re: Silly newbie question - Carrot character (^)

2010-11-06 Thread Hrvoje Niksic
Seebs writes: > I'm a bit lost here. Could you highlight some of the differences > between "a reference manual for the language itself" and "something > written for language lawyers"? I don't speak for "Nobody", but to me a reference manual would be a document intended for the user of the langu

Re: Man pages and info pages

2010-11-03 Thread Hrvoje Niksic
Teemu Likonen writes: > Enter Follow a link (down to node) > u up node level > h help (general how-to) > ? help (commands) > s search And don't forget: l last viewed page (aka "back") That one seems to be the info reader's best-kept sec

Re: functions, list, default parameters

2010-11-03 Thread Hrvoje Niksic
Paul Rudin writes: > Terry Reedy writes: > >> Suppose I write an nasty C extension that mutates tuples. What then >> would be illegal about... > > Depends on exactly what we mean by legal. If immutability is part of the > language spec (rather than an artifact of a particular implementation) > t

Re: factorial of negative one (-1)

2010-11-02 Thread Hrvoje Niksic
Ken Watford writes: > 1.1 .as_integer_ratio() >> (2476979795053773, 2251799813685248) > > Handy, but if you need the exact representation, my preference is > float.hex, which seems to be the same as C99's %a format. [...] > Granted, it's not as easy for humans to interpret, but it's useful fo

Re: factorial of negative one (-1)

2010-11-01 Thread Hrvoje Niksic
Chris Rebert writes: > (2) The underlying double-precision floating-point number only has ~16 > decimal digits of precision, so it's pointless to print out "further" > digits. A digression which has nothing to do with Raj's desire for "better accuracy"... Printing out further digits (without qu

Re: Multilingual documentation solutions

2010-10-27 Thread Hrvoje Niksic
Astley Le Jasper writes: > At the moment I'm producing a word document with screenshots that gets > translated, but this is getting very difficult to control, especially > tracking small content changes and translations. I don't know if you considered this, but you might want to look into Restru

Re: downcasting problem

2010-10-26 Thread Hrvoje Niksic
John Nagle writes: > On 10/25/2010 7:38 AM, Tim Chase wrote: >> While a dirty hack for which I'd tend to smack anybody who used it...you >> *can* assign to instance.__class__ > >That's an implementation detail of CPython. May not work in > IronPython, Unladen Swallow, PyPy, or Shed Skin. > >

Re: Has Next in Python Iterators

2010-10-25 Thread Hrvoje Niksic
Kelson Zawack writes: > Iterators however are a different beast, they are returned by the > thing they are iterating over and thus any special cases can be > covered by writing a specific implementation for the iterable in > question. This sort of functionality is possible to implement, > becaus

mro() or __mro__?

2010-10-23 Thread Hrvoje Niksic
The documentation of the mro() method on the class object says: class.mro() This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__. Am I interpreting it correctly

Re: how to scrutch a dict()

2010-10-21 Thread Hrvoje Niksic
Joost Molenaar writes: > Using a 2.7/3.x dictionary comprehension, since you don't seem to mind > creating a new dictionary: > > def _scrunched(d): >     return { key: value for (key, value) in d.items() if value is not None } Note that a dict comprehension, while convenient, is not necessary fo

Re: overriding a property

2010-10-20 Thread Hrvoje Niksic
Lucasm writes: > Thanks for the answers. I would like to override the property though > without making special modifications in the main class beforehand. Is > this possible? That will not be easy. When you access obj.return_five, python looks up 'return_five' in type(obj) to see what the retur

Re: Unicode questions

2010-10-19 Thread Hrvoje Niksic
Tobiah writes: > would be shared? Why can't we just say "unicode is unicode" > and just share files the way ASCII users do. Just have a huge > ASCII style table that everyone sticks to. I'm not sure that I understand you correctly, but UCS-2 and UCS-4 encodings are that kind of thing. Many pe

Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith writes: >> echo (-echo) >> Echo back (do not echo back) every character typed. > > I'm going to guess that the percent sign in your prompt indicates that > you're using zsh(1). With my minimally-customized zsh, the echo > option is reset every time the prompt is dis

Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith writes: > On Tue, Oct 19, 2010 at 1:37 PM, kj wrote: > >> % stty -echo > > That doesn't do what you think it does. Really? Turning off tty echo sounds exactly like what he wants. Emacs shell echoes characters for you, just like interactive shells do. When you press enter, the charac

Re: How is correct use of eval()

2010-10-12 Thread Hrvoje Niksic
Nobody writes: > Oh, look what's "new in version 2.6": > > > ast.literal_eval("7") > 7 > > ast.literal_eval("7") == 7 > True Note that it doesn't work for some reasonable inputs involving unary and binary plus, such as "[-2, +1]" or "2+3j". This has been fixed in the dev

Re: harmful str(bytes)

2010-10-12 Thread Hrvoje Niksic
Stefan Behnel writes: > Hallvard B Furuseth, 11.10.2010 23:45: >> If there were a __plain_str__() method which was supposed to fail rather >> than start to babble Python syntax, and if there were not plenty of >> Python code around which invoked __str__, I'd agree. > > Yes, calling str() "just in

Re: if the else short form

2010-10-10 Thread Hrvoje Niksic
Antoon Pardon writes: > Personaly I don't see a reason to declare in advance that someone > who wants to treat "True" differently from non-zero numbers or > non-empty sequences and does so by a test like: > > if var == Trueorif var is True > > to have written incorrect code. I wouldn't

Re: hashkey/digest for a complex object

2010-10-10 Thread Hrvoje Niksic
Arnaud Delobelle writes: > I have learnt too that hash(-1) is not (-1), and that it seems that a > hash value is not allowed to be (-1). There is one thing left to find > out. Why can't it be (-1)? Because -1 has a special meaning in the C function equivalent to Python's hash(). PyObject_Hash

Re: hashkey/digest for a complex object

2010-10-10 Thread Hrvoje Niksic
Steven D'Aprano writes: > On Sat, 09 Oct 2010 21:39:51 +0100, Arnaud Delobelle wrote: > >> 1. hash() is an idempotent function, i.e. hash(hash(x)) == hash(x) hold >> for any hashable x (this is a simple consequence of the fact that >> hash(x) == x for any int x (by 'int' I mean 2.X int)). > > It'

Re: Many newbie questions regarding python

2010-10-09 Thread Hrvoje Niksic
alex23 writes: > If anything, I feel like the list comp version is the correct solution > because of its reliability, whereas the multiplication form feels like > either a lucky naive approach or relies on the reader to know the type > of the initialising value and its mutability. Other than lis

Re: About __class__ of an int literal

2010-09-29 Thread Hrvoje Niksic
Steven D'Aprano writes: > On Wed, 29 Sep 2010 02:20:55 +0100, MRAB wrote: > >> On 29/09/2010 01:19, Terry Reedy wrote: > >>> A person using instances of a class should seldom use special names >>> directly. They are, in a sense, implementation details, even if >>> documented. The idiom "if __name

Re: if the else short form

2010-09-29 Thread Hrvoje Niksic
Tracubik writes: > Hi all, > I'm studying PyGTK tutorial and i've found this strange form: > > button = gtk.Button(("False,", "True,")[fill==True]) > > the label of button is True if fill==True, is False otherwise. The tutorial likely predates if/else expression syntax introduced in 2.5, which w

Re: Overriding dict constructor

2010-09-20 Thread Hrvoje Niksic
Christian Heimes writes: > Am 20.09.2010 13:11, schrieb Steven D'Aprano: >> I have a dict subclass that associates extra data with each value of the >> key/value items: > [...] >> How can I fix this? > > Since the dict class is crucial to the overall performance of Python, > the dict class behav

Re: Speed-up for loops

2010-09-03 Thread Hrvoje Niksic
Ulrich Eckhardt writes: > Tim Wintle wrote: >> [..] under the hood, cpython does something like this (in psudo-code) >> >> itterator = xrange(imax) >> while 1: >> next_attribute = itterator.next >> try: >> i = next_attribute() >> except: >> break >> a = a + 10 > > There is one th

Re: Speed-up for loops

2010-09-02 Thread Hrvoje Niksic
Michael Kreim writes: > Are there any ways to speed up the for/xrange loop? > Or do I have to live with the fact that Matlab beats Python in this > example? To a point, yes. However, there are things you can do to make your Python code go faster. One has been pointed out by Peter. Another is

Re: speed of numpy.power()?

2010-08-25 Thread Hrvoje Niksic
Carlos Grohmann writes: > I'd like to hear from you on the benefits of using numpy.power(x,y) > over (x*x*x*x..) > > I looks to me that numpy.power takes more time to run. You can use math.pow, which is no slower than repeated multiplication, even for small exponents. Obviously, after the expon

Re: Contains/equals

2010-08-24 Thread Hrvoje Niksic
Lawrence D'Oliveiro writes: > In message , Alex Hall > wrote: > >> def __eq__(self, obj): >> if self.a==obj.a and self.b==obj.b: return True >> return False > > Is there a “Useless Use Of ...” award category for these “if then > return True; else return False” constructs? Well, remember

Re: Using String Methods In Jump Tables

2010-08-23 Thread Hrvoje Niksic
Tim Daneliuk writes: >You can get away with this because all string objects appear to point to > common >method objects. That is,: id("a".lower) == id("b".lower) A side note: your use of `id' has misled you. id(X)==id(Y) is not a perfect substitue for the X is Y. :) "a".lower and "b

Re: Iterative vs. Recursive coding

2010-08-22 Thread Hrvoje Niksic
Steven D'Aprano writes: > * It throws away information from tracebacks if the recursive function > fails; and [...] > If you're like me, you're probably thinking that the traceback from an > exception in a recursive function isn't terribly useful. Agreed. On the other hand, a full-fledged tai

Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-07-30 Thread Hrvoje Niksic
Gregory Ewing writes: > I think the point is that the name is misleading, because it makes it > *sound* like it's going to call a method in a superclass, when it fact > it might not. That is indeed confusing to some people, especially those who refuse to to accept the notion that "superclass" me

Re: measuring a function time

2010-07-30 Thread Hrvoje Niksic
Steven D'Aprano writes: > On Thu, 29 Jul 2010 14:42:58 +0200, Matteo Landi wrote: > >> This should be enough >> >import time >tic = time.time() >function() >toc = time.time() >print toc - tic > > You're typing that in the interactive interpreter, which means the > timer is co

Re: Performance ordered dictionary vs normal dictionary

2010-07-29 Thread Hrvoje Niksic
sturlamolden writes: > On 29 Jul, 03:47, Navkirat Singh wrote: > >> I was wondering what would be better to do some medium to heavy book keeping >> in memory - Ordered Dictionary or a plain simple Dictionary object?? > > It depends on the problem. A dictionary is a hash table. An ordered > dict

Re: Cpp + Python: static data dynamic initialization in *nix shared lib?

2010-07-14 Thread Hrvoje Niksic
"Alf P. Steinbach /Usenet" writes: > Also, things like the 'owned' option is just asking for trouble. Isn't owned=true (or equivalent) a necessity when initializing from a PyObject* returned by a function declared to return a "new reference"? How does your API deal with the distinction between

Re: Why doesn't python's list append() method return the list itself?

2010-07-12 Thread Hrvoje Niksic
dhruvbird writes: > No, I meant x.append(4) > Except that I want to accomplish it using slices. > > (I can do it as x[lex(x):] = [item_to_append] but is there any other > way?) It seems that you've found a way to do so, so why do you need another way? Are you after elegance? Efficiency? Brevi

Re: efficiently create and fill array.array from C code?

2010-06-14 Thread Hrvoje Niksic
Thomas Jollans writes: > On 06/14/2010 01:18 PM, Hrvoje Niksic wrote: >> Thomas Jollans writes: >> >>> 1. allocate a buffer of a certain size >>> 2. fill it >>> 3. return it as an array. >> >> The fastest and more robust approach (I&#

Re: efficiently create and fill array.array from C code?

2010-06-14 Thread Hrvoje Niksic
Thomas Jollans writes: > 1. allocate a buffer of a certain size > 2. fill it > 3. return it as an array. The fastest and more robust approach (I'm aware of) is to use the array.array('typecode', [0]) * size idiom to efficiently preallocate the array, and then to get hold of the pointer pointing

Re: optparse: best way

2010-06-08 Thread Hrvoje Niksic
Thomas Jollans writes: > UNIX and GNU recommendations. I've never actually heard of optparser, > but I'd expect it to have the usual limitations: Hiral probably meant to write "optparse", which supports GNU-style options in a fairly standard and straightforward way. Which includes that defining

Re: Sublassing tuple works, subclassing list does not

2010-03-31 Thread Hrvoje Niksic
"Frank Millman" writes: class MyList(list): > ... def __new__(cls, names, values): > ... for name, value in zip(names, values): > ... setattr(cls, name, value) > ... return list.__new__(cls, values) Did you really mean to setattr the class here? If I'm guessing your intenti

Re: Python version of perl's "if (-T ..)" and "if (-B ...)"?

2010-02-17 Thread Hrvoje Niksic
Tim Chase writes: > if portion is None: > content = iter(f) iter(f) will iterate over lines in the file, which doesn't fit with the rest of the algorithm. Creating an iterator that iterates over fixed-size file chunks (in this case of length 1) is where the two-argument form of iter c

Re: UnboundLocalError: local variable '_[1]' referenced before assignment

2009-12-09 Thread Hrvoje Niksic
Richard Thomas writes: > That isn't an error that should occur, not least because _[1] isn't a > valid name. Can you post a full traceback? The name _[n] is used internally when compiling list comprehensions. The name is chosen precisely because it is not an (otherwise) valid identifier. For ex

Re: Create object from variable indirect reference?

2009-11-10 Thread Hrvoje Niksic
NickC writes: > moon2 = ephem.${!options.body}() moon2 = getattr(ephem, options.body)() -- http://mail.python.org/mailman/listinfo/python-list

Re: is None or == None ?

2009-11-08 Thread Hrvoje Niksic
"Alf P. Steinbach" writes: > * Hrvoje Niksic: >> "Alf P. Steinbach" writes: >> >>> Speedup would likely be more realistic with normal implementation (not >>> fiddling with bit-fields and stuff) >> >> I'm not sure I underst

Re: is None or == None ?

2009-11-07 Thread Hrvoje Niksic
"Alf P. Steinbach" writes: > Speedup would likely be more realistic with normal implementation (not > fiddling with bit-fields and stuff) I'm not sure I understand this. How would you implement tagged integers without encoding type information in bits of the pointer value? -- http://mail.pytho

Re: Q: sort's key and cmp parameters

2009-10-07 Thread Hrvoje Niksic
Bearophile writes: > What I meant is that a general sorting routine, even in D, is better > to be first of all flexible. So I think it's better for the D built-in > sort to be stable, because such extra invariant allows you to use the > sort in more situations. Note that stable sort has addition

Re: Are min() and max() thread-safe?

2009-09-17 Thread Hrvoje Niksic
Steven D'Aprano writes: >> min() and max() don't release the GIL, so yes, they are safe, and >> shouldn't see a list in an inconsistent state (with regard to the >> Python interpreter, but not necessarily to your application). But a >> threaded approach is somewhat silly, since the GIL ensures t

Re: Question on the "csv" library

2009-08-28 Thread Hrvoje Niksic
David Smith writes: >> 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" >> comes from my regional Spanish settings > > The C really does stand for comma. I've never seen MS spit out > semi-colon separated text on a CSV format. That's because you're running MS Office in a U

Re: proposal: add setresuid() system call to python

2009-08-25 Thread Hrvoje Niksic
travis+ml-pyt...@subspacefield.org writes: > On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: >> To emulate the os-module-type calls, it's better to raise exceptions >> than return negative values: >> >> > def setresuid(ruid, euid, suid): >

Re: Generate a new object each time a name is imported

2009-08-02 Thread Hrvoje Niksic
Steven D'Aprano writes: > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal.

Re: New implementation of re module

2009-07-30 Thread Hrvoje Niksic
MRAB writes: > So it complains about: > > ++(RE_CHAR*)context->text_ptr > > but not about: > > ++info->repeat.count > > Does this mean that the gcc compiler thinks that the cast makes it an > rvalue? The cast operator does return an rvalue, treating it otherwise used to be an extension t

Re: FTP Offset larger than file.

2009-07-28 Thread Hrvoje Niksic
Bakes writes: >> > As a quick fix, you can add a file.flush() line after the >> > file.write(...) line, and the problem should go away. >> >> Thank you very much, that worked perfectly. > > Actually, no it didn't. That fix works seamlessly in Linux, but gave > the same error in a Windows environm

Re: FTP Offset larger than file.

2009-07-28 Thread Hrvoje Niksic
Bakes writes: > The error I get is: > ftplib.error_temp: 451-Restart offset 24576 is too large for file size > 22852. > 451 Restart offset reset to 0 > which tells me that the local file is larger than the external file, > by about a kilobyte. Certainly, the local file is indeed that size, so > m

Re: The longest word

2009-07-28 Thread Hrvoje Niksic
Piet van Oostrum writes: >> NiklasRTZ (N) wrote: > >>N> Thank you. This seems to work: >>N> sorted("a AAA aa a sdfsdfsdfsdf vv".split(' '),lambda a,b: len(a)- >>N> len(b))[-1] >>N> 'sdfsdfsdfsdf' > > simpler: > > sorted("a AAA aa a sdfsdfsdfsdf vv".split(' '), key=len)[-1] There i

Re: non-owning references?

2009-07-24 Thread Hrvoje Niksic
Ben Finney writes: > Utpal Sarkar writes: > >> Is there a way I can tell a variable that the object it is pointing >> too is not owned by it, in the sense that if it is the only reference >> to the object it can be garbage collected? > > Python doesn't have “pointers”, and doesn't really have “v

Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Chris Rebert writes: >>> x = [2,1,3] >>> print sorted(x)[0] >>>DB> 3 >> >> What kind of Python produces that? > > Assuming you're referring to the latter example, it was added in version 2.4 > If you meant the former example, I think that's purely pseudo-Python. sorted([2, 1, 3])[0] eval

Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Phillip B Oldham writes: > On Jul 20, 6:08 pm, Duncan Booth wrote: >> The main reason why you need both lists and tuples is that because a tuple >> of immutable objects is itself immutable you can use it as a dictionary >> key. > > Really? That sounds interesting, although I can't think of any r

Re: proposal: add setresuid() system call to python

2009-07-20 Thread Hrvoje Niksic
"Diez B. Roggisch" writes: To emulate the os-module-type calls, it's better to raise exceptions than return negative values: > def setresuid(ruid, euid, suid): > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) def setresuid(ruid, euid, suid): res = _setresuid(__uid_t(ruid

Re: missing 'xor' Boolean operator

2009-07-15 Thread Hrvoje Niksic
Jean-Michel Pichavant writes: > Hrvoje Niksic wrote: > [snip] >> Note that in Python A or B is in fact not equivalent to not(not A and >> not B). >> >>>> l = [(True, True), (True, False), (False, True), (False, False)] >>>> for p in l: > ..

  1   2   3   4   5   >