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

2012-03-10 Thread Hrvoje Niksic
Stefan Behnel stefan...@behnel.de 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

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

2012-03-07 Thread Hrvoje Niksic
Alec Taylor alec.tayl...@gmail.com 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,

Re: round down to nearest number

2012-02-11 Thread Hrvoje Niksic
Terry Reedy tjre...@udel.edu 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

Re: copy on write

2012-02-02 Thread Hrvoje Niksic
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 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

Re: while True or while 1

2012-01-23 Thread Hrvoje Niksic
Dave Angel d...@davea.name 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 ndbeck...@gmail.com 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.

Re: order independent hash?

2011-12-09 Thread Hrvoje Niksic
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 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

Re: order independent hash?

2011-12-08 Thread Hrvoje Niksic
Tim Chase python.l...@tim.thechases.com 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

Re: order independent hash?

2011-12-07 Thread Hrvoje Niksic
Chris Angelico ros...@gmail.com writes: 2011/12/5 Hrvoje Niksic hnik...@xemacs.org: 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 tree of hash

Re: order independent hash?

2011-12-04 Thread Hrvoje Niksic
Terry Reedy tjre...@udel.edu 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

Re: order independent hash?

2011-12-02 Thread Hrvoje Niksic
Chris Angelico ros...@gmail.com 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

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

2011-12-01 Thread Hrvoje Niksic
Chris Rebert c...@rebertia.com 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

Re: Server Questions (2 of them)

2011-11-20 Thread Hrvoje Niksic
Andrew andrew.chapkow...@gmail.com 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

Re: Dictionary sorting

2011-11-04 Thread Hrvoje Niksic
Ben Finney ben+pyt...@benfinney.id.au writes: Tim Chase python.l...@tim.thechases.com 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

Re: __dict__ attribute for built-in types

2011-10-28 Thread Hrvoje Niksic
candide candide@free.invalid 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 like this : foo.bar

Re: __dict__ attribute for built-in types

2011-10-27 Thread Hrvoje Niksic
candide candide@free.invalid 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

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

2011-07-31 Thread Hrvoje Niksic
Neil Cerutti ne...@norwich.edu writes: On 2011-07-29, Dennis Lee Bieber wlfr...@ix.netcom.com 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

Re: Convert '165.0' to int

2011-07-22 Thread Hrvoje Niksic
Frank Millman fr...@chagford.com 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. --

Re: Possible File iteration bug

2011-07-14 Thread Hrvoje Niksic
Billy Mays no...@nohow.com 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 =

Re: How does CO_FUTURE_DIVISION compiler flag get propagated?

2011-07-02 Thread Hrvoje Niksic
Terry twest...@gmail.com 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

Re: Python and Lisp : car and cdr

2011-06-19 Thread Hrvoje Niksic
Ethan Furman et...@stoneleaf.us 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))

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

2011-05-03 Thread Hrvoje Niksic
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 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,

Re: generator / iterator mystery

2011-03-13 Thread Hrvoje Niksic
Dave Abrahams d...@boostpro.com 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

Re: Use-cases for alternative iterator

2011-03-10 Thread Hrvoje Niksic
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 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

Re: Parameterized functions of no arguments?

2011-02-11 Thread Hrvoje Niksic
Chris Rebert c...@rebertia.com 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

Re: Perl Hacker, Python Initiate

2011-02-03 Thread Hrvoje Niksic
Gary Chambers gwch...@gwcmail.com 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

Re: Resolve circular reference

2011-01-14 Thread Hrvoje Niksic
Magnus Lyckå ly...@carmen.se 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 the cycle, but it only stores

Re: list 2 dict?

2011-01-02 Thread Hrvoje Niksic
Octavian Rasnita orasn...@gmail.com 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]))

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

2010-12-29 Thread Hrvoje Niksic
Christian Heimes li...@cheimes.de 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. --

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

2010-12-28 Thread Hrvoje Niksic
Christian Heimes li...@cheimes.de 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

Re: round in 2.6 and 2.7

2010-12-24 Thread Hrvoje Niksic
Martin v. Loewis mar...@v.loewis.de 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 the repr retains the

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 going out of its way

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

Re: Exception handling in Python 3.x

2010-12-03 Thread Hrvoje Niksic
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 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)

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

Re: Collect output to string

2010-11-24 Thread Hrvoje Niksic
Burton Samograd bur...@userful.com writes: Terry Reedy tjre...@udel.edu 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

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

2010-11-20 Thread Hrvoje Niksic
Mark Dickinson dicki...@gmail.com writes: On Nov 19, 3:29 pm, RJB rbott...@csusb.edu 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.

Re: with HTTPConnection as conn:

