Re: Metaclass of a metaclass
On Jun 5, 10:48 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: Apparently it gives an error. Can anyone explain why this does not work? # Python 3.2 class MyType(type): # A metaclass... ... def __repr__(self): ... s = super().__repr__() ... return s.replace('class', 'metaclass') class Meta(metaclass=MyType): # ... of a metaclass. ... pass (...) class MyClass(metaclass=Meta): # And now try to use it. ... pass ... Traceback (most recent call last): File stdin, line 1, in module TypeError: object.__new__() takes no parameters What am I doing wrong? Meta inherit from object, but being used as a metaclass, Meta.__new__ is called with name, bases, dict etc as arguments. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not use juxtaposition to indicate function application
On Mar 16, 1:45 pm, Ray Song emacs...@gmail.com wrote: I confess i've indulged in Haskell and found f a more readable than f(a) Hmmm... What about: f a b versus f(a(b)) or was it supposed to be read as f(a)(b) or as f(a, b) ?-) And why aren't functions curried (partially applied function is another function which takes the rest arguments) by default? If you're asking why isn't Python like Haskell, the obvious answer is, well, because Python is not Haskell ;) Remember that Pythons is first and foremost an object-oriented language, where most of the support for functional idioms comes from the underlying object model. functions are central to fp, objects are central to OOP, so better to use objects than functions (hint: there's a builtin partial type). -- http://mail.python.org/mailman/listinfo/python-list
Re: Id of methods
On Feb 9, 5:06 am, Chris Angelico ros...@gmail.com wrote: On Thu, Feb 9, 2012 at 2:48 PM, Emeka emekami...@gmail.com wrote: My question is why is it that the id of Boo.daf is different from daf's hex value in the above dict? daf is not a function, it's a special object for an unbound method. http://wiki.python.org/moin/FromFunctionToMethod -- http://mail.python.org/mailman/listinfo/python-list
Re: SnakeScript? (CoffeeScript for Python)
On Feb 2, 9:23 pm, Michal Hantl michal.ha...@gmail.com wrote: See the link I attached. Ruby-like blocks would be nice too. Implicit returns. Better strings like My name is #{name}. Uhu... Looks like you want Ruby, not Python g -- http://mail.python.org/mailman/listinfo/python-list
Re: Help about dictionary append
On Feb 5, 4:29 pm, Andrew Berg bahamutzero8...@gmail.com wrote: This has nothing to do with dictionaries. If you want to add, delete, or change items, use a list (or a set if there aren't supposed to be any duplicates). AND you don't care about ordering... -- http://mail.python.org/mailman/listinfo/python-list
Re: Closures and Partial Function Application
On 31 août, 18:45, Travis Parks jehugalea...@gmail.com wrote: I was a little disappointed the other day when I realized that closures were read-only. I like to use closures quite a bit. They are not _strictly_ read only, but Python being first and foremost an OO language, it's usually way simpler to use OO instead of closures when you start needing such features. -- http://mail.python.org/mailman/listinfo/python-list
Re: NoneType and new instances
On 28 juil, 17:39, Ethan Furman et...@stoneleaf.us wrote: -- bool(0) is bool(0) True This test is not reliable - a same id can be reused for terms (I have already seen such things happening). If you want a reliable test, use: # a = bool(0) # b = bool(0) # a is b True Note that this still fails to prove anything since bool is a subclass of int and CPython caches small integers: # a = 42 # b = 42 # a is b True -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: PEP8: A cauldron of inconsistencies.
On 28 juil, 00:34, rantingrick rantingr...@gmail.com wrote: In Python4000 i'm making it a syntax error to include ANY blank lines in a func/meth body. Hopefully this is not going to happen. (snip remaining stupidities). -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to learn about metaclasses
On 25 juil, 17:36, Steven W. Orr ste...@syslang.net wrote: I have been doing a lot of reading. I'm starting to get it. I think it's really cool as well as dangerous, Dangerous ??? Why so ? Is there anything dangerous in a constructor or an initialiser ??? A metaclass is just a class, and a class is just an object. -- http://mail.python.org/mailman/listinfo/python-list
Re: Use self.vars in class.method(parameters, self.vars)
On Jul 22, 1:12 pm, caccolangrifata caccolangrif...@gmail.com wrote: Totally OT but others already answered the question... class foo(object): class names should start with an uppercase letter: class Foo(object): __init__(self, len = 9): 1/ you want to add a def statement before __init__ 2/ the argument name ('len') will shadow the builtin 'len' function within this function's scope. self.__myvar = len There are very few reasons to invoke the __name_mangling mechanism. Canonically, implementation attributes (ie: not part of the API) are written with a *single* leading underscore. Also and FWIW, there's no need to hide public attributes and add dummy accessors in Python since you can turn a plain attribute into a computed one latter without breaking client code, so only use _implementation attributes if you really mean implementation. def foo2(self, len = self_myvar): while i len: dosomething Most of the time, this is spelled: for x in somesquence: do_something Note that range() can provide the required sequence. I want to use optional parameter, so i can use myfoo = foo() or myfoo = foo(20) and also foo.foo2(20) or foo.foo2() Note that default values for function params are only computed once, when the def statement is evaluated. This is a famous gotcha, specially if you use some mutable object as default value... Also, since neither the class nor - a fortiori - the instance exist when the def statement is evaluated, there's no way to make reference to the instance at this time. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 and extraneous whitespace
On 21 juil, 20:46, Andrew Berg bahamutzero8...@gmail.com wrote: -BEGIN PGP SIGNED MESSAGE- Hash: RIPEMD160 On 2011.07.21 01:32 PM, Thomas Jollans wrote: So, the PEP says: do not align operators. End of story. I'm pretty sure that colons, commas and equals signs are not operators. 1/ you can consider the equal sign ('=') is the binding operator. 2/ since {'key':'val'} is equivalent to dict(key=val), you can consider colons as a binding operator here 3/ since it's the comma - not the parens - that makes a tuple, ie t = 1, 2 is equivalent to t = (1,2), you can also consider commas as an operator here ;) FWIW: I'm pretty anal when it comes to code formatting and coding conventions (rationale : don't make me think), and I do agree with pep8: consistent spacing between tokens is much more readable than aligned stuff. And it's way less painfull to maintain... -- http://mail.python.org/mailman/listinfo/python-list
Re: Please critique my script
On Jul 15, 8:36 am, Chris Angelico ros...@gmail.com wrote: This can alternatively be done with map(): sortlist = map(lambda x,y: x+y, npalist, nxxlist) (It would have been a lot cleaner if Python exposed its operators as functions. from operator import add -- http://mail.python.org/mailman/listinfo/python-list
Re: list(), tuple() should not place at Built-in functions in documentation
On Jul 15, 4:58 am, Inside fancheyuj...@gmail.com wrote: Hey guy,thx for you feedback first. But I can't follow your opinion.Why?because of the list tuple are placed at built-in function,so before I type 'list' unintentionally on the pyshell and it show me type 'list', I never know that the name 'list' is a type,I used to consider it's a function to produce 'list' type. so,after I figure out this matter,I have to change all my code assert isinstance(someobj, (type([]), type((0, to assert isinstance(someobj, (list, tuple)),that's not a funny job. Are you sure you need such assertions in your code ? -- http://mail.python.org/mailman/listinfo/python-list
Re: list(), tuple() should not place at Built-in functions in documentation
On Jul 15, 9:27 am, bruno.desthuilli...@gmail.com bruno.desthuilli...@gmail.com wrote: On Jul 15, 4:58 am, Inside fancheyuj...@gmail.com wrote: Hey guy,thx for you feedback first. But I can't follow your opinion.Why?because of the list tuple are placed at built-in function,so before I type 'list' unintentionally on the pyshell and it show me type 'list', I never know that the name 'list' is a type,I used to consider it's a function to produce 'list' type. so,after I figure out this matter,I have to change all my code assert isinstance(someobj, (type([]), type((0, to assert isinstance(someobj, (list, tuple)),that's not a funny job. Are you sure you need such assertions in your code ? Sorry, Ben already mentionned this. Need more coffee obviously :-/ -- http://mail.python.org/mailman/listinfo/python-list
Re: None versus MISSING sentinel -- request for design feedback
On Jul 15, 8:08 am, Chris Angelico ros...@gmail.com wrote: Agreed that float('nan') and and spam are all bad values for Missings. Possibly should come out as 0 In the face of ambiguity, refuse the temptation to guess. As far as I'm concerned, I'd expect this to raise a TypeError... -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible File iteration bug
On Jul 14, 9:46 pm, Billy Mays no...@nohow.com wrote: I noticed that if a file is being continuously written to, the file generator does not notice it: def getLines(f): lines = [] for line in f: lines.append(line) return lines what's wrong with file.readlines() ? -- http://mail.python.org/mailman/listinfo/python-list
Re: None versus MISSING sentinel -- request for design feedback
On Jul 15, 7:28 am, Steven D'Aprano steve +comp.lang.pyt...@pearwood.info wrote: I'm designing an API for some lightweight calculator-like statistics functions, such as mean, standard deviation, etc., and I want to support missing values. Missing values should be just ignored. E.g.: (snip) Against None: it's too easy to mistakenly add None to a data set by mistake, because functions return None by default. Yeps. In favour of a dedicated MISSING singleton: it's obvious from context. It's not a lot of work to implement compared to using None. Hard to accidentally include it by mistake. If None does creep into the data by accident, you get a nice explicit exception. Against MISSING: users may expect to be able to choose their own sentinel by assigning to MISSING. I don't want to support that. What about allowing users to specificy their own sentinel in the simplest pythonic way: # stevencalc.py MISSING = object() def mean(values, missing=MISSING): your code here Or, if you want to make it easier to specify the sentinel once for the whole API: # stevencalc.py MISSING = object() class Calc(object): def __init__(self, missing=MISSING): self._missing = missing def mean(self, values): # your code here # default: _calc = Calc() mean = _calc.mean # etc... My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: None versus MISSING sentinel -- request for design feedback
On Jul 15, 9:44 am, Cameron Simpson c...@zip.com.au wrote: On 15Jul2011 15:28, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: | Against MISSING: users may expect to be able to choose their own sentinel by | assigning to MISSING. I don't want to support that. Well, we don't have readonly values to play with :-( Personally I'd do what I did above: give it a private name like _MISSING so that people should expect to have inside (and unsupported, unguarenteed) knowledge if they fiddle with it. I think the point is to allow users to explicitely use MISSING in their data sets, so it does have to be public. But anyway: ALL_UPPER names are supposed to be treated as constants, so the warranty void if messed with still apply. -- http://mail.python.org/mailman/listinfo/python-list
Re: None versus MISSING sentinel -- request for design feedback
On Jul 15, 10:28 am, Teemu Likonen tliko...@iki.fi wrote: How about accepting anything but ignoring all non-numbers? Totally unpythonic. Better to be explicit about what you expect and crash as loudly as possible when you get anything unexpected. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Wizard, with apologies to The Who
On Jul 12, 6:40 pm, John Keisling maththespia...@gmail.com wrote: After too much time coding Python scripts and reading Mark Lutz's Python books, I was inspired to write the following lyrics. Brillant. This deserves to become a cpython easter egg along with import this or from __future__ import braces. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write a file generator
On Jul 12, 4:46 pm, Billy Mays no...@nohow.com wrote: I want to make a generator that will return lines from the tail of /var/log/syslog if there are any Err... I must have missed something, but python files are their own iterators. 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. pythonrc start pythonrc done f = open(/var/log/syslog) for line in f: ... print line ... (snip unintersting syslog stuff)) , but my function is reopening the file each call: How do you know, and how do you call your function ? def getLines(): with open('/var/log/syslog', 'rb') as f: while True: line = f.readline() if line: yield line else: raise StopIteration I know the problem lies with the StopIteration, but I'm not sure how to tell the caller that there are no more lines for now. If you want the generator to wait until new content is available, just remove the raise part - but you'll have a blocking call... Else, I don't see what behaviour you are expecting exactly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Wgy isn't there a good RAD Gui tool fo python
On Jul 11, 2:42 am, Adam Tauno Williams awill...@whitemice.org wrote: But Open Source land is simply too fragmented. There are too many database bindings [and RAD requires something like an ORM (think SQLalchemy)] and far too many GUI toolkits [Qt, Gtk, wx, and the list goes on and on]. Nothing can muster the gravity required to bring a quality RAD tool into existence. Why too many ? Natural selection is a GoodThing. Python is known as the language with more web frameworks than keywords, and this doesn't prevent some of these frameworks to be 1/ pretty good and 2/ becoming de facto standards. I also suspect - seeing some of the articles that float across the FLOSS-o-sphere mentioning RAD - that many Open Source developers have never had the pleasure [yes, it is a pleasure] of using a professional RAD tool. This is slightly arrogant. Did you occur to you that quite a few OSS developers may have at least as much experience as you do with these kind of tools and just happen to actually prefer the unix way of doing things ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Project-wide variable...
On Jun 23, 4:42 pm, Peter Otten __pete...@web.de wrote: (snip) However I end up doing it in every submodule, so it seems a little redundant. I wish I could load the variable in the parent program and have it be available in all submodules. Am I missing something? You can modify the builtin namespace: But I don't think it's a good idea. Even posting about it is already a bad idea IMHO. There are good reasons this isn't documented. @OP: yes, explicit imports are boring... until you have to debug and maintain the code, and then you start to LOVE them. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using django ORM from web browser and from command line apps
On Jun 22, 2:21 am, News123 news1...@free.fr wrote: Out of curiousity: Do you know whether the imports would be executed for each potential command as soon as I call manage.py or only 'on demand'? Why would you care ? Just importing the module shouldn't have any side effect. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this base class?
On 18 juin, 06:17, John Salerno johnj...@gmail.com wrote: Note: I have in mind that when a specific subclass (Warrior, Wizard, etc.) is created, the only argument that will ever be passed to the __init__ method is the name. The other variables will never be explicitly passed, but will be set during initialization. __init__ is actually supposed to be the initialization phase, but well g 1) class Character: If you using Python 2.x, make this: class Character(object): def __init__(self, name, base_health=50, base_resource=10): self.name = name self.health = base_health self.resource = base_resource If neither base_health nor base_resource are supposed to be passed in, why make them arguments at all: class Character(object): def __init__(self, name): self.name = name self.health = 50 self.resource = 10 2) class Character: base_health = 50 base_resource = 10 def __init__(self, name): self.name = name self.health = base_health self.resource = base_resource Did you at least tried this one ? Hint: it won't work. 3) BASE_HEALTH = 50 BASE_RESOURCE = 10 class Character: def __init__(self, name): self.name = name self.health = BASE_HEALTH self.resource = BASE_RESOURCE This is probably what I'd do. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best way to write this base class?
On 18 juin, 13:24, Tim Chase python.l...@tim.thechases.com wrote: On 06/18/2011 05:55 AM, bruno.desthuilli...@gmail.com wrote: On 18 juin, 06:17, John Salernojohnj...@gmail.com wrote: class Character: base_health = 50 base_resource = 10 def __init__(self, name): self.name = name self.health = base_health self.resource = base_resource Did you at least tried this one ? Hint: it won't work. If you want it, you can use self.health = Character.base_health Though I'd treat them as semi-constants and capitalize them like your 3rd case: class Character(object): BASE_HEALTH = 50 ... def __init__(...): ... self.health = Character.BASE_HEALTH If you go that way, then using polymorphic dispatch might (or not, depending on the game's rules g) be a good idea: class Character(object): BASE_HEALTH = 50 ... def __init__(self, name): ... self.health = type(self).BASE_HEALTH This would allow different Character subclasses to have different BASE_HEALTH etc..., defaulting to the base class values. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid () when writing a decorator accepting optional arguments?
On Jun 11, 10:28 pm, Ian Kelly ian.g.ke...@gmail.com wrote: Since there is no way to distinguish the two cases by the arguments, def deprecated(func=None, replacement=None): if replacement: # handle the case where a replacement has been given elif func: # handle the case where no replacement has been given else: raise ValueErrorOrSomethingLikeThis() @deprecated(replacement=other_func): def some_func(args): # code here @deprecated def another_func(args): # code here My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid () when writing a decorator accepting optional arguments?
On Jun 17, 3:53 pm, Ian Kelly ian.g.ke...@gmail.com wrote: That works, but I would be concerned about forgetting to specify the argument by keyword (snip funny side effect description) Also, as in my suggestion, it doesn't seem like a big improvement to have to type out replacement= when you need the replacement function just to avoid typing () when you don't. I wholefully agree with you on both points. FWIW, it was just for the sake of being technically correct which, as everyone should know, is the best kind of correct), not about being practically helpful in anyway g -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Web
On Jun 15, 9:50 am, sidRo slacky2...@gmail.com wrote: Is Python only for server side? Is it a theoretical question or a practical one ?-) More seriously: except for the old proof-of-concept Grail browser, no known browser uses Python as a client-side scripting language. -- http://mail.python.org/mailman/listinfo/python-list
Re: BadValueError: Property title is required
On May 31, 10:32 am, Chris Rebert c...@rebertia.com wrote: On Tue, May 31, 2011 at 1:21 AM, michal.bulla michal.bu...@gmail.com wrote: Hello, I'm trying to create simple method to create category. I set the model category: class Category(db.Model): title = db.StringProperty(required=True) clashes_count = db.IntegerProperty(default=0) snip some obviously Django-using code Not obviously Django at all. The problem is that I'm getting an error BadValueError: Property title is required. Can you help me with that ? Thanks Try asking on the Django mailing list:http://groups.google.com/group/django-users Arf ! I just told the guy he was on the wrong group when he (re?)posted this on django-users. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bring out yer dead Bring out yer dead
On 30 mar, 09:12, harrismh777 harrismh...@charter.net wrote: 2.6.2 2.5.1 == (___) \--- ( 3.2 ) Cartman: Bring out yer dead,.. bring out yer dead... Devlpr: Here' one... (Python27) Cartman: ... nine pence! Python27: I'm not dead! Cartman: What? Devlpr: Nothing, here's your nine pence. Python27: I'm not dead! Cartman: There, he says he's not dead... Devlpr: yes he is Python27: I'm not! Cartman: He isn't? Devlpr: Well, he will be soon, he's very ill... Python27: I'm getting better! Devlpr: no yer not, you'll be stone dead in a moment... Cartman: I can't take 'em like that, its against regulations! Python27: I don't want to go on the cart! Devlpr: Oh, don't be such a baby... Cartman: I can't take him. Python27: I feel fine! Devlpr: oh, do us a favor, 'ey? Cartman: I can't. Devlpr: ah, can you hang around for a couple of minutes, it won't take long? Cartman: I've got to get to Robinson's, they've lost nine today. Devlpr: Well, when's your next round then? Cartman: Thursday. Python27: I think I'll go for a walk ! Devlpr: You're not fooling anyone ya know...(!) Devlpr: Look, isn't there anything you can do? Python27: I feel happy! I feel happy! :) Cartman: Club( Python27 ).__whack__ Devlpr: Oh thank you very much ! Cartman: Not at all, Devlpr: see ya Thursday?! Cartman: Right. Horse(virtual).__clomping__ {Guido?} Devlpr: who's that then... Cartman: I don't know. Devlpr: ... must be a king! Cartman: Why? Devlpr: ... hasn't got shitul-over'em. 2.7.1 2.6.2 2.5.1 == (___) \--- ( 3.2 ) +1 QOTW - but this will make for the longuest QOTW ever g -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting an array of string to array of float
On 25 mar, 16:19, joy99 subhakolkata1...@gmail.com wrote: Dear Group, I got a question which might be possible but I am not getting how to do it. If I have a list, named, list1=[1.0,2.3,4.4,5.5] Now each element in the array holds the string property if I want to convert them to float, how would I do it? Extracting the values with for and appending to a blank list it would not solve the problem. If appended to a blank list, it would not change the property. If any one of the learned members can kindly suggest any solution? print source ['0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0', '7.0', '8.0', '9.0'] source[:] = map(float, source) print source [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0] Note the source[:] = part - it modifies the list in place. -- http://mail.python.org/mailman/listinfo/python-list
Re: Redundant importing of modules
On 21 déc, 03:03, Steve Holden st...@holdenweb.com wrote: On 12/20/2010 8:36 PM, Jshgwave wrote: When writing a function that uses a module such as NumPy, it is tempting to include the statement import numpy or import numpy as np in the definition of the function, in case the function is used in a script that hasn't already imported NumPy. (answering the OP - post didn't show off here on c.l.py): This is actually totally useless. The global namespace of a function is the namespace of the module in which it has been defined, not the namespace of the module where the function is called. -- http://mail.python.org/mailman/listinfo/python-list
Re: string identity and comparison
On 16 déc, 12:55, Jean-Michel Pichavant jeanmic...@sequans.com wrote: Fellows, I'd like to illutrate the fact that comparing strings using identity is, most of the time, a bad idea. However I'm searching a short example of code that yields 2 differents object for the same string content. id('foo') 3082385472L id('foo') 3082385472L Anyone has that kind of code ? 2 points: 1- an id is only valid for the lifetime of a given object - when the object has been collected, the id can be reused for another object. 2- in CPython, strings that would be valid Python identifiers are interned. Try using a string that would not be a valid Python identifier 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. id(Not a valid python identifier) 3076522016L id(Not a valid python identifier) 3076522016L s1 = Not a valid python identifier s2 = Not a valid python identifier s1 is s2 False s1 == s2 True HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: string identity and comparison
On 16 déc, 15:52, Jean-Michel Pichavant jeanmic...@sequans.com wrote: bruno.desthuilli...@gmail.com wrote: On 16 d c, 12:55, Jean-Michel Pichavant jeanmic...@sequans.com wrote: id('foo') 3082385472L id('foo') 3082385472L Anyone has that kind of code ? 2 points: 1- an id is only valid for the lifetime of a given object - when the object has been collected, the id can be reused for another object. that's exactly what happened in my example, the 2 'foo' are not the same object actually, the fact that the 2 successive id() calls return the same value is implementation specific. Thanks for pointing that out, I didn't realize in the first place. been here, done that :-/ -- http://mail.python.org/mailman/listinfo/python-list
Re: string identity and comparison
On 16 déc, 15:53, Jean-Michel Pichavant jeanmic...@sequans.com wrote: Mel wrote: Jean-Michel Pichavant wrote: Fellows, I'd like to illutrate the fact that comparing strings using identity is, most of the time, a bad idea. However I'm searching a short example of code that yields 2 differents object for the same string content. id('foo') 3082385472L id('foo') 3082385472L Anyone has that kind of code ? Currently, CPython interns strings that look like identifiers. Any strings that don't look like identifiers are on their own: mwil...@tecumseth:~/sandbox/candlekit/stringlight-1$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type help, copyright, credits or license for more information. a = 'x(3)' id(a) 3075373248L c='x(3)' id(c) 3075373856L a==c True Mel. thanks to all who replied. It looks like there are some differences between python 2.5 2.6, I tested all the possibilities I've been given in this thread and did not always get the same result. Which FWIW is one more reason to avoid identity testing on strings - too much implementation specific stuff happening here. -- http://mail.python.org/mailman/listinfo/python-list
Re: while True or while 1
On 14 déc, 21:38, Arnaud Delobelle arno...@gmail.com wrote: I almost used: True = to be or not to be # that is the question KEYBOARD !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Objects and validation
On 12 déc, 15:28, pyt...@lists.fastmail.net wrote: I have a routine in Python which is extracting information from a website. This information is read and inserted into objects. I currently have all the validations and checks implemented in the routines which are reading the HTML and creating the objects. It is however also possible to move all the validations into the class itself. What is considered the best practice for this: validation in the functions which read the information and creates the objects or in the class itself? There's no one-size-fits-all answer to this question. Part of the work really belongs to the layer that accepts data from the outside world, part of it belong to the 'model' object itself. In any case, the 'model' object shouldn't have to worry about data conversion etc - like, if one of the attribute is supposed to be a datetime, it's the client code's responsability to provide a proper datetime object, not a string that may (or not) be the textual representation of a date and time. -- http://mail.python.org/mailman/listinfo/python-list
Re: v = vte.Terminal() AttributeError: 'module' object has no attribute 'Terminal'
On 7 déc, 12:05, Steve steve.gnuli...@gmail.com wrote: Hi, I try to run a terminal emulation using Python+Gtk+Vte. Before develop my own sources, i'm testing some examples like this ;http://www.eurion.net/python-snippets/snippet/Embed%20a%20VTE%20termi... But when i try to run, i get this message error; v = vte.Terminal() AttributeError: 'module' object has no attribute 'Terminal' Before any other thing, make sure the vte module you imported is the expected one. Edit your script that way: # import vte try: import vte except: error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, 'You need to install python bindings for libvte') error.run() sys.exit (1) else: print using wte module : %s % vte and check the module path this prints to your stdout. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I define class methods outside of the class?
On 2 déc, 06:36, Jeremy jlcon...@gmail.com wrote: I have some methods that I need (would like) to define outside of the class. I know this can be done by defining the function and then setting it equal to some member OT assignement or binding might be the terms you were looking for here ;) Also in Python we talk about attributes, not members /OT of an instance of the class. What you describe here will not define class methods, nor even instance methods FWIW - it will only make the function an attribute of the instance, but won't turn the function into a method (IOW: the function won't get the instance as first argument). Also and while we're at it, a Python classmethod is something special - it's a method that can be called on either an instance or the class itself, and takes the class - not the instance - as first argument. But, because of the complexity of what I'm doing (I have to set many functions as class methods) I would rather not do this. Can someone show me how to do this? Is it even possible? To no do this ? Yes, certainly g More seriously: if your problem is to dynamically add a bunch of methods to an existing *class*, it's quite easy - just import the class and assign your functions to it, ie: from otherlib import OtherClass def foo(self): print %s.foo % self OtherClass.foo = foo And voila, The foo method is now available to all (even already existing) instances of OtherClass. If this doesn't answer your question, please provide more context. Can decorators be used here? What for ? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I define class methods outside of the class?
On 2 déc, 15:45, Jeremy jlcon...@gmail.com wrote: On Dec 1, 10:47 pm, James Mills prolo...@shortcircuit.net.au wrote: On Thu, Dec 2, 2010 at 3:36 PM, Jeremy jlcon...@gmail.com wrote: I have some methods that I need (would like) to define outside of the class. I know this can be done by defining the function and then setting it equal to some member of an instance of the class. But, because of the complexity of what I'm doing (I have to set many functions as class methods) I would rather not do this. Can someone show me how to do this? Is it even possible? Can decorators be used here? Do you mean something like this ? @classmethod def foo(cls): print I am the foo classmethod on %r % cls class Foo(object): pass Foo.foo = foo cheers James Thanks, James. That is almost exactly what I want. However, I want to avoid doing Foo.foo = foo Is this going to be possible? def patch(cls): def _patch(func): setattr(cls, func.__name__, func) return func return _patch class Foo(object): pass @patch(Foo) def bar(self): print self f = Foo() f.bar() I'm trying to understand how decorators are used. Are they really necessary in this example? In the above example, the classmethod type was used as a decorator to turn the function into, well, a classmethod (read my other answer in this thread if you don't know what a classmethod is). -- http://mail.python.org/mailman/listinfo/python-list
Re: strange TypeError exception in function compiled from a string
On 1 déc, 14:48, nelson nelson1...@gmail.com wrote: Hi all, I have this function, defined in a string and ecetuted through ad exec call def cell1(d): x=d.get('x') print x import y return y.add(y.add(self.adf0(x),self.adf0(x)),self.adf0(x)) d is a dict of this kind {'x':2} I receive the following exception, that i find very strange... File string, line 7, in cell1 TypeError: 'dict' object is not callable I have tested all the function al line 7, and none of them raise any exception. Have anyone some suggestion on how to solve this? Not without the minimal executable code reproducing your error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recursively __getattribute__
On 22 nov, 21:44, Roman Dolgiy tost...@gmail.com wrote: http://stackoverflow.com/questions/4247036/python-recursively-getattr... I need to support a lot of legacy code, with THC4k's approach I'll have to modify project's existing code to use obj.attr1.val instead of obj.attr1 but this is not suitable. You should probably re-read THC4k's answer. His code works just fine AFAICT: # the proxy maps attribute access to another object class GetattrProxy(object): def __init__(self, proxied, prefix=None): self.proxied = proxied self.prefix = prefix def __getattr__(self, key): attr = (key if self.prefix is None else self.prefix + '__' + key) try: # if the proxied object has the attr return it return getattr(self.proxied, attr) except AttributeError: # else just return another proxy return GetattrProxy(self.proxied, attr) # the thing you want to wrap class Target(object): attr1__attr2__attr3 = 5 attr2 = attr2 t = Target() proxy = GetattrProxy(t) print proxy.attr1.attr2.attr3 : '%s' % proxy.attr1.attr2.attr3 print proxy.attr2 : '%s' % proxy.attr2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Descriptors and decorators
On 25 oct, 17:18, Joost Molenaar j.j.molen...@gmail.com wrote: Thanks, Bruno. Your python-wiki page and walk-through for the Decorator code make it clear. I now finally understand that methods are in fact ordinary functions at the time the class is created, and that the descriptor protocol turns them into bound or unbound methods when they're accessed as attributes: (snip) Cheers! Now I will try to wrap my brain around metaclasses and coroutines. ;-) Metaclasses are nothing special, really. Python classes are plain objects and you can as well instanciate a class directly - the class statement being mostly syntactic sugar: def func(obj, x): obj.x = x NewClass = type(NewClass, (object,), {'__init__':func, 'foo':lambda z: z.x + 2}) So in the end, a metaclass is just another plain class, that is used to instanciate class objects. -- http://mail.python.org/mailman/listinfo/python-list
Re: init inside def
On 25 oct, 12:05, targetsmart targetsm...@gmail.com wrote: Hi, today I just came across a python code snippet where __init__ was defined inside a function.. I am not able to understand the reason why The code snippet was similar like def func1(a,b): def __init__(): func2(a,b) def func2(a,b): if a == b: return True else: return False return False So far I have seen __init__ only used inside class definitions not inside any function, could somebody tell me how __init__ can be useful inside a function definition..? __init__ as an inner function name has no special meaning. And in the above snippet it happens to to be totally useless since it's not neither called nor returned nor used in any way. In fact, since func2 is not used neither (and totally braindead FWIW), the above snippet is functionally equivalent to: def func1(a, b): return False Perhaps the real snippet would make more sense ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Descriptors and decorators
On 25 oct, 14:15, Joost Molenaar j.j.molen...@gmail.com wrote: WebOb contains this little nugget of code that allows you to define a decorator that works on both methods and functions: class Decorator(object): def __init__(self, func): self.func = func def __get__(self, object, type=None): if type is None: return self newfunc = self.func.__get__(object, type) return self.__class__(newfunc) (snip) I'm still not sure what Decorator.__get__ does, or at least I'm not sure enough to be able to explain it well. http://wiki.python.org/moin/FromFunctionToMethod Logically, the method C.m is unbound at the time the class is defined At the time the class is defined - that is (usually) when the class statement's body is executed -, 'm' is a plain function. Note that by that time, class 'C' doesn't even exist, so there's no way you could have a 'C.m' method ;) So, your decorator is applied to a function, and wraps it into a Decorator object. Or more exactly, the function is defined, then the Decorator class is called so a new Decorator object is instanciated with the function as argument, and finally this Decorator instance is rebound to the name under which the function was formely known. All this happenning _before_ class C even exists, so when the class object is created, it has an attribute by the name of the decorated function which is in fact a Decorator instance. Now this instance is itself a descriptor, so when C.m or o.m are looked up, the descriptor protocol is fired and Descriptor.__get__ is called. If called without at least a 'type' argument, it just returns itself, so it works as an ordinary function. Else it calls the function's own descriptor implementation to get a bound or unbound method, and returns a new instance of the decorator with the method as argument. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Why flat is better than nested?
On 25 oct, 15:34, Alex Willmer a...@moreati.org.uk wrote: On Oct 25, 11:07 am, kj no.em...@please.post wrote: In The Zen of Python, one of the maxims is flat is better than nested? Why? Can anyone give me a concrete example that illustrates this point? I take this as a reference to the layout of the Python standard library and other packages i.e. it's better to have a module hierarchy of depth 1 or 2 and many top level items, than a depth of 5+ and only a few top level items. (snip) This also applies to inheritance hierarchies (which tend to be rather flat in Python compared to most mainstreams OOPLs), as well as nested classes etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: subclass constructor problem
On 5 oct, 17:52, de...@web.de (Diez B. Roggisch) wrote: Btw, you are a bit on the overprotective side. The convention for marking attributes (methods or objects alike) private s/private/implementation/ I find that thinking in terms of interface / implementation instead of public / private really helps focusing on what's important here. is by prefixing them with a *single* underscore. And FWIW, the usual idiom is to avoid dummy accessor and use plain attributes until you have a need for a computed one - in which case you use a descriptor (either the builtin 'property' or custom descriptor). Python is not Java. -- http://mail.python.org/mailman/listinfo/python-list
Re: if the else short form
On 30 sep, 19:22, Andreas Waldenburger use...@geekmail.invalid wrote: On Thu, 30 Sep 2010 03:42:29 -0700 (PDT) bruno.desthuilli...@gmail.com bruno.desthuilli...@gmail.com wrote: On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote: On 2010-09-29, Tracubik affdfsdfds...@b.com wrote: button = gtk.Button((False,, True,)[fill==True]) Oh, what a nasty idiom. Well, it's not very different from dict-based dispatch , which is the core of OO polymorphic dispatch in quite a few dynamic OOPLs. Anyway, it's a common Python idiom and one that's not specially hard to grasp so I don't see any legibility problem here. But it does violate the explicit is better than implicit tenet, don't you think? Why so ? The doc clearly states that booleans are integers with True == 1 and False == 0, so there's nothing implicit here. -- http://mail.python.org/mailman/listinfo/python-list
Re: namespace hacking question
On 1 oct, 14:12, Fuzzyman fuzzy...@gmail.com wrote: On Sep 30, 6:07 pm, kj no.em...@please.post wrote: This is a recurrent situation: I want to initialize a whole bunch of local variables in a uniform way, but after initialization, I need to do different things with the various variables. What I end up doing is using a dict: d = dict() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) foo(d['spam']) bar(d['ham']) baz(d['eggs']) This is fine, but I'd like to get rid of the tedium of typing all those extra d['...']s. I.e., what I would *like* to do is something closer to this: d = locals() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) foo(spam) bar(ham) baz(eggs) ...but this results in errors like NameError: global name 'spam' is not defined. But the problem is deeper than the fact that the error above would suggest, because even this fails: spam = ham = eggs = None d = locals() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) foo(spam) # calls foo(None) bar(ham) # calls bar(None) baz(eggs) # calls baz(None) In other words, setting the value of locals()['x'] does not set the value of the local variable x. I also tried a hack using eval: for v in ('spam', 'ham', 'eggs'): eval %s = init('%s') % (v, v) but the = sign in the eval string resulted in a SyntaxError: invalid syntax. Is there any way to use a loop to set a whole bunch of local variables (and later refer to these variables by their individual names)? One way: import sys module = sys.modules[__name__] for entry in ('spam', 'eggs', 'ham'): setattr(module, entry, 'some value') Only works on globals - which you can already set using globals() IIRC. -- http://mail.python.org/mailman/listinfo/python-list
Re: if the else short form
On 29 sep, 19:20, Seebs usenet-nos...@seebs.net wrote: On 2010-09-29, Tracubik affdfsdfds...@b.com wrote: button = gtk.Button((False,, True,)[fill==True]) Oh, what a nasty idiom. Well, it's not very different from dict-based dispatch , which is the core of OO polymorphic dispatch in quite a few dynamic OOPLs. Anyway, it's a common Python idiom and one that's not specially hard to grasp so I don't see any legibility problem here. -- http://mail.python.org/mailman/listinfo/python-list
Re: namespace hacking question
On 30 sep, 19:07, kj no.em...@please.post wrote: This is a recurrent situation: I want to initialize a whole bunch of local variables in a uniform way, but after initialization, I need to do different things with the various variables. What I end up doing is using a dict: d = dict() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) foo(d['spam']) bar(d['ham']) baz(d['eggs']) This is fine, but I'd like to get rid of the tedium of typing all those extra d['...']s. I.e., what I would *like* to do is something closer to this: d = locals() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) foo(spam) bar(ham) baz(eggs) ...but this results in errors like NameError: global name 'spam' is not defined. But the problem is deeper than the fact that the error above would suggest, because even this fails: spam = ham = eggs = None d = locals() for v in ('spam', 'ham', 'eggs'): d[v] = init(v) The local namespace is not implemented as a dict - locals() only returns a dict representation of it, so updating this dict has no effect on the local namespace. This is documented FWIW. I also tried a hack using eval: for v in ('spam', 'ham', 'eggs'): eval %s = init('%s') % (v, v) but the = sign in the eval string resulted in a SyntaxError: invalid syntax. eval only accepts expressions. You'd need exec here - but that's a bit ugly. -- http://mail.python.org/mailman/listinfo/python-list
Re: list problem...
On 29 sep, 14:17, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: On Tue, 28 Sep 2010 20:11:51 +0100, Rog wrote: On Tue, 28 Sep 2010 11:59:08 -0700, geremy condra wrote: On Tue, Sep 28, 2010 at 11:44 AM, Rog r...@pynguins.com wrote: Hi all, Have been grappling with a list problem for hours... a = [2, 3, 4, 5,.] b = [4, 8, 2, 6,.] Basicly I am trying to place a[0], b[0] in a seperate list IF a[2] and b[2] is present. I have tried sets, zip etc with no success. I am tackling Euler projects with Python 3.1, with minimal knowledge, and having to tackle the language as I progress. Enjoyable frustration :) I'm not clear on what your actual problem is, could you restate it? It sounds like you want to copy the ith element out of a and b into some other list- call it c- when the (i+2)th element meets some condition. What's the condition? Geremy Condra The condition is that the i-th element is inverted, but not equal. eg 4,2 - 2,4 , 34,5 - 5,34 etc. Hope that is clearer. Clear as mud. Perhaps you should given an example. Given input a = [2, 3, 4, 5, 6, 7] b = [4, 8, 2, 6, 10, 42] what output are you expecting, AFAICT, the OP expects [2, 4] in this case, but it's not clear what he'd expect for let's say: a = [2, 3, 21, 4, 5, 6, 7] b = [4, 8, 22, 2, 6, 10, 42] (the 'reversed' pair is at i+3, not i+2) or a = [0, 2, 3, 4, 5, 6, 7] b = [3, 4, 8, 2, 6, 10, 42] (the first pair is at pos 1, not 0) or a = [2, 3, 4, 8, 6, 7] b = [4, 8, 2, 3, 10, 42] (there's a second 'non-reversed/reversed' match at positions resp. 1 3) -- http://mail.python.org/mailman/listinfo/python-list
Re: if the else short form
On 29 sep, 13:38, Hrvoje Niksic hnik...@xemacs.org wrote: Tracubik affdfsdfds...@b.com writes: button = gtk.Button((False,, True,)[fill==True]) (snip) BTW adding ==True to a boolean value is redundant and can even break for logically true values that don't compare equal to True (such as the number 10 or the string foo). Note that if fill is actually an int outside the (0, 1) domain, it will break too. The correct test would be: (False,, True,)[bool(fill)]) ['a', 'b'][bool(10)] 'b' ['a', 'b'][bool('')] 'a' ['a', 'b'][bool(yes)] 'b' ['a', 'b'][bool([])] 'a' ['a', 'b'][bool([42, 24])] 'b' ['a', 'b'][bool(None)] 'a' -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning inheritance
On 18 sep, 17:25, Niklasro nikla...@gmail.com wrote: Hi How can I make the visibility of a variable across many methods or files? To avoid repeating the same line eg url = os.environ['HTTP_HOST'] if os.environ.get('HTTP_HOST') else os.environ['SERVER_NAME'] First learn to use Python correctly: url = os.environ.get(HTTP_HOST, os.environ[SERVER_NAME]) = dict.get(key, default=None) Also and FWIW, neither HTTP_HOST not SERVER_NAME are really urls... I repeat for many methods. So declaring it to a super class and inheriting it is my plan. Do you agree or propose otherwise? Not enough background to answer. -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
On 27 août, 18:20, Mark Lawrence breamore...@yahoo.co.uk wrote: On 27/08/2010 15:43, Bruno Desthuilliers wrote: Dave Angel a écrit : (snip) or (untested) def is_palindrom(s): s = s.lower() return s == s[::-1] Right, go on, make me feel a bit more stupid :-/ Who's next ? It could be worse, try responding to issue 9702. :) lol ! Nice one, indeed. -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
On 27 août, 20:05, Jussi Piitulainen jpiit...@ling.helsinki.fi def palindromep(s): return ( s == or ( s[0] == s[-1] and palindromep(s[1:-1]) ) ) I-can-write-lisp-in-any-language-p !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: palindrome iteration
On 29 août, 06:39, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Steven D'Aprano wrote: I'm not entirely sure what the use-case for swapcase is. Obviously it's for correcting things that were typed in with tHE cAPS lOCK kEY oN bY mISTAKE. :-) +1 QOTW !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newsgroup for beginners
On 20 nov, 20:42, Ethan Furman et...@stoneleaf.us wrote: Aahz wrote: In article hdt6tb$9d...@reader1.panix.com, Grant Edwards inva...@invalid.invalid wrote: You've really got to try pretty hard to create one. But if you want to, here's how to do it: 1) Start by complaining that your program doesn't work because of a bug in Python. [...] Post of the month! I'll second that! I really needed a good laugh. Many thanks! So I'll thrice it - FWIW it indeed made it's way to the weekly python (thanks the python-url team), but deserves much more than that. I was so hilarious my son came out of it's room and even tried to read the post by himself - I just wasn't able to calm down and explain him what this was about. Grant, if we ever meet, remind me to pay you a couple beers. Cheers ! -- http://mail.python.org/mailman/listinfo/python-list