detect interactivity
Dear all, Is it possible for a Python script to detect whether it is running interactively? It can be useful for e.g. defining functions that are only useful in interactive mode. Kind regards, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: detect interactivity
On Dec 29, 2009, at 8:34 PM, Dave Angel wrote: Antoine Pitrou wrote: Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit : Dear all, Is it possible for a Python script to detect whether it is running interactively? It can be useful for e.g. defining functions that are only useful in interactive mode. Try the isatty() method (*) on e.g. stdin: $ python -c "import sys; print sys.stdin.isatty()" True $ echo "" | python -c "import sys; print sys.stdin.isatty()" False Your test determines whether input is redirected. But I think the OP was asking how to detect whether the script was being run from an interpreter prompt. That was my question indeed. Is it possible? -- http://mail.python.org/mailman/listinfo/python-list
Re: detect interactivity
On Dec 30, 2009, at 1:52 AM, Steven D'Aprano wrote: On Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries wrote: Dear all, Is it possible for a Python script to detect whether it is running interactively? It can be useful for e.g. defining functions that are only useful in interactive mode. Ah, I should have looked more carefully at the docs... http://docs.python.org/library/sys.html#sys.ps1 sys.ps1 and sys.ps2 are documented as only existing if you are running interactively. This doesn't really work. In ipython, sys.ps1 is not defined. But also if I run 'python <<< "import sys; print(sys.ps1)"', I get an error. -- http://mail.python.org/mailman/listinfo/python-list
Re: detect interactivity
On Dec 30, 2009, at 2:28 AM, Dave Angel wrote: Roald de Vries wrote: On Dec 29, 2009, at 8:34 PM, Dave Angel wrote: Antoine Pitrou wrote: Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit : Dear all, Is it possible for a Python script to detect whether it is running interactively? It can be useful for e.g. defining functions that are only useful in interactive mode. Try the isatty() method (*) on e.g. stdin: $ python -c "import sys; print sys.stdin.isatty()" True $ echo "" | python -c "import sys; print sys.stdin.isatty()" False Your test determines whether input is redirected. But I think the OP was asking how to detect whether the script was being run from an interpreter prompt. That was my question indeed. Is it possible? If I had had a good answer, I would have supplied it in my earlier message. The sneaky answer would be that a script cannot be used interactively, as once you import it from the interpreter, it's a module, not a script. So you can detect that it's not a script, by examing __name__ in the usual way. If it's a script, it'll have a value of "__main__". But that won't tell you if you're running inside an IDE, or using the -i switch on the Python command line, or probably a bunch of other questions. I don't know of any "correct" answer, and I'm not sure what the real use case is for knowing. Are you really going to somehow define a different set of functions??? I'm using a database, and want to use python interactively to manipulate it. On the other hand, I also want to be able to use it non- interactively. In that case, it would be a waste of CPU to load the function/class definitions meant for interactive use. -- http://mail.python.org/mailman/listinfo/python-list
Re: detect interactivity
On Dec 30, 2009, at 4:10 AM, Steve Holden wrote: Roald de Vries wrote: On Dec 30, 2009, at 2:28 AM, Dave Angel wrote: Roald de Vries wrote: On Dec 29, 2009, at 8:34 PM, Dave Angel wrote: Antoine Pitrou wrote: Le Tue, 29 Dec 2009 16:09:58 +0100, Roald de Vries a écrit : Dear all, Is it possible for a Python script to detect whether it is running interactively? It can be useful for e.g. defining functions that are only useful in interactive mode. Try the isatty() method (*) on e.g. stdin: $ python -c "import sys; print sys.stdin.isatty()" True $ echo "" | python -c "import sys; print sys.stdin.isatty()" False Your test determines whether input is redirected. But I think the OP was asking how to detect whether the script was being run from an interpreter prompt. That was my question indeed. Is it possible? If I had had a good answer, I would have supplied it in my earlier message. The sneaky answer would be that a script cannot be used interactively, as once you import it from the interpreter, it's a module, not a script. So you can detect that it's not a script, by examing __name__ in the usual way. If it's a script, it'll have a value of "__main__". But that won't tell you if you're running inside an IDE, or using the -i switch on the Python command line, or probably a bunch of other questions. I don't know of any "correct" answer, and I'm not sure what the real use case is for knowing. Are you really going to somehow define a different set of functions??? I'm using a database, and want to use python interactively to manipulate it. On the other hand, I also want to be able to use it non-interactively. In that case, it would be a waste of CPU to load the function/class definitions meant for interactive use. This is an extreme case of premature optimization. Write the code and run it. Do you have any idea how much extra time and memory loading the additional code will require? If not, it's a waste of your time to even think about omitting the stuff required for interactive use. Once you get a handle on the structures and functions required for interactive vs. non-interactive use you can consider refactoring the code so that the non-interactive programs don't need to import the stuff that's exclusively for interactive use. But frankly I wouldn't waste your time. Actually, performance is not much if an issue for what I want to do; it's mainly interest in 'how should I do this in general'. I'll just leave in all the code, and if it becomes a real issue, I'll separate the code over an interactive and a non-interactive script. Thanks for your inputs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Symbols as parameters?
Hi Martin, On Jan 21, 2010, at 8:43 AM, Martin Drautzburg wrote: Hello all, When passing parameters to a function, you sometimes need a paramter which can only assume certain values, e.g. def move (direction): ... If direction can only be "up", "down", "left" or "right", you can solve this by passing strings, but this is not quite to the point: - you could pass invalid strings easily - you need to quote thigs, which is a nuisance - the parameter IS REALLY NOT A STRING, but a direction Alternatively you could export such symbols, so when you "import *" you have them available in the caller's namespace. But that forces you to "import *" which pollutes your namespace. What I am really looking for is a way - to be able to call move(up) - having the "up" symbol only in the context of the function call So it should look something like this ... magic, magic ... move(up) ... unmagic, unmagic ... print up This should complain that "up" is not defined during the "print" call, but not when move() is called. And of course there should be as little magic as possible. Any way to achieve this? You could do something like this: class Move(object): def __call__(self, direction): print(direction) return 0 def up(self): return self('up') move = Move() Now move.up() means move('up'), and you can obviously do similar things for other directions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Symbols as parameters?
On Jan 22, 2010, at 1:06 PM, Martin Drautzburg wrote: On 22 Jan., 11:56, Roald de Vries wrote: Hi Martin, On Jan 21, 2010, at 8:43 AM, Martin Drautzburg wrote: Hello all, When passing parameters to a function, you sometimes need a paramter which can only assume certain values, e.g. def move (direction): ... If direction can only be "up", "down", "left" or "right", you can solve this by passing strings, but this is not quite to the point: - you could pass invalid strings easily - you need to quote thigs, which is a nuisance - the parameter IS REALLY NOT A STRING, but a direction Alternatively you could export such symbols, so when you "import *" you have them available in the caller's namespace. But that forces you to "import *" which pollutes your namespace. What I am really looking for is a way - to be able to call move(up) - having the "up" symbol only in the context of the function call So it should look something like this ... magic, magic ... move(up) ... unmagic, unmagic ... print up This should complain that "up" is not defined during the "print" call, but not when move() is called. And of course there should be as little magic as possible. Any way to achieve this? You could do something like this: class Move(object): def __call__(self, direction): print(direction) return 0 def up(self): return self('up') move = Move() Now move.up() means move('up'), and you can obviously do similar things for other directions.- Zitierten Text ausblenden - - Zitierten Text anzeigen - I had thought about that too. It gets a bit tricky when there is more than one parameter and it completely fails whan a parameter can REALLY be a number or an arbitrary string. Think: move(direction, distance) For extra parameters: class Move(object): def __call__(self, direction, param1, param2, *params, **dict): print(direction) return 0 def up(self, *params, **dict): return self('up', *params, **dict) move = Move() On Jan 22, 2010, at 1:06 PM, Martin Drautzburg wrote: On 22 Jan., 11:56, Roald de Vries wrote: Hi Martin, On Jan 21, 2010, at 8:43 AM, Martin Drautzburg wrote: Hello all, When passing parameters to a function, you sometimes need a paramter which can only assume certain values, e.g. def move (direction): ... If direction can only be "up", "down", "left" or "right", you can solve this by passing strings, but this is not quite to the point: - you could pass invalid strings easily - you need to quote thigs, which is a nuisance - the parameter IS REALLY NOT A STRING, but a direction Alternatively you could export such symbols, so when you "import *" you have them available in the caller's namespace. But that forces you to "import *" which pollutes your namespace. What I am really looking for is a way - to be able to call move(up) - having the "up" symbol only in the context of the function call So it should look something like this ... magic, magic ... move(up) ... unmagic, unmagic ... print up This should complain that "up" is not defined during the "print" call, but not when move() is called. And of course there should be as little magic as possible. Any way to achieve this? You could do something like this: class Move(object): def __call__(self, direction): print(direction) return 0 def up(self): return self('up') move = Move() Now move.up() means move('up'), and you can obviously do similar things for other directions.- Zitierten Text ausblenden - - Zitierten Text anzeigen - I had thought about that too. It gets a bit tricky when there is more than one parameter For extra parameters: class Move(object): def __call__(self, direction, param1, param2, *params, **dict): print(direction) return 0 def up(self, *params, **dict): return self('up', *params, **dict) move = Move() and it completely fails whan a parameter can REALLY be a number or an arbitrary string. Think: move(direction, distance) For a number, move.up(10) wouldn't be too bad. For an arbitrary string, you always have __getattr__ and __getattribute__. But if you like this style of coding, you should probably switch to Ruby. -- http://mail.python.org/mailman/listinfo/python-list
enumerated while loop
Dear all, I sometimes want to use an infinite while loop with access to the loop index, like this: def naturals(): i = 0 while True: yield i y += 1 for i in naturals(): print(i) I assume a function like 'naturals' already exists, or a similar construction for the same purpose. But what is it called? Kind regards, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: enumerated while loop
On Jan 23, 2010, at 3:50 PM, Grant Edwards wrote: On 2010-01-23, Roald de Vries wrote: Dear all, I sometimes want to use an infinite while loop with access to the loop index, like this: def naturals(): i = 0 while True: yield i y += 1 for i in naturals(): print(i) I assume a function like 'naturals' already exists, or a similar construction for the same purpose. But what is it called? xrange(), except that you need to provde an upper limit. I'm sorry, Grant, but you exactly miss my point ;-). The essence of this is that it's endless. -- http://mail.python.org/mailman/listinfo/python-list
Re: enumerated while loop
On Jan 23, 2010, at 3:49 PM, Diez B. Roggisch wrote: Am 23.01.10 15:44, schrieb Roald de Vries: Dear all, I sometimes want to use an infinite while loop with access to the loop index, like this: def naturals(): i = 0 while True: yield i y += 1 for i in naturals(): print(i) I assume a function like 'naturals' already exists, or a similar construction for the same purpose. But what is it called? for i, item in enumerate(iterable): This only moves the problem to the variable 'iterable'. And moreover is more complex than needed; it give '(i, item)', whereas I only need the index 'i'. -- http://mail.python.org/mailman/listinfo/python-list
Re: enumerated while loop
On Jan 23, 2010, at 3:58 PM, Mark Dickinson wrote: On Jan 23, 2:44 pm, Roald de Vries wrote: I assume a function like 'naturals' already exists, or a similar construction for the same purpose. But what is it called? itertools.count() On Jan 23, 2010, at 4:04 PM, Jan Kaliszewski wrote: itertools.count() -- see http://docs.python.org/library/itertools.html#itertools.count for i, item in enumerate(iterable): That's completely beside the point. Thanks guys -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Ruby
On Jan 27, 2010, at 2:01 PM, Jean Guillaume Pyraksos wrote: What are the arguments for choosing Python against Ruby for introductory programming ? Python has no provisions for tail recursion, Ruby is going to... So what ? Thanks, I think the main difference is in culture, especially for *introductory* programming. For example, I have the impression that Rubyists like to write the same thing in as many ways as possible (example: rubyquiz.com), Python prefers one obvious way; this (arguably) makes Ruby more writable and Python more readable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Symbols as parameters?
On Jan 22, 2010, at 11:56 AM, Roald de Vries wrote: Hi Martin, On Jan 21, 2010, at 8:43 AM, Martin Drautzburg wrote: Hello all, When passing parameters to a function, you sometimes need a paramter which can only assume certain values, e.g. def move (direction): ... If direction can only be "up", "down", "left" or "right", you can solve this by passing strings, but this is not quite to the point: - you could pass invalid strings easily - you need to quote thigs, which is a nuisance - the parameter IS REALLY NOT A STRING, but a direction Alternatively you could export such symbols, so when you "import *" you have them available in the caller's namespace. But that forces you to "import *" which pollutes your namespace. What I am really looking for is a way - to be able to call move(up) - having the "up" symbol only in the context of the function call So it should look something like this ... magic, magic ... move(up) ... unmagic, unmagic ... print up This should complain that "up" is not defined during the "print" call, but not when move() is called. And of course there should be as little magic as possible. Any way to achieve this? You could do something like this: class Move(object): def __call__(self, direction): print(direction) return 0 def up(self): return self('up') move = Move() Now move.up() means move('up'), and you can obviously do similar things for other directions. Question out of general interest in the language: If I would want to generate such functions in a for-loop, what would I have to do? This doesn't work: class Move(object): def __call__(self, direction): return direction move = Move() for f in ['up', 'down', 'right', 'left']: move.__dict__[f] = lambda: move(f) ... because now 'move.up()' returns 'left' because thats the current value of f. Is there a way to 'expand' f in the loop? Or a reason that you never should use this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Symbols as parameters?
On Jan 29, 2010, at 2:30 AM, Steven D'Aprano wrote: On Thu, 28 Jan 2010 17:01:38 +0100, Roald de Vries wrote: Question out of general interest in the language: If I would want to generate such functions in a for-loop, what would I have to do? This doesn't work: class Move(object): def __call__(self, direction): return direction move = Move() for f in ['up', 'down', 'right', 'left']: move.__dict__[f] = lambda: move(f) ... because now 'move.up()' returns 'left' because thats the current value of f. Is there a way to 'expand' f in the loop? Or a reason that you never should use this? Possibly the simplest way is to use Python's handling of default values to get the result you want: for f in ['up', 'down', 'right', 'left']: move.__dict__[f] = lambda f=f: move(f) This still leaves open the possibility of move.up('down') resulting in move('down'), but for the rest I like it. BTW, there's no need to explicitly reference move.__dict__: for f in ['up', 'down', 'right', 'left']: setattr(move, f, lambda f=f: move(f)) I expected something like that. Thanks. Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Your beloved python features
On Feb 5, 2010, at 12:03 AM, Julian wrote: Hello, I've asked this question at stackoverflow a few weeks ago, and to make it clear: this should NOT be a copy of the stackoverflow-thread "hidden features of Python". I want to design a poster for an open source conference, the local usergroup will have a table there, and in the past years there were some people that came to the python-table just to ask "why should I use python?". For those guys would be a poster quite cool which describes the most popular and beloved python features. So, may you help me please? If there's a similar thread/blogpost/ whatever, please give it to me, google couldn't. My reasoning: I needed a language more powerful than bash, but more portable and faster to develop (at least small scripts) than C/C++. So I needed a scripting language. Python, Ruby, Perl, Tcl, ...? Python seems to be the language with the most libraries available, programs written in it, OS-support (even runs on my smartphone), has a good data-model, has a good interactive shell (iPython). -- http://mail.python.org/mailman/listinfo/python-list
Re: Constraints on __sub__, __eq__, etc.
On Feb 18, 2010, at 5:28 PM, Stephen Hansen wrote: On Thu, Feb 18, 2010 at 8:19 AM, Andrey Fedorov wrote: It seems intuitive to me that the magic methods for overriding the +, -, <, ==, >, etc. operators should have no sideffects on their operands. Also, that == should be commutative and transitive, that > and < should be transitive, and anti-commutative. Is this intuition written up in a PEP, or assumed to follow from the mathematical meanings? It may be intuitive to you, but its not true, written down anywhere, nor assumed by the language, and the mathematical meaning of the operators doesn't matter to Python. Python purposefully does not enforce anything for these methods. Still, it's clear that (for example) '==' is not just a normal function call. Look at this example (in ipython): >>> False == False == False True >>> True == False == False False >>> (True == False) == False True Anybody knows how why this is so? -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting talk on Python vs. Ruby and how he would like Python to have just a bit more syntactic flexibility.
This pipeline idea has actually been implemented further, see . from stream import map, filter, cut range(10) >> map(lambda x: [x**2, x**3]) >> filter(lambda t: t[0]! =25 and t[1]!=64) >> cut[1] >> list [0, 1, 8, 27, 216, 343, 512, 729] Wow, cool! Just to show that you can easily add the iterator.map(f).blabla-syntax to Python: from __future__ import print_function class rubified(list): map= lambda self, f: rubified(map(f, self)) filter = lambda self, f: rubified(filter(f, self)) reject = lambda self, f: rubified(filter(lambda x: not f(x), self)) # each = lambda self, f: rubified(reduce(lambda x, y: print(y), self, None)) def each(self, f): for x in self: f(x) def __new__(cls, value): return list.__new__(cls, value) def print_numbers(): rubified([1, 2, 3, 4, 5, 6]).map(lambda n: [n * n, n * n * n]).reject(lambda (square, cube): square == 25 or cube == 64).map(lambda (square, cube): cube).each(lambda n: print(n)) -- http://mail.python.org/mailman/listinfo/python-list
Re: When will Python go mainstream like Java?
On Feb 22, 2010, at 10:56 PM, AON LAZIO wrote: That will be superb I guess static typing will have to be added, so that tools like eclipse can inspect (and autocomplete) your programs [better]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Renaming identifiers & debugging
Hi Luca, On Feb 26, 2010, at 12:41 AM, Luca wrote: MRAB wrote: Perhaps you could use a different extension, eg ".pyn", so existing ".py" files are handled as-is but ".pyn" files are read through a translator. This could be a good idea... especially since i could make my own extension since we are talking of a special-purpose application that only incorporates python as a library. I would suggest to do choose the same strategy as 'from __future__ import ...' takes, which does similar things and limits them to the module it is used in. I would be curious to hear about your results. Kind regards, Roald -- http://mail.python.org/mailman/listinfo/python-list
Interfaces
Dear all, PEP 245 and 246 about interfaces for python are both rejected for 'something much better' (GvR in 246's rejection notice). Does anybody know what this is? I am *very* curious! Kind regards, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary
On Apr 26, 2010, at 8:04 PM, gopi krishna wrote: When I give a dictionary with key and value in order how can get back iy in same order I use YAML a lot, which supports ordered dicts, and these are interpreted as lists of pairs by Python, so that might be a good choice. -- http://mail.python.org/mailman/listinfo/python-list
Re: map is useless!
On Jun 6, 2010, at 5:16 PM, rantingrick wrote: Everyone knows i'm a Python fanboy so nobody can call me a troll for this... Python map is just completely useless. For one it so damn slow why even bother putting it in the language? And secondly, the total "girl- man" weakness of lambda renders it completely mute! Ruby has a very nice map [1,2,3].map{|x| x.to_s} Have not done any benchmarking but far more useful from the programmers POV. And that really stinks because map is such a useful tool it's a shame to waste it. Here are some test to back up the rant. import time def test1(): l = range(1) t1 = time.time() map(lambda x:x+1, l) t2= time.time() print t2-t1 def test2(): l = range(1) t1 = time.time() for x in l: x + 1 t2 = time.time() print t2-t1 test1() 0.0029346008 test2() 0.00027520752 def test3(): l = range(1) t1 = time.time() map(str, l) t2= time.time() print t2-t1 def test4(): l = range(1) t1 = time.time() for x in l: str(x) t2= time.time() print t2-t1 test3() 0.0032098083 test4() 0.0034850159 So can anyone explain this poor excuse for a map function? Maybe GVR should have taken it out in 3.0? *scratches head* Use list comprehension. It's nicer than Ruby's map: [x.to_s for x in 1, 2, 3] -- http://mail.python.org/mailman/listinfo/python-list
floatref
Hi all, I have two objects that should both be able to alter a shared float. So i need something like a mutable float object, or a float reference object. Does anybody know if something like that exists? I know it's not hard to build, but I have a feeling that there should be a standard solution to it. Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: floatref
On Jul 14, 2010, at 1:26 AM, Gary Herron wrote: On 07/13/2010 03:02 PM, Roald de Vries wrote: Hi Gary, On Jul 13, 2010, at 8:54 PM, Gary Herron wrote: On 07/13/2010 10:26 AM, Roald de Vries wrote: Hi all, I have two objects that should both be able to alter a shared float. So i need something like a mutable float object, or a float reference object. Does anybody know if something like that exists? I know it's not hard to build, but I have a feeling that there should be a standard solution to it. Roald Huh? I must be missing something here. Isn't this what you use a variable for: Maybe I didn't explain well: >>> shared_var = 1.0 >>> x.var = shared_var >>> y.var = shared_var >>> x.var = 2.0 >>> y.var 1.0 I wanted y.var and x.var to point to the same value, so that always x.var == y.var. So that the last line becomes: >>> y.var 2.0 Cheers, Roald Please keep responses and further discussions on list.python-l...@python.org instead of using private emails. Sorry. Python does not have pointers, so if I take your wording"y.var and x.var to point to the same value" literally, then the answer is NO Python does not do that. Maybe I should have put it between quotes, but I used the words 'mutable float' and 'float reference' in the original post, and this was only an attempt to clarify better. However, Python does have references all over the place, so you can achieve something similar in many ways. I know, I just wondered if there is a *standard* solution. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: floatref
On Jul 14, 2010, at 3:53 AM, Steven D'Aprano wrote: On Tue, 13 Jul 2010 19:26:34 +0200, Roald de Vries wrote: Hi all, I have two objects that should both be able to alter a shared float. So i need something like a mutable float object, or a float reference object. Does anybody know if something like that exists? I know it's not hard to build, but I have a feeling that there should be a standard solution to it. One standard solution would be to wrap the float in a class as an attribute. E.g.: a class FloatWrapper with a get and set method. Advantages: transparent, easy to implement Disadvantages: for 'f = FloatWrapper' you have to use 'f.set(1.0)' instead of 'f = 1.0', which reads less easily (I think), and a mistake like assigning with 'f = 1.0' is easily made. Another is to put it in a list: myvalue = [3.1415] pi = myvalue myvalue[0] = 3.0 assert pi[0] == 3.0 I thought about something like that, but it's a bit misleading, because the value is actually a list. An even better solution is to avoid the idiom of shared state in the first place. Whenever people say "I need shared data", the chances are very good that they don't *need* it at all, but merely *want* it because that's the idiom they're used to. I want to simulate a distributed algorithm, in which components can only communicate through shared state. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: floatref
On Jul 14, 2010, at 3:53 AM, Steven D'Aprano wrote: On Tue, 13 Jul 2010 19:26:34 +0200, Roald de Vries wrote: Hi all, I have two objects that should both be able to alter a shared float. So i need something like a mutable float object, or a float reference object. Does anybody know if something like that exists? I know it's not hard to build, but I have a feeling that there should be a standard solution to it. One standard solution would be to wrap the float in a class as an attribute. I think the nicest solution is to do this with a wrapping descriptor class. Thanks for your input! Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing versus object redefinition
On Aug 3, 2010, at 2:46 PM, wheres pythonmonks wrote: Hi! I have a class (supposed to be an abstract base class): In python (as opposed to static languages like C++) I don't seed to subclass the base class, but instead I can simply override the behavior of stub methods and values. Is there a preference between between subclassing (C++ approach) and overriding methods/data in an instance? From a design perspective? I think I prefer the override/redefine approach because it result in a thinner class hierarchy. It seems like inheriting an ABC is needed only when I must share instances (between multiple parts of the code, or if the subclass is instantiated in different places...) Thoughts? 1) some things are just not possible in instances, like overriding operators 2) abstract base classes are not supposed to be instantiable, so if you are able to do it anyway, that is a hack 3) adding stuff to instances is less reusable that adding stuff to (sub)classes 4) if I'm reading your code and want to know what an object is like, I look at the class, not through your whole program to collect all bits and pieces of information spread out over it 5) why would you want a thinner class hierarchy? So I would go for inheritance. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: subclassing versus object redefinition
Hi W, On Aug 3, 2010, at 4:38 PM, wheres pythonmonks wrote: I think that the crux of the matter is in points #3, #4, and #5 that you raised: I think #2 is important too: a program is supposed to do what you expect, and I don't expect instantiation of an ABC. On #3: Not clear that all possible specializations warrant factorization into a class. Indeed, this may result in "premature abstraction" -- and make the code less clear. Also, it will freeze in the base classes, making future refactoring a headache. I agree (for small specializations only). On #4: Unless I misunderstood something, there is nothing in python that ensures that a class definition is localized. So, putting definitions in classes, does not guarantee that the definition is at a single location in the code. That's right, but with classes it is possible (and encouraged) to keep things in a single location. The other option necessarily puts things where I don't expect them. 5) why would you want a thinner class hierarchy? The yo-yo anti-patten: http://en.wikipedia.org/wiki/Yo-yo_problem I have a pretty strong preference for using a small number of useful objects, instead of having code littered with objects strewn across the namespace. I see the point, but I would like to remark that if a program does what you expect, you won't need to understand the whole inheritance graph. Maybe there is a Python ABC tutorial out there that can enlighten me? http://docs.python.org/library/abc.html http://www.doughellmann.com/PyMOTW/abc/ Cheers, Roald PS: most people in this list prefer not top posting -- http://mail.python.org/mailman/listinfo/python-list
Re: simple integer subclass
Hi Andreas, On Aug 3, 2010, at 1:52 AM, Andreas Pfrengle wrote: I'm trying to define a subclass of int called int1. An int1-object shall behave exactly like an int-object, with the only difference that the displayed value shall be value + 1 (it will be used to display array indices starting at 1 instead of 0). Right now I have: class int1(int): def __str__(self): return int.__str__(self + 1) However, if I calculate with int1 and int- (or other number) objects, the result is always coerced to an int (or other number object), e.g: a = int1(5) b = 5 print a # "6" print a+b #"10" How can I tell int1 to be the "default integer object"? Do I need to overload *every* mathematical operation method of int, or is there an easier way? Maybe you could use: 1) a dict with keys 1..n 2) a simple list (or iterable) subclass with 1-based indices. class list1(list): def __new__(cls, *args, **kwargs): return list.__new__(cls, *args, **kwargs) def __getitem__(self, key): return list.__getitem__(self, key-1) ... etcetera Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
abstract metaclass
Hi all, I'm trying to create a metaclass that keeps track of its objects, and implement this as a collections.MutableMapping. That is, something like this: class type2(type, MutableMapping): ... /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/abc.pyc in __new__(mcls, name, bases, namespace) 83 if getattr(value, "__isabstractmethod__", False)) 84 for base in bases: ---> 85 for name in getattr(base, "__abstractmethods__", set()): 86 value = getattr(cls, name, None) 87 if getattr(value, "__isabstractmethod__", False): TypeError: Error when calling the metaclass bases 'getset_descriptor' object is not iterable Anybody knows why? Every type is just an object, isn't it? Thanks in advance, cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: easy question on parsing python: "is not None"
On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: How does "x is not None" make any sense? "not x is None" does make sense. I can only surmise that in this context (preceding is) "not" is not a unary right-associative operator, therefore: x is not None === IS_NOTEQ(X, None) Beside "not in" which seems to work similarly, is there other syntactical sugar like this that I should be aware of? 'not None' first casts None to a bool, and then applies 'not', so 'x is not None' means 'x is True'. 'not x is None' is the same as 'not (x is None)' Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: easy question on parsing python: "is not None"
On Aug 5, 2010, at 6:11 PM, Chris Rebert wrote: On Thu, Aug 5, 2010 at 8:56 AM, Roald de Vries wrote: On Aug 5, 2010, at 5:42 PM, wheres pythonmonks wrote: How does "x is not None" make any sense? "not x is None" does make sense. I can only surmise that in this context (preceding is) "not" is not a unary right-associative operator, therefore: x is not None === IS_NOTEQ(X, None) Beside "not in" which seems to work similarly, is there other syntactical sugar like this that I should be aware of? 'not None' first casts None to a bool, and then applies 'not', so 'x is not None' means 'x is True'. Absolutely incorrect. Read the final paragraph of http://docs.python.org/reference/expressions.html#notin Oops, sorry :$. -- http://mail.python.org/mailman/listinfo/python-list
Re: easy question on parsing python: "is not None"
On Aug 6, 2010, at 9:25 AM, Bruno Desthuilliers wrote: Roald de Vries a écrit : 'not None' first casts None to a bool, and then applies 'not', so 'x is not None' means 'x is True'. Obviously plain wrong : Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 42 is not None True >>> 42 is True False >>> I know. I'm sorry. I'm embarrassed. I will check my facts better before posting in the future. And I'm sorry. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 7, 2010, at 5:46 AM, Vito 'ZeD' De Tullio wrote: Default User wrote: From "the emperor's new clothes" department: 1) Why do Python lists start with element [0], instead of element [1]? "Common sense" would seem to suggest that lists should start with [1]. http://userweb.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html I think the reason why is just historical; C uses zero-based indices. In C, an array index is an offset with respect to the pointer that the array variable actually is, so 0 makes sense (my_array[0] == *my_array). I'm not convinceed (yet) by Dijkstra's reasoning. *Maybe* if you want to describe a range with two C, nor ...) uses that notation. I agree with the OP that the first item in a list would most naturally be called item 1, and therefore have index 1. (This doesn't mean I'm in favor of 1-based indices) One of the reasons I like python so much, is that you (almost) never have to use indices. Normally you just iterate over the elements. If I ever need indices, it's a strong indication that I actually want a dictionary. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 7, 2010, at 2:54 PM, D'Arcy J.M. Cain wrote: On Sat, 07 Aug 2010 13:48:32 +0200 News123 wrote: It makes sense in assembly language and even in many byte code languages. It makes sense if you look at the internal representation of unsigned numbers (which might become an index) For a complete beginner common sense dictates differently and there might be confusion why the second element in a list has index 1. Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. A new born baby is in his/her first year. It's year 1 of his/her life. For this reason, also "the year 0" doesn't exist. From the fact that a baby can be half a year old, you derive that arrays should have floats as indices? -- http://mail.python.org/mailman/listinfo/python-list
iterators and continuing after a StopIteration
Hi all, I have a list that I'm iterating over, and during the iteration items are appended. Moreover, it is iterated over in two nested loops. If the inner loop comes to the end, I want the outer loop to append an item. Is there a way to do this? Because once an iterator has raised a StopIteration, it can not go to a next item anymore. Aside question: is there a rationale for the current behavior? To me it seems more natural to continue iteration after appending new items. I want to use it for a graph walk. nodes is a list of all nodes, edges is an on the fly constructed list of edges in the order of visiting, initial_nodes is a list of (root) nodes edges = [] edge_it = iter(edges) for node in initial_nodes: edges += node.leaving_edges try: while True: edge = edge_it.next() edges += edge.head.leaving_edges except StopIteration: pass Thanks in advance, cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 7, 2010, at 3:53 PM, D'Arcy J.M. Cain wrote: On Sat, 7 Aug 2010 15:37:23 +0200 Roald de Vries wrote: Would said beginner also be surprised that a newborn baby is zero years old or would it be more natural to call them a one year old? Zero based counting is perfectly natural. A new born baby is in his/her first year. It's year 1 of his/her life. For this reason, also "the year 0" doesn't exist. From the fact that a baby can be half a year old, you derive that arrays should have floats as indices? No. You are giving me math and logic but the subject was common sense. Common usage counts ages as years with the second year called "one year old" so zero based counting is common. We don't tell Aunt Martha that little Jimmy is in his third year. We say that he is two years old and Aunt Martha, a non-programmer, understands exactly what we mean. Using one-based counting (first year, second year, etc.) would be the unnatural thing, would confuse Aunt Martha and make her spoil her apple pie and no one wants that. My point is that "0" in "Jimmy is 0" doesn't play the same role as in "item 0 of a sequence". -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 7, 2010, at 5:24 PM, Nobody wrote: On Sat, 07 Aug 2010 13:48:32 +0200, News123 wrote: "Common sense" is wrong. There are many compelling advantages to numbering from zero instead of one: http://lambda-the-ultimate.org/node/1950 It makes sense in assembly language and even in many byte code languages. It makes sense if you look at the internal representation of unsigned numbers (which might become an index) It also makes sense mathematically. E.g. for an MxN array stored as a 1-dimensional array, the element a[j][i] is at index j * N + i Nice example! -- http://mail.python.org/mailman/listinfo/python-list
Re: Class initialization
On Aug 8, 2010, at 3:32 PM, Costin Gament wrote: Hi there. I'm kind of a beginner with Python (and programming in general). My problem is with initializing a class. Let's say I've defined it like this: class foo: a = 0 b = 0 and later I'm trying to initialize two different classes like this: c1 = foo() c2 = foo() The problem I have is that c1 and c2 tend to point to the same instance, like a weird c-like pointer. Please tell me, what am I doing wrong? Your problem probably is that a and b are class variables; c1 and c2 are different objects (in your terminology: they point to different instances). See http://docs.python.org/tutorial/classes.html#class-objects for more info. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Class initialization
On Aug 8, 2010, at 4:14 PM, Costin Gament wrote: Thank you for your answer, but it seems I didn't make myself clear. You could have been clearer in your first post, yeah. Take the code: class foo: a = 0 b = 0 c1 = foo() c1.a = 5 c2 = foo() print c2.a 5 Somehow, when I try to acces the 'a' variable in c2 it has the same value as the 'a' variable in c1. Am I missing something? I can't reproduce this. Which version are you using? On Sun, Aug 8, 2010 at 4:59 PM, Roald de Vries wrote: Your problem probably is that a and b are class variables; And class variables are not instance variables. c1 and c2 are different objects (in your terminology: they point to different instances). I still suspect that this is the problem. In Python, classes are objects (instances of another class) too. In your class, you assign 0 to the variables foo.a and foo.b. See http://docs.python.org/tutorial/classes.html#class-objects for more info. So: class foo: a = 0 creates a class variable foo.a and set it to 0 b = 0 creates a class variable foo.b and set it to 0 c1 = foo() creates a new foo that can be referenced as c1 c1.a = 5 creates an instance variable c1.a and set it to 5 c2 = foo() creates a new foo that can be referenced as c2 print c2.a there is no instance variable c2.a, so the class variable foo.a is referenced 5 I get 0 here. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: python ide for ubuntu
Hi Bhanu, On Aug 12, 2010, at 4:15 AM, Bhanu Kumar wrote: Hi All, Is there any good free python IDE available in Ubuntu? See a similar discussion at django-users mailing list: http://groups.google.com/group/django-users/browse_thread/thread/562189578285211 Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 12, 2010, at 11:33 AM, Paul Rubin wrote: Baba writes: exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 packs, write an exhaustive search to find the largest number of McNuggets that cannot be bought in exact quantity. Is that a homework problem? Hint: first convince yourself that a largest number actually exists. Good point. There is actually an upper bound. Let's take 6 packs of 20, that's 120 nuggets. Now 121 nuggets can be reached by substituting 1 pack of 20 with 2 packs of 6 and 1 pack of 9. 122 = 4*20 + 2*(2*6+9) 123 = 3*20 + 3*(2*6+9) ... 126 = 6*20 + 6 127 = 121 + 6 = 5*20 + (2*6 + 9) + 6 ... etcetera. Now you have to find the largest number below 120, which you can easily do with brute force (untested): can_be_bought = [False for i in range(120)] for twenties in range(6): for nines in range(14): for sixes in range(20): can_be_bought[twenties*20+nines*9+sixes*6] = True for i in reverse(range(120)): if not can_be_bought[i]: return i Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 12, 2010, at 9:02 PM, Peter Otten wrote: Baba wrote: Thank You for helping me out. Indeed i am not looking for the code but rather for hints that direct my reasoning as well as hints as to how to write basic programs like this. You have broken down the approach into 2 parts. I have tried to solve part 1 but i'm not quite there yet. Here's my code: def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): if 6*a+9*b+20*c==n_nuggets: #print a,b,c,'n_nuggets=',n_nuggets return True else: return False can_buy(55) as you can see i am trying to loop through all combinations of values bewtween 1 and n_nuggets and when the equation resolves it should return True, else it should return False. I was hoping that when i then call my function and ask it to test a value nothing happens. What is wrong? My syntax? My semantic? Both? First, the function gives up too early; it should only return False when all combinations of a, b, c (technically: the product of the ranges) have been tried. Second, can_buy(0) should return True, but the solution 0*6 + 0*9 + 0*20 is never tried; fix your ranges accordingly. Moreover: a, b and c can range over n_nuggets/6, n_nuggets/9 and n_nuggets/20 respectively. This will work, but does too much work. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 12, 2010, at 10:51 PM, John Posner wrote: On 8/12/2010 9:22 AM, Dave Angel wrote: Now you have to find the largest number below 120, which you can easily do with brute force tgt = 120 # thanks, Dave Angel Anytime, but I'm not Dave Angel. My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 13, 2010, at 12:25 PM, Roald de Vries wrote: My previous algorithm was more efficient, but for those who like one- liners: [x for x in range(120) if any(20*a+9*b+6*c == x for a in range(x/20) for b in range(x/9) for c in range(x/6))][-1] OK, I did some real testing now, and there's some small error in the above. All solutions for all x's are given by: [(x, a, b, c) for x in range(120) for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1) if x == a*20+b*9+c*6] ... and all non-solutions by: [x for x in range(120) if not any(x == a*20+b*9+c*6 for a in range(x/20+1) for b in range(x/9+1) for c in range(x/6+1))] Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: It would be if pointers and arrays were the same thing in C. Only they’re not, quite. Which somewhat defeats the point of trying to make them look the same, don’t you think? How are they not the same? The code snippet (in C/C++) below is valid, so arrays are just pointers. The only difference is that the notation x[4] reserves space for 4 (consecutive) ints, and the notation *y doesn't. int x[4]; int *y = x; Moreover, the following is valid (though unsafe) C/C++: int *x; int y = x[4]; Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 7, 2010, at 9:14 PM, John Nagle wrote: FORTRAN, MATLAB, and Octave all use 1-based subscripts. The languages which have real multidimensional arrays, rather than arrays of arrays, tend to use 1-based subscripts. That reflects standard practice in mathematics. True, but that something is "standard mathematical notation" doesn't mean it's preferable. For example, I have never seen keyword arguments in mathematical notation, and it's definitely not standard practice, but nobody would drop them in favor of standard mathematical notation. In fact, I think, regularly mathematical notation can be improved by standard programming notation. Moreover, I don't see what's so nice about 'real' multidimensional arrays; the way to construct multidimensional arrays from one- dimensional ones is more orthogonal. And you never *have* to think about them as being one-dimensional, it's just a bonus you can (sometimes) profit from. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python "why" questions
On Aug 15, 2010, at 2:16 PM, geremy condra wrote: On Sun, Aug 15, 2010 at 4:55 AM, Roald de Vries wrote: On Aug 15, 2010, at 1:00 PM, Lawrence D'Oliveiro wrote: It would be if pointers and arrays were the same thing in C. Only they’re not, quite. Which somewhat defeats the point of trying to make them look the same, don’t you think? How are they not the same? The code snippet (in C/C++) below is valid, so arrays are just pointers. The only difference is that the notation x[4] reserves space for 4 (consecutive) ints, and the notation *y doesn't. int x[4]; int *y = x; Moreover, the following is valid (though unsafe) C/C++: int *x; int y = x[4]; Just to demonstrate that they are different, the following code compiles cleanly: int main() { int *pointer; pointer++; return 0; } While this does not: int main() { int array[0]; array++; return 0; } Interesting! Thanks for the lesson ;-). Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 15, 2010, at 11:51 PM, Ian Kelly wrote: On Sun, Aug 15, 2010 at 4:36 PM, Baba wrote: Hi Mel, indeed i thought of generalising the theorem as follows: If it is possible to buy n, n+1,…, n+(x-1) sets of McNuggets, for some x, then it is possible to buy any number of McNuggets >= x, given that McNuggets come in x, y and z packs. so with diophantine_nuggets(7,10,21) i would need 7 passes result:53 but with (10,20,30) and 10 passes i get no result You're on the right track. In the case of (10,20,30) there is no largest exactly purchasable quantity. Any quantity that does not end with a 0 will not be exactly purchasable. I suspect that there exists a largest unpurchasable quantity iff at least two of the pack quantities are relatively prime, but I have made no attempt to prove this. That for sure is not correct; packs of 2, 4 and 7 do have a largest unpurchasable quantity. I'm pretty sure that if there's no common divisor for all three (or more) packages (except one), there is a largest unpurchasable quantity. That is: ∀ i>1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x| y) means "x is no divider of y" Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 16, 2010, at 5:04 PM, Ian Kelly wrote: On Mon, Aug 16, 2010 at 4:23 AM, Roald de Vries wrote: I suspect that there exists a largest unpurchasable quantity iff at least two of the pack quantities are relatively prime, but I have made no attempt to prove this. That for sure is not correct; packs of 2, 4 and 7 do have a largest unpurchasable quantity. 2 and 7 are relatively prime, so this example fits my hypothesis. I now notice I misread your post (as 'iff the least two pack quantities are relatively prime') I'm pretty sure that if there's no common divisor for all three (or more) packages (except one), there is a largest unpurchasable quantity. That is: ∀ i>1: ¬(i|a) ∨ ¬(i|b) ∨ ¬(i|c), where ¬(x|y) means "x is no divider of y" No. If you take the (2,4,7) example and add another pack size of 14, it does not cause quantities that were previously purchasable to become unpurchasable. Then what is the common divisor of 2, 4, 7 and 14? Not 2 because ¬(2| 7), not anything higher than 2 because that's no divisor of 2. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list
Re: 79 chars or more?
Dear Jean-Michel, On Aug 18, 2010, at 10:57 AM, Jean-Michel Pichavant wrote: At least, if you still want to stick with 79 chars, do something like text = find(response, 'MPNExpirationDate', ).text self.expiration_date = translate_date(text,'%Y-%m-%d', '%m%d%Y') I don't necessarily like this example *so* much. I have no real problem with it, and maybe would write it myself sometimes, but I'm curious what people think of the following reasoning. I think that, for optimal readability, variable names should reflect the role if the function/class/module of the variable they refer to. If you stick to this convention, a function can normally be read very easily by just scanning through the left part of assignment statements. In your case, it looks like text would better be called expiration_text, or something like that. But what I would like better, is: self.expiration_date = translate_date( text= find(response, 'MPNExpirationDate', ).text, format1 = '%Y-%m-%d', # I don't know the argument name format2 = '%m%d%Y', # ... and of this one neither ) Moreover, the 'text = ...'-like statement, that are only used in the one statement after it, often interrupt a (more) logical sequence of variable assignments, and make your program a bit less readable. Cheers, Roald -- http://mail.python.org/mailman/listinfo/python-list