2010-11-18 Thread Hrvoje Niksic
Antoine Pitrou solip...@pitrou.net writes: On Thu, 18 Nov 2010 12:46:07 +0100 trylks try...@gmail.com 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

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 the

Re: Some syntactic sugar proposals

2010-11-15 Thread Hrvoje Niksic
Dmitry Groshev lambdadmi...@gmail.com 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

Re: Is Eval *always* Evil?

2010-11-10 Thread Hrvoje Niksic
Simon Mullis si...@mullis.co.uk 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: Is Eval *always* Evil?

2010-11-10 Thread Hrvoje Niksic
Robert Kern robert.k...@gmail.com writes: On 2010-11-10 15:52 , Hrvoje Niksic wrote: Simon Mullissi...@mullis.co.uk 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. No, that doesn't work since he

Re: Silly newbie question - Carrot character (^)

2010-11-06 Thread Hrvoje Niksic
Seebs usenet-nos...@seebs.net 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

Re: Silly newbie question - Carrot character (^)

2010-11-06 Thread Hrvoje Niksic
Seebs usenet-nos...@seebs.net writes: On 2010-11-06, Hrvoje Niksic hnik...@xemacs.org 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: functions, list, default parameters

2010-11-03 Thread Hrvoje Niksic
Paul Rudin paul.nos...@rudin.co.uk writes: Terry Reedy tjre...@udel.edu 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

Re: Man pages and info pages

2010-11-03 Thread Hrvoje Niksic
Teemu Likonen tliko...@iki.fi 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

Re: factorial of negative one (-1)

2010-11-02 Thread Hrvoje Niksic
Ken Watford kwatford+pyt...@gmail.com 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

Re: factorial of negative one (-1)

2010-11-01 Thread Hrvoje Niksic
Chris Rebert c...@rebertia.com 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

Re: Multilingual documentation solutions

2010-10-27 Thread Hrvoje Niksic
Astley Le Jasper astley.lejas...@gmail.com 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

Re: downcasting problem

2010-10-26 Thread Hrvoje Niksic
John Nagle na...@animats.com 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

Re: Has Next in Python Iterators

2010-10-25 Thread Hrvoje Niksic
Kelson Zawack zawack...@gis.a-star.edu.sg 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

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

Re: how to scrutch a dict()

2010-10-21 Thread Hrvoje Niksic
Joost Molenaar j.j.molen...@gmail.com 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,

Re: overriding a property

2010-10-20 Thread Hrvoje Niksic
Lucasm lordlucr...@gmail.com 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

Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith j...@jedsmith.org writes: On Tue, Oct 19, 2010 at 1:37 PM, kj no.em...@please.post 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.

Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith j...@jedsmith.org 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

Re: Unicode questions

2010-10-19 Thread Hrvoje Niksic
Tobiah t...@rcsreg.com 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

Re: harmful str(bytes)

2010-10-12 Thread Hrvoje Niksic
Stefan Behnel stefan...@behnel.de 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

Re: How is correct use of eval()

2010-10-12 Thread Hrvoje Niksic
Nobody nob...@nowhere.com 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

Re: hashkey/digest for a complex object

2010-10-10 Thread Hrvoje Niksic
Steven D'Aprano st...@remove-this-cybersource.com.au 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

Re: hashkey/digest for a complex object

2010-10-10 Thread Hrvoje Niksic
Arnaud Delobelle arno...@gmail.com 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().

Re: if the else short form

2010-10-10 Thread Hrvoje Niksic
Antoon Pardon antoon.par...@rece.vub.ac.be 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

Re: Many newbie questions regarding python

2010-10-09 Thread Hrvoje Niksic
alex23 wuwe...@gmail.com 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.

Re: if the else short form

2010-09-29 Thread Hrvoje Niksic
Tracubik affdfsdfds...@b.com 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

Re: About __class__ of an int literal

2010-09-29 Thread Hrvoje Niksic
Steven D'Aprano st...@remove-this-cybersource.com.au 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

Re: Overriding dict constructor

2010-09-20 Thread Hrvoje Niksic
Christian Heimes li...@cheimes.de 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

Re: Speed-up for loops

2010-09-03 Thread Hrvoje Niksic
Ulrich Eckhardt eckha...@satorlaser.com 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

Re: Speed-up for loops

2010-09-02 Thread Hrvoje Niksic
Michael Kreim mich...@perfect-kreim.de 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

Re: speed of numpy.power()?

2010-08-25 Thread Hrvoje Niksic
Carlos Grohmann carlos.grohm...@gmail.com 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.

Re: Contains/equals

2010-08-24 Thread Hrvoje Niksic
Lawrence D'Oliveiro l...@geek-central.gen.new_zealand writes: In message mailman.2311.1282230005.1673.python-l...@python.org, 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

Re: Using String Methods In Jump Tables

2010-08-23 Thread Hrvoje Niksic
Tim Daneliuk tun...@tundraware.com 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. :)

Re: Iterative vs. Recursive coding

2010-08-22 Thread Hrvoje Niksic
Steven D'Aprano st...@remove-this-cybersource.com.au 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

Re: measuring a function time

2010-07-30 Thread Hrvoje Niksic
Steven D'Aprano st...@remove-this-cybersource.com.au 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

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 greg.ew...@canterbury.ac.nz 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

Re: Performance ordered dictionary vs normal dictionary

2010-07-29 Thread Hrvoje Niksic
sturlamolden sturlamol...@yahoo.no writes: On 29 Jul, 03:47, Navkirat Singh navkir...@gmail.com 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

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

2010-07-14 Thread Hrvoje Niksic
Alf P. Steinbach /Usenet alf.p.steinbach+use...@gmail.com 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

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

2010-07-12 Thread Hrvoje Niksic
dhruvbird dhruvb...@gmail.com 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?

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

2010-06-14 Thread Hrvoje Niksic
Thomas Jollans tho...@jollans.com 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

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

2010-06-14 Thread Hrvoje Niksic
Thomas Jollans tho...@jollans.com writes: On 06/14/2010 01:18 PM, Hrvoje Niksic wrote: Thomas Jollans tho...@jollans.com 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

Re: optparse: best way

2010-06-08 Thread Hrvoje Niksic
Thomas Jollans tho...@jollans.com 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

Re: Sublassing tuple works, subclassing list does not

2010-03-31 Thread Hrvoje Niksic
Frank Millman fr...@chagford.com 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

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

2010-02-17 Thread Hrvoje Niksic
Tim Chase python.l...@tim.thechases.com 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

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

2009-12-09 Thread Hrvoje Niksic
Richard Thomas chards...@gmail.com 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

Re: Create object from variable indirect reference?

2009-11-10 Thread Hrvoje Niksic
NickC reply...@works.fine.invalid 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 al...@start.no writes: * Hrvoje Niksic: Alf P. Steinbach al...@start.no 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

Re: is None or == None ?

2009-11-07 Thread Hrvoje Niksic
Alf P. Steinbach al...@start.no 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? --

Re: Q: sort's key and cmp parameters

2009-10-07 Thread Hrvoje Niksic
Bearophile bearophileh...@lycos.com 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

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

2009-09-17 Thread Hrvoje Niksic
Steven D'Aprano ste...@remove.this.cybersource.com.au 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

Re: Question on the csv library

2009-08-28 Thread Hrvoje Niksic
David Smith d...@cornell.edu 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

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): return _setresuid(__uid_t(ruid), __uid_t(euid

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

2009-08-02 Thread Hrvoje Niksic
Steven D'Aprano st...@remove-this-cybersource.com.au 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

Re: The longest word

2009-07-28 Thread Hrvoje Niksic
Piet van Oostrum p...@cs.uu.nl writes: NiklasRTZ nikla...@gmail.com (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]

Re: FTP Offset larger than file.

2009-07-28 Thread Hrvoje Niksic
Bakes ba...@ymail.com 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

Re: FTP Offset larger than file.

2009-07-28 Thread Hrvoje Niksic
Bakes ba...@ymail.com 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

Re: non-owning references?

2009-07-24 Thread Hrvoje Niksic
Ben Finney ben+pyt...@benfinney.id.au writes: Utpal Sarkar doe...@gmail.com 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

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

2009-07-20 Thread Hrvoje Niksic
Diez B. Roggisch de...@nospam.web.de 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 =

Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Phillip B Oldham phillip.old...@gmail.com writes: On Jul 20, 6:08 pm, Duncan Booth duncan.bo...@invalid.invalid 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

Re: Help understanding the decisions *behind* python?

2009-07-20 Thread Hrvoje Niksic
Chris Rebert c...@rebertia.com 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] evaluates

Re: missing 'xor' Boolean operator

2009-07-15 Thread Hrvoje Niksic
Jean-Michel Pichavant jeanmic...@sequans.com writes: While everyone's trying to tell the OP how to workaround the missing xor operator, nobody answered the question why is there no [boolean] xor operator ?. Probably because there isn't one in C. The bitwise XOR operator, on the other hand,

Re: missing 'xor' Boolean operator

2009-07-15 Thread Hrvoje Niksic
Jean-Michel Pichavant jeanmic...@sequans.com 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: ... p[0] or p[1] [...] Try with a different

  1   2   3   4   5   >