[Germany / München] Munich Python User Grou p Meeting this thursday!
Hi, sorry for choosing this forum for a regional announcement - just hoping to attract some local users who don't read the local mailing list. After a while of silence, there will be a meeting of the µPy (Münchner Python User Group) this thursday (June 24th). See here for further information: http://wiki.python.de/User_Group_M%C3%BCnchen Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: "isinstance" question
> >I want to test whether an object is an instance of any user-defined >> class. "isinstance" is less helpful than one would expect. >> >> >>> import types >> >>> class foo() : # define dummy class >> ... pass >> ... >> >>> x = foo() >> >>> >> >>> type(x) >> >> >>> >> >>> isinstance(x, types.ClassType) >> False >> >>> isinstance(x, types.InstanceType) >> True >> >>> foo >> >> >>> x >> <__main__.foo instance at 0x020080A8> >> >> So far, so good. x is an InstanceType. But let's try a >> class with a constructor: >> >> >>> class bar(object) : >> ...def __init__(self, val) : >> ... self.val = val >> ... >> >>> b = bar(100) >> >>> b >> <__main__.bar object at 0x01FF50D0> >> >>> isinstance(b, types.InstanceType) >> False >> >>> isinstance(b, types.ClassType) >> False >> >> bar >> >> >> well the same code on my side returns true when you run isinstance(b, types.InstanceType) even when the class has a constructor. Why is there a difference in the output when we are both using Cython 2.6 ?? (2.6.4 to be exact) Cheers Satish -- http://satisheerpini.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Unicode file names with ftplib and encodings.idna as a workaround?
En Tue, 22 Jun 2010 11:43:34 -0300, escribió: Python 2.6.5 (Win32): Is there a work around for ftplib's (and ftputil's) apparent inability to support Unicode file names? I'm thinking that I might be able to use the encodings.idna as a work around for this? According to RFC 2640, you should use UTF-8 instead. http://www.faqs.org/rfcs/rfc2640.html One downside is that processes on the server will also have to wrap directory access with a similar transformation. This wouldn't be too complicated for Python programs, but I'm not sure how convenient this would be for our PHP and shell scripters. (Just checked: There's a PEAR module for PHP4/5; oddly enough nothing pops up for .NET IDNA libraries) The server software must be able to convert from file system encoding to utf-8 and viceversa; check its configuration. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 6/22/10 10:39 PM, Dennis Lee Bieber wrote: > On Tue, 22 Jun 2010 15:55:51 -0700, Stephen Hansen > declaimed the following in > gmane.comp.python.general: > >> I second Forth. Learning and using that was -- slightly painful, but > > Just pick up any advanced HP programmable calculator... RPL is a > close substitute That's just a start. The reverse and stack-oriented nature of the language makes you have to start thinking in an interesting way, and sure, a RPL/stack-calculator can get that for you. But then going on and doing real programming with it, making your own words (functions), ... its fun. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange factory pattern
En Tue, 22 Jun 2010 23:33:55 -0300, Zac Burns escribió: In the threading module there are several code bits following this convention: ### def Class(*args, **kwargs): return _Class(*args, **kwargs) class _Class(... ### This is true for Event, RLock, and others. Why do this? It seems to violate the rule of least astonishment (isinstance(Event(), Event) raises an exception). I assume there must be some trade-off that the designer intended to achieve. So, what is that trade-off and when should I follow this in my code? Those classes are not meant to be subclassed (I don't know *why*). From original module documentation (1998): http://svn.python.org/view/python/trunk/Lib/threading_api.py?view=markup&pathrev=10430 "Lock() A factory function that returns a new primitive lock object... RLock() A factory function that returns..." Same for Condition, Semaphore, Event, but: "Thread A class that represents a thread of control -- subclassable." "Note that the classes marked as ''do not subclass'' are actually implemented as factory functions; classes are shown here as a way to structure the documentation only." And those classes have a big "*** DO NOT SUBCLASS THIS CLASS ***" message. The message never made into the documentation. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On 6/22/10 9:48 PM, John Bokma wrote: > alex23 writes: >> Given the current propensity for people to scrape web sites like >> Wikipedia and publish them on Amazon without the rights holders' >> consent, > > Can you explain were exactly it states that you can't print a book out > of wikipedia articles?: > http://wikimediafoundation.org/wiki/Terms_of_Use There's a difference between what is legal, and what is ethical. There are many, many people who re-use Wikipedia content in ethical ways and some even make money off of it. That's fine. Its when you package it up in such a way that the buyer doesn't realize what they're buying, that's where the problem comes-- and that's what is happening quite a lot these days. >> my initial impression was exactly the same as Stephen's. I >> don't think there's anything contractually binding about the product >> description that would guarantee the PSF even see any returns at all. >> But hey, as long as the page _looks_ and _sounds_ official, it must >> be, right? > > And if it looks like a scam, it must be, right? If it looks like a scam, some due-diligence and concern is appropriate. Especially when asked by someone like the OP who is not you, is not sophisticated in their knowledge of the community and the resources available to it. If it looks like a scam, take care personally. If it looks like a scam and someone is asking about it, you don't sit by and say nothing. That's inhuman. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: "isinstance" question
En Tue, 22 Jun 2010 23:45:07 -0300, John Nagle escribió: I want to test whether an object is an instance of any user-defined class. "isinstance" is less helpful than one would expect. >>> import types >>> class foo() : # define dummy class ... pass ... >>> x = foo() >>> >>> type(x) >>> >>> isinstance(x, types.ClassType) False >>> isinstance(x, types.InstanceType) True >>> foo >>> x <__main__.foo instance at 0x020080A8> So far, so good. x is an InstanceType. But let's try a class with a constructor: >>> class bar(object) : ...def __init__(self, val) : ... self.val = val ... >>> b = bar(100) >>> b <__main__.bar object at 0x01FF50D0> >>> isinstance(b, types.InstanceType) False >>> isinstance(b, types.ClassType) False >> bar Without a constructor, we get an "instance". With a constructor, we get an "object", one which is not an InstanceType. That's not the relevant difference. In the first case, you don't inherit from object; in the second one, you do. foo is a "classic" class (or "old-style" class); x is an instance of foo, its *type* is InstanceType, its *class* is foo. All instances of any other classic class have the same type (InstanceType). bar is a "new-style" class, b is an instance of bar, its type is bar, its class is bar. class and type are equivalent for new style classes; things are a lot more regular and predictable. In Python 3.x classic classes are gone. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Tue, Jun 22, 2010 at 5:58 PM, Josef Tupag wrote: > I've been programming (when I do program) mainly in Perl for the last 10 > years or so. But I've been itching to learn a new language for a while now, > and the two near the top of the list are Ruby and Python. > > I figure that Ruby would be easy to learn because of its similarity to Perl > (I'm told). But I also figure that Python would be easy to learn because of > its simplicity. And when it comes to webby stuff, I can use Rails with Ruby > and Django with Python. I think it does not matter much. It matters much more that you know one of them really well rather than both of them so so. There are some stuff in python without any equivalent in ruby AFAIK, things like numpy/scipy. I am sure the contrary is true as well, but I don't enough about ruby to have an informed opinion. cheers, David -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
alex23 writes: > John Bokma wrote: >> Now let's hope that your asshat behaviour doesn't stop companies like >> this to continue to print those books. I have considered to buy the >> complete set a few times. And I hope you're not calling me naive... > > Given the current propensity for people to scrape web sites like > Wikipedia and publish them on Amazon without the rights holders' > consent, Can you explain were exactly it states that you can't print a book out of wikipedia articles?: http://wikimediafoundation.org/wiki/Terms_of_Use > my initial impression was exactly the same as Stephen's. I > don't think there's anything contractually binding about the product > description that would guarantee the PSF even see any returns at all. > But hey, as long as the page _looks_ and _sounds_ official, it must > be, right? And if it looks like a scam, it must be, right? > Let's hope that _your_ asshat behaviour isn't responsible for people > being conned and ripped off. Yeah, and let's hope that your asshat behaviour doesn't stop this publisher from printing material that people like me actually want to buy. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Stephen Hansen writes: > I *have* seen people burned by confusion over situations *extremely* > similar to this; But is it? You didn't even ask yourself that question. > If being concerned about fellow Python-folks possibly getting ripped off > makes me an asshat, so be it. Go y'know-what yourself. If this publisher is legimate you might very well be denying people -- like I said I am interested -- from getting a print-out in the future just because /you/ cried wolf and called them scammers. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V'comp.language.python.brood of vipers! Look! I got it, Gus! I got it! Look: P= /V:P == 2P*V because fist '/V' is actually '/' div
I got it, Gus! I got it! Look: P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because because fist '/ V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V'fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V because fist '/V' is actually '/' divided by 'V' P= /V:P == 2P*V -- http://mail.python.org/mailman/listinfo/python-list
Re: "isinstance" question
On 6/22/2010 8:13 PM, Ben Finney wrote: John Nagle writes: I want to test whether an object is an instance of any user-defined class. "isinstance" is less helpful than one would expect. Right. The type hierarchy is now unified; there's essentially no difference in later Python versions between user-defined types and built-in types. OK, now that I know that, there's no problem. I'n doing something that involves program analysis through introspection. More on this later. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Jew JUDGE shows off JEW POWER by BULLYING and BLACKMAILING a BLACK PRESIDENT OBAMA
Jew Judges NEVER came out against the CRIMES of BUSH and CHENEY and LARRYS I L V E RS T E I N - The main player in 911 Jews are coming out from the directions of Corporations, Mafias, Legislators, and now Judge to SUBVERT the UNITED STATES. Please listen to the Speech of Mr Benjamin H Freedman on http://iamthewitness.com to see how they BLACKMAILED President WOODROW WILSON to INSTALL a Jew Judge BRANDEIS in the SUPREME COURT - the FIRST one http://abcnews.go.com/Politics/gulf-oil-spill-disaster-judge-overrule... Judge Drills Hole in Deepwater Ban; Obama Promises Immediate Appeal Judge: Drilling Moratorium 'Cannot Justify' Effects on Local Economy 123 comments By ARIANE de VOGUE and JAKE TAPPER WASHINGTON, June 22, 2010 A federal judge ruled today that the Interior Department had acted "arbitrarily" when it issued a six-month moratorium on all pending, current or approved drilling plans for new deepwater wells in the Gulf of Mexico and Pacific Ocean and agreed to lift the ban. Scientists believe oil is depleting water of oxygen, driving predators to shore. Judge Martin L.C. Feldman granted a preliminary injunction to Hornbeck Offshore Services to lift the moratorium, saying that the government "failed to cogently reflect the decision to issue a blanket, generic, indeed punitive, moratorium." The Administrative Procedure Act authorizes judges to review the actions of executive branch agencies only if the action is found to be "arbitrary, capricious, and abuse of discretion, or not otherwise in accordance with the law." Feldman said a report by Secretary of the Interior Ken Salazar calling for the moratorium went too far and that he was "unable to divine or fathom a relationship between the findings and the immense scope of the moratorium." Recent disclosure documents indicate that Feldman, who was appointed to the bench by President Ronald Reagan, has had financial holdings in energy companies. The Department of Justice said it would immediately appeal the decision. On Jun 22, 2:38 pm, nanothermite911fbibustards - Hide quoted text - - Show quoted text - wrote: > The FASCINATING Secret Relationship Between PROFLIGATE WHITES and > MISLEADER JEWS > A fascinating relationship has existed between the PROFLIGATE WHITES > of the European continent and the MISLEADING and MANIPULATING JEWS > for more than a thousand years. > The understanding of the world history can never commence without a > focus on this historical point of view. > We will slowly slowly reveal parts of this comprehensive treatise. -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Jun 22, 9:31 pm, MRAB wrote: > [snip] > Napoleon once said "Never interrupt your enemy when he is making a > mistake."! :-) And how exactly does your example express itself in a more "syntactically-correct" "linear-flow" than the two code snippets i provided earlier, hmmm? PS: Oh yes i do know about generators and *even* list comprehensions. They are some of my favorite Python syntactic sugars. But heck there are so many tasty sugars in Python i guess the only thing a Python noob should really worry about is premature tooth decay! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange factory pattern
This looks like a public class exposing an implementation private class.Jun 22, 2010 10:39:05 PM, zac...@gmail.com wrote:In the threading module there are several code bits following this convention:###def Class(*args, **kwargs): return _Class(*args, **kwargs)class _Class(...###This is true for Event, RLock, and others. Why do this? It seems to violate the rule of least astonishment (isinstance(Event(), Event) raises an exception). I assume there must be some trade-off that the designer intended to achieve. So, what is that trade-off and when should I follow this in my code? --Zachary Burns(407)590-4814Aim - Zac256FLProduction EngineerZindagi Games -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: "isinstance" question
John Nagle writes: > I want to test whether an object is an instance of any user-defined > class. "isinstance" is less helpful than one would expect. Right. The type hierarchy is now unified; there's essentially no difference in later Python versions between user-defined types and built-in types. > So that's useless. For what purpose? > I have to be missing something obvious here. Maybe if we know what you're trying to do, we can suggest a better way. -- \“Human reason is snatching everything to itself, leaving | `\ nothing for faith.” —Saint Bernard, 1090–1153 | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
"isinstance" question
I want to test whether an object is an instance of any user-defined class. "isinstance" is less helpful than one would expect. >>> import types >>> class foo() : # define dummy class ... pass ... >>> x = foo() >>> >>> type(x) >>> >>> isinstance(x, types.ClassType) False >>> isinstance(x, types.InstanceType) True >>> foo >>> x <__main__.foo instance at 0x020080A8> So far, so good. x is an InstanceType. But let's try a class with a constructor: >>> class bar(object) : ...def __init__(self, val) : ... self.val = val ... >>> b = bar(100) >>> b <__main__.bar object at 0x01FF50D0> >>> isinstance(b, types.InstanceType) False >>> isinstance(b, types.ClassType) False >> bar Without a constructor, we get an "instance". With a constructor, we get an "object", one which is not an InstanceType. One might think that testing for types.ObjectType would help. But no, everything is an ObjectType: >>> isinstance(1, types.ObjectType) True >>> isinstance(None, types.ObjectType) True So that's useless. I have to be missing something obvious here. (CPython 2.6) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Strange factory pattern
In the threading module there are several code bits following this convention: ### def Class(*args, **kwargs): return _Class(*args, **kwargs) class _Class(... ### This is true for Event, RLock, and others. Why do this? It seems to violate the rule of least astonishment (isinstance(Event(), Event) raises an exception). I assume there must be some trade-off that the designer intended to achieve. So, what is that trade-off and when should I follow this in my code? -- Zachary Burns (407)590-4814 Aim - Zac256FL Production Engineer Zindagi Games -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
rantingrick wrote: On Jun 22, 7:56 pm, Gregory Ewing wrote: Thomas Jollans wrote: "Everything is an object" in both languages, or so they say. That's really a meaningless statement, because it depends on what you count as a "thing". But there is at least one thing that is an object in Python but not in Ruby. There are no stand-alone functions in Ruby, or callable objects in general. The only way to invoke code is to call a method of some object. Although i will admit the chaining of methods compared to the nesting of built in functions seems more linear-ly natural as in this case... RUBY: ['one', 'two', 'three'].map{|x| x.capitalize}.join(',') PYTHON ','.join(map(string.capitalize, ['one','two', 'three'])) ','.join(x.capitalize() for x in ['one','two', 'three']) ','.join(map(lambda x:x.title(), ['one','two', 'three'])) ...but i digress This can be confusing to someone coming from Python, because you can write what *look* deceptively like top-level function definitions. But they actually become methods of class Object, which is inherited by everything, and thus become implicitly available in any other method. Yes i call that "Ruby's Global Nightmare" and the folks over at SketchUp are learning day by day how this nightmare is going to undermine the Ruby API. Not only that, but since the API is for scripting it seems more natural to use Pythonic namespaces so you can write simple scripts very easily with one or two functions or complete packages spanning multiple modules without fear of name clashes (ever tried debugging that! 8^O). Of course you can create a module with Ruby (see next comment) [snip] Napoleon once said "Never interrupt your enemy when he is making a mistake."! :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Jun 22, 7:56 pm, Gregory Ewing wrote: > Thomas Jollans wrote: > > "Everything is an object" in both languages, or so they say. > > That's really a meaningless statement, because it depends on > what you count as a "thing". But there is at least one thing > that is an object in Python but not in Ruby. There are no > stand-alone functions in Ruby, or callable objects in general. > The only way to invoke code is to call a method of some > object. Although i will admit the chaining of methods compared to the nesting of built in functions seems more linear-ly natural as in this case... RUBY: ['one', 'two', 'three'].map{|x| x.capitalize}.join(',') PYTHON ','.join(map(string.capitalize, ['one','two', 'three'])) ','.join(map(lambda x:x.title(), ['one','two', 'three'])) ...but i digress > This can be confusing to someone coming from Python, because > you can write what *look* deceptively like top-level function > definitions. But they actually become methods of class Object, > which is inherited by everything, and thus become implicitly > available in any other method. Yes i call that "Ruby's Global Nightmare" and the folks over at SketchUp are learning day by day how this nightmare is going to undermine the Ruby API. Not only that, but since the API is for scripting it seems more natural to use Pythonic namespaces so you can write simple scripts very easily with one or two functions or complete packages spanning multiple modules without fear of name clashes (ever tried debugging that! 8^O). Of course you can create a module with Ruby (see next comment) > You can ignore the difference until you start trying to > use modules. Ruby has something it calls a "module", but it's > really more like a mixin class. If you try to think of it and > use it like a Python module, you'll get very confused and > frustrated and pull out large chunks of hair. At least I > did until I figured out what was really going on behind the > scenes. I always found it so odd that Ruby uses a special syntax for modules and not just copy the beautiful solution Python has pioneered. Matz, you already copied SOOO much, are you really trying to save face, because it's far too late for that my friend! > Having used both, I find the way that Python handles namespaces > to be greatly preferable. This may be partly because I'm more > familiar with it, but I think there are ways in which it's > objectively simpler and more useful for organising code. Python's way is better. There is no way to argue against it. Globals are bad, redundant end statements are bad, TIMTOWTDI is bad, module declarations are bad, not having docstrings is bad, allowing method calls without parenthesis is bad, using punctuation in identifiers is bad, bad keyword naming choices are bad, need i go on...? I would say check out Ruby if no more than just out of curiosity. You will find the map far more useful, and the linear chaining of methods more natural, but after that there really ain't much more to like! ...although i am sure the word "closure" is coming up *real* soon! -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the Emacs engine to Guile
Very EDUCATIONAL VIDEO http://www.youtube.com/watch?v=wzr_hRsSuGM&feature=related On Jun 22, 1:40 pm, Cecil Westerhof wrote: > Op dinsdag 22 jun 2010 19:28 CEST schreef Pascal J. Bourguignon: > > > > >>> this (while (re-search-forward ...)) loop modifies the line for each > >>> occurence of the regexp, replacing it with (substring substitute-str 0 > >>> match-length), which is a different replacement string in general. > > >> Why? I would think the replacement string is the same. (When using > >> single byte characters.) > > > With: > > > substitute-str = "Abcdef" ; initally > > start-match = 4 > > end-match = 12 > > match-length = 8 > > > substitute-str will become "AbcdefAbcdef", > > and (substring substitute-str 0 match-length) = "AbcdefAb" > > while (substring substitute-str start-match end-match) = "efAbcdef" > > I made a stupid mistake. It did not show because I only changed a > substring at the start of the line. Better code is at: > http://www.decebal.nl/guile/sources/substituteExpression.scm > > -- > Cecil Westerhof > Senior Software Engineer > LinkedIn:http://www.linkedin.com/in/cecilwesterhof -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On 6/22/10 1:09 PM, John Bokma wrote: > Now let's hope that your asshat behaviour doesn't stop companies like > this to continue to print those books. I have considered to buy the > complete set a few times. And I hope you're not calling me naive... Excuse me? I *have* seen people burned by confusion over situations *extremely* similar to this; there's quite a lot of content which is being scraped off of the internet and bundled into "books" and posted up on Amazon and the like. From both technical sources and things like Wikipedia. Yes. I read every single word available on the page. Yes. I read the claims that they are donating some proceeds to the PSF. Yes, I read that it (very poorly) identified what version of Python it was covering. Yes, it looks sort of above board visually. That doesn't mean it is: and considering I have *experience* dealing with things that look a lot like this that *are* scams, I wondered. So I spoke up and asked to see if anyone knew if it was really legit, after I found no evidence in a couple Google searches of any legitimate or even quasi-existing entity behind the products. If being concerned about fellow Python-folks possibly getting ripped off makes me an asshat, so be it. Go y'know-what yourself. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'open' is not a function according to inspect module?
Peng Yu wrote: > Hi, > > 'open' is not a function according to inspect module. But according to > help(open), it is a function. Is there something wrong with inspect > module? > > $ cat main.py > #!/usr/bin/env python > > import inspect > > def hello(): > print "Hello World!" > return > > print inspect.isfunction(str) > print inspect.isfunction(open) > print inspect.isfunction(hello) help (inspect.isfunction) gives Help on function isfunction in module inspect: isfunction(object) Return true if the object is a user-defined function. Mel. -- http://mail.python.org/mailman/listinfo/python-list
Re: TkInter bind() event is not firing event trigger
On Jun 22, 7:39 pm, MRAB wrote: > http://www.pythonware.com/library/tkinter/introduction/events-and-bin... > > it's ''. Yes and i vehemently hate these names! Just hideous if you ask me. @ Anthony Also be sure to use an "event name" for an event function/method and use the docstring to describe what the event will do. Do NOT use the method name to describe this like you have done. It's also a good idea to start event methods with "on". This is fairly well recognized as an event naming convention... onMotion() onButtonOneClick() onKeyPress() onEnter() onConfigure() ...etc ...Just ideas folks, just ideas! -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
John Bokma wrote: > Now let's hope that your asshat behaviour doesn't stop companies like > this to continue to print those books. I have considered to buy the > complete set a few times. And I hope you're not calling me naive... Given the current propensity for people to scrape web sites like Wikipedia and publish them on Amazon without the rights holders' consent, my initial impression was exactly the same as Stephen's. I don't think there's anything contractually binding about the product description that would guarantee the PSF even see any returns at all. But hey, as long as the page _looks_ and _sounds_ official, it must be, right? Let's hope that _your_ asshat behaviour isn't responsible for people being conned and ripped off. -- http://mail.python.org/mailman/listinfo/python-list
Re: TkInter bind() event is not firing event trigger
On Jun 22, 7:21 pm, Anthony Papillion wrote: > I've also removed the (event) parameter just in case and tried it and > it makes no difference. What am I doing wrong here? Well don't remove the event parameter because Tkinter will pass it every time since this is an EVENT! Here is some code to play with. Note: If using Python 3.x use lowercase Tkinter! #-- Start Code --# import Tkinter as tk from Tkconstants import * class MyListbox(tk.Listbox): def __init__(self, master, **kw): tk.Listbox.__init__(self, master, **kw) self.bind("", self.onButtonOneDoubleClick) self.bind("", self.onButtonThreeClick) def onButtonOneDoubleClick(self, event): lineno = self.nearest(event.y) print 'User double clicked line: %s' %(lineno) def onButtonThreeClick(self, event): lineno = self.nearest(event.y) self.activate(lineno) # # You make this next comand a bit smarter # and only clear the selection when user # clicks on a line this is not already selected # (well in multi line mode anyway), but i cannot # do all the work! ;) self.selection_clear(0, END) self.selection_set(lineno) print 'User right clicked line: %s' %(lineno) if __name__ == '__main__': app = tk.Tk() listbox = MyListbox(app, width=10, height=10, bg='white', selectmode=EXTENDED) for x in range(100): listbox.insert(END, x) listbox.pack(fill=BOTH, expand=1) app.mainloop() #-- End Code --# -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
Thomas Jollans wrote: "Everything is an object" in both languages, or so they say. That's really a meaningless statement, because it depends on what you count as a "thing". But there is at least one thing that is an object in Python but not in Ruby. There are no stand-alone functions in Ruby, or callable objects in general. The only way to invoke code is to call a method of some object. This can be confusing to someone coming from Python, because you can write what *look* deceptively like top-level function definitions. But they actually become methods of class Object, which is inherited by everything, and thus become implicitly available in any other method. You can ignore the difference until you start trying to use modules. Ruby has something it calls a "module", but it's really more like a mixin class. If you try to think of it and use it like a Python module, you'll get very confused and frustrated and pull out large chunks of hair. At least I did until I figured out what was really going on behind the scenes. Having used both, I find the way that Python handles namespaces to be greatly preferable. This may be partly because I'm more familiar with it, but I think there are ways in which it's objectively simpler and more useful for organising code. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: TkInter bind() event is not firing event trigger
Anthony Papillion wrote: So I want to execute some code when the user double clicks an item in a ListBox. The documentation says I should use the listbox.bind() method, specifying the Double-l event to detect the double left mouse button click. My code is this: gsItems = Listbox(root, width=76, height=30, selectmode="browse", yscroll=scrollBar.set) gsItems.bind('', openandDisplayFolder) gsItems.pack() So the first line configures the Listbox, second line SHOULD set up the event, and third line, of course, adds the Listbox to the UI. The problem is that the openandDisplayFolder function is never executed. The function is VERY simple for now while I learn the way to do it: def openandDisplayFolder(event): tkMessageBox.showinfo("Event Fired", "An item has been double clicked!") I've also removed the (event) parameter just in case and tried it and it makes no difference. What am I doing wrong here? According to: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm it's ''. -- http://mail.python.org/mailman/listinfo/python-list
TkInter bind() event is not firing event trigger
So I want to execute some code when the user double clicks an item in a ListBox. The documentation says I should use the listbox.bind() method, specifying the Double-l event to detect the double left mouse button click. My code is this: gsItems = Listbox(root, width=76, height=30, selectmode="browse", yscroll=scrollBar.set) gsItems.bind('', openandDisplayFolder) gsItems.pack() So the first line configures the Listbox, second line SHOULD set up the event, and third line, of course, adds the Listbox to the UI. The problem is that the openandDisplayFolder function is never executed. The function is VERY simple for now while I learn the way to do it: def openandDisplayFolder(event): tkMessageBox.showinfo("Event Fired", "An item has been double clicked!") I've also removed the (event) parameter just in case and tried it and it makes no difference. What am I doing wrong here? Thanks! Anthony -- http://mail.python.org/mailman/listinfo/python-list
Re: Uses of a deprecated module 'string'
On 6/22/10 4:53 PM, rantingrick wrote: > On Jun 22, 4:37 pm, Thomas Jollans wrote: >> Looks like `letters' has been renamed to `ascii_letters'. > > > ASCII rubutted: > Really it's more like "asc-bye-bye_letters". They keep shoving me > more and more under the carpet! And that big fat glory hog Unicode is > really stating to get on my nerves!" Just what the heck makes him *so* > special anyway with his "squiggly" lines and accent marks? It's like a > on-going pronunciation tutorial for cry'in out loud! Is the world > suddenly moving BACKWARDS! Are we counter evolving? Ooo, Ooo, look > everybody i got squiggly lines too! ~~~ > > ...read em and weep you fat @$$! You've already done this particularly offensive, unrealistic, culturally imperialistic and nonsensical rant. http://groups.google.com/group/comp.lang.python/browse_thread/thread/7dfa560c675b06b2/47ee7d03aa4c9b09 We really don't have to do it again. :) Everyone knows you don't like unicode, man. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 6/22/2010 4:09 PM rantingrick said... ...After reading these comments i reminisce back to a time when a good friend of this community "r" said basically the same things but was lynched for them.Hmm? Has the community changed? Or is it that these comments came from someone other than "r" that they go unpunished. Hmm, riddles in the dark...? Hmm, I don't remember the thread you're referring to, but when Matz launched Ruby and the volume of posts on c.l.py talking about ruby increased, we all wished him the best and voted to establish c.l.ruby. (OK, call it voted him off the island if you wish.) As I recall, compilation was the biggest missing piece that Matz wanted and my impression was that Ruby in the early days used much of what was then pythonesque. I always figured to take a closer look if/when python didn't run as quickly as I needed. Hasn't happened yet... Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Uses of a deprecated module 'string'
On Jun 22, 4:37 pm, Thomas Jollans wrote: > Looks like `letters' has been renamed to `ascii_letters'. ASCII rubutted: Really it's more like "asc-bye-bye_letters". They keep shoving me more and more under the carpet! And that big fat glory hog Unicode is really stating to get on my nerves!" Just what the heck makes him *so* special anyway with his "squiggly" lines and accent marks? It's like a on-going pronunciation tutorial for cry'in out loud! Is the world suddenly moving BACKWARDS! Are we counter evolving? Ooo, Ooo, look everybody i got squiggly lines too! ~~~ ...read em and weep you fat @$$! -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 06/23/2010 01:30 AM, Stephen Hansen wrote: > On 6/22/10 4:09 PM, rantingrick wrote: >> ...After reading these comments i reminisce back to a time when a good >> friend of this community "r" said basically the same things but was >> lynched for them. Hmm? Has the community changed? Or is it that these >> comments came from someone other than "r" that they go unpunished. >> Hmm, riddles in the dark...? > > If I remember the thread correctly, it was a part of a Call to Arms to > march out and Wage War against Ruby and Defeat It before it Defeated Us. > > Or something to that nature. If I'm remembering a different thread then > you are, well -- there /was/ a thread like that. > > And that's terribly exhausting. See, we all (wait, let me get up on a > stool and speak for The Community) may quite like Python, may quite not > like Ruby, and may find usage of Ruby to be perhaps a sign of some form > of mental illness (okay, no, not really), but we're also quite content > and happy for people to use Ruby if they want to. And we're oddly not > threatened by its popularity. > > Good for you, Rubyers. I applaud your success and wish you more of it. Hear, hear! -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 6/22/10 4:09 PM, rantingrick wrote: > ...After reading these comments i reminisce back to a time when a good > friend of this community "r" said basically the same things but was > lynched for them. Hmm? Has the community changed? Or is it that these > comments came from someone other than "r" that they go unpunished. > Hmm, riddles in the dark...? If I remember the thread correctly, it was a part of a Call to Arms to march out and Wage War against Ruby and Defeat It before it Defeated Us. Or something to that nature. If I'm remembering a different thread then you are, well -- there /was/ a thread like that. And that's terribly exhausting. See, we all (wait, let me get up on a stool and speak for The Community) may quite like Python, may quite not like Ruby, and may find usage of Ruby to be perhaps a sign of some form of mental illness (okay, no, not really), but we're also quite content and happy for people to use Ruby if they want to. And we're oddly not threatened by its popularity. Good for you, Rubyers. I applaud your success and wish you more of it. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Wed, 23 Jun 2010 00:09:15 +0100, rantingrick wrote: ...After reading these comments i reminisce back to a time when a good friend of this community "r" said basically the same things but was lynched for them. Hmm? Has the community changed? Or is it that these comments came from someone other than "r" that they go unpunished. Hmm, riddles in the dark...? I don't recall seeing "r" say basically the same things. Of course, "r" being one of the four people introduced to my killfile may have had an effect on that. Strangely, I do recall a number of occasions on which "r" blathered on in a manner that could be mistaken for those things if one didn't actually read what was written. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
Quotes for this thread... On Jun 22, 4:20 am, James Mills wrote: > I find Ruby (compared to Python) to be a syntactical rip-off and > a bad one at that. Some things in Ruby aren't nearly as simple or > as concise as you would find in Python. --- On Jun 22, 4:29 am, Jean-Michel Pichavant wrote: > This is a python list, fully dedicated to our dutch semi God. So how can > you even immagine that someone here will suggest you to go for rub... > sorry I can't prononce this blasphemous name. --- On Jun 22, 5:02 am, lkcl wrote: > so whilst ruby may be dynamic and compact, it's not beautiful, > readable or obvious as to what's going on. i look at a python > program, and it uses actual... like... y'know... words that make > sense. i look at a ruby program and i simply cannot say the same, not > even if you put code which is supposed to do exactly the same job. --- On Jun 22, 5:02 am, Thomas Jollans wrote: > Ruby has a bunch of strange syntactical zits: I mean, @instancevariable, > @@classvariable, $GLOBAL, and whatnot?? I don't like them, I find > Python's syntax cleaner, easier on the eye, and the finger. > > To get really religious, and Ruby violates quite a few of these,>>> import > this > > The Zen of Python, by Tim Peters .. > Ruby is almost only used on Rails and in Japan. We're much more > universal, and more friendly ! --- On Jun 22, 9:49 am, "D'Arcy J.M. Cain" wrote: > Python is executible pseudocode. --- ...After reading these comments i reminisce back to a time when a good friend of this community "r" said basically the same things but was lynched for them. Hmm? Has the community changed? Or is it that these comments came from someone other than "r" that they go unpunished. Hmm, riddles in the dark...? Josef, As for me i would suggest Python (of course). Ruby has a very very few niceties but all in all Python wins hands down. However if your a past perl obfuscation nut, or laborious lisper, just skip strait over to Ruby right away because you ain't gonna like Python's clean syntax! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
geremy condra writes: > On Tue, Jun 22, 2010 at 1:58 AM, Josef Tupag wrote: >> I've been programming (when I do program) mainly in Perl for the last 10 >> years or so. But I've been itching to learn a new language for a while now, >> and the two near the top of the list are Ruby and Python. > > My advice is to learn something *really different* while you've got the itch. > Work with Forth or (my favorite non-Python language) Haskell for six > months and then come back to things like Python or Ruby- IME it helps > to highlight where there are actual differences between languages and > where there's just minor variations in approach. Good advice. While I have been exposed to functional programming 16+ years ago, I am reading up on Haskell, and learing a bit of Lisp (Emacs Lisp). -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
Re: Where is the help function defined?
On 10-06-21 10:57 AM, Emile van Sebille wrote: On 6/21/2010 10:17 AM Peng Yu said... help(help) gives me the following explanation. I then looked at pydoc site. But I don't see an entry on help(). How to figure out where help() (or a function in general) is defined? ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> dir(help) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> help.__module__ 'site' >>> import site >>> dir (site) ['_Helper', '_Printer', '__builtin__', '__builtins__', '__doc__', '__file__', '__name__', '_init_pathinfo', '_test', 'abs__file__', 'addbuilddir', 'addpackage', 'addsitedir', 'addsitepackages', 'aliasmbcs', 'execsitecustomize', 'main', 'makepath', 'os', 'removedup paths', 'setBEGINLIBPATH', 'setcopyright', 'setencoding', 'sethelper', 'setquit', 'sys'] >>> site.__file__ 'C:\\Python24\\lib\\site.pyc' >>> "site.py" (at least in the Python trunk) has this: def sethelper(): __builtin__.help = _Helper() Trent -- Trent Mick http://www.activestate.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 6/22/10 3:35 PM, geremy condra wrote: > On Tue, Jun 22, 2010 at 1:58 AM, Josef Tupag wrote: >> I've been programming (when I do program) mainly in Perl for the last 10 >> years or so. But I've been itching to learn a new language for a while now, >> and the two near the top of the list are Ruby and Python. > > My advice is to learn something *really different* while you've got the itch. > Work with Forth or (my favorite non-Python language) Haskell for six > months and then come back to things like Python or Ruby- IME it helps > to highlight where there are actual differences between languages and > where there's just minor variations in approach. I second Forth. Learning and using that was -- slightly painful, but really invigorating. And I also second learning a functional language (though I don't know if I'd inflict Haskell on anyone). It bends your brain and makes you think in a different way. The mental toolbox expands. New possibilities suddenly occur to you down the road when you return to Python (or Perl, even) for some sane, regular sort of coding. Learning new languages = good. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Tue, Jun 22, 2010 at 1:58 AM, Josef Tupag wrote: > I've been programming (when I do program) mainly in Perl for the last 10 > years or so. But I've been itching to learn a new language for a while now, > and the two near the top of the list are Ruby and Python. My advice is to learn something *really different* while you've got the itch. Work with Forth or (my favorite non-Python language) Haskell for six months and then come back to things like Python or Ruby- IME it helps to highlight where there are actual differences between languages and where there's just minor variations in approach. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: From Dict to Classes yes or no and how
On Tue, 22 Jun 2010 13:56:43 +0200 (CEST) "Jerry Rocteur" wrote: > As part of learning Python, I'm also learning OOP! That is why I want > to know if this is doable using classes. Everything[1] is doable using classes. The question is: Do you *need* to do it with classes? If your problem is best described as "mappings from keys to values", then you have already implemented a fine solution with dicts. Think of "objects" as "things with behavior". Basically, if you have many top-level data items (such as dicts, lists, whatever), and many functions operating on these, grouping these data items with the appropriate functions within classes might clean up your code conceptually (It might! I didn't say it will!). If you can categorize these data/function groups into a hierarchical structure of ever more specialized functionality, then classes and inheritance are pretty much your friends by default. So the takeaway is this: Will you (and possibly others) be able to understand my code better by organizing it in this-or-that structure? If so, use this-or-that structure, if not, then don't. And to even more evade answering your specific question: If you have the time, go and rewrite your code with classes. That'll teach you more than theorizing about *maybe doing* it here. /W [1] For sufficiently small values of "everything". -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Tue, 22 Jun 2010 10:49:49 -0400 "D'Arcy J.M. Cain" wrote: > Python is executible pseudocode. > I don't know about you, but if I didn't know this to be praise, it'd sound like an insult to me. As in "Timecube is expendable pseudoscience". Phrases like "Your mother [has property x]" have the same effect on me, no matter how flattering ascribing [property x] to someone might actually be. "Your mother is executable pseudocode." See? No, I don't have a lot to do right now, why do you ask? ;) /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Tue, 22 Jun 2010 19:38:43 +1000 James Mills wrote: > When I came across Rub* I found it to be just a rip-off of Python (in > some respects) and couldn't understand how it became popular so > quickly :) You answered your own question: It's a rip-off of Python. On a more serious note, though, I think Ruby is as much a rip-off of Python as Python is a rip-off of Smalltalk or Modula. I think one should be careful with such statements. Then again, this is a Python group, so you're relatively safe, I guess. ;) /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Uses of a deprecated module 'string'
On 06/22/2010 11:11 PM, Steven Howe wrote: > Hi, I'm trying to import 'letters' from the string module. > I get the following message: > > Uses of a deprecated module 'string' > > I realize the functionality of 'string' is now in the _builtin_. But are > the > constants. If so, what are they called. I tried 'letters', but got: > > NameError: name 'letters' is not defined > >>> import string >>> from pprint import pprint >>> pprint(dir(string)) ['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 'punctuation', 'whitespace'] >>> Looks like `letters' has been renamed to `ascii_letters'. -- http://mail.python.org/mailman/listinfo/python-list
Re: mysql query results to web page
On Jun 22, 4:50 pm, Greg wrote: > I'd like to query my local MySQL db and send the results to a locally > served web page. I've poked around and found complex examples using > web2py and pylons What's best for beginners? Can somebody lay out > the basic steps for me? > > thanks, > > Greg You need to use some sort of web server and some sort of interface to a web server. Most web servers support the CGI interface. Here is an example query using a web server CGI interface and the WSGI/CGI translator. This is one of many options, but it has the advantage that you can move to a higher performance approach later if you need to without changing code. === cut, beginning of file #!/Library/Frameworks/Python.framework/Versions/Current/bin/python import sys import wsgiref.handlers import MySQLdb def application(env, start_response): connection = MySQLdb.connect(host="localhost", user="me", passwd="xyz", db="mydatabase") cursor = connection.cursor() cursor.execute("select * from MY_TABLE") start_response("200 OK", [('Content-Type', 'text/html')]) for x in cursor.fetchall(): yield str(x) yield "\n" # serve a CGI request using the application wsgiref.handlers.CGIHandler().run(application) === end of file Here is a link to the running example I just tested: http://aaron.oirt.rutgers.edu/cgi-bin/mysql.cgi The first thing you should try is getting the "hello world" CGI script running before adding the MySQL query. I had to make the CGI script executable and have it point to my Python installation in the first line. Please see http://docs.python.org/library/cgi.html for a discussion of CGI scripting. I also had to mess with some directory permissions because my MySQLdb on my Mac in inside a Python Egg... to get around these sorts of problems you may have to look at your server error log. Also please see the WHIFF quickstart for a discussion of setting up a WSGI/WHIFF based CGI script. Good luck! -- Aaron Watters === % man less less is more. -- http://mail.python.org/mailman/listinfo/python-list
Re: Uses of a deprecated module 'string'
On Wed, Jun 23, 2010 at 7:11 AM, Steven Howe wrote: > Hi, I'm trying to import 'letters' from the string module. > I get the following message: > > Uses of a deprecated module 'string' > > I realize the functionality of 'string' is now in the _builtin_. But are the > constants. If so, what are they called. I tried 'letters', but got: > > NameError: name 'letters' is not defined > > Thanks for any help. What python version ? In python 3.1.x the "string" module is just a collection of string constants which obviously still exists. I believe it's the use of said "functions" from the old "string" module that are deprecated. cheers James -- http://mail.python.org/mailman/listinfo/python-list
Uses of a deprecated module 'string'
Hi, I'm trying to import 'letters' from the string module. I get the following message: Uses of a deprecated module 'string' I realize the functionality of 'string' is now in the _builtin_. But are the constants. If so, what are they called. I tried 'letters', but got: NameError: name 'letters' is not defined Thanks for any help. Steven Howe -- http://mail.python.org/mailman/listinfo/python-list
mysql query results to web page
I'd like to query my local MySQL db and send the results to a locally served web page. I've poked around and found complex examples using web2py and pylons What's best for beginners? Can somebody lay out the basic steps for me? thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Information about PHP + MySQL E-book
On Wed, Jun 23, 2010 at 6:10 AM, John Bokma wrote: > My guess is that this is just spam for a blog. Please don't copy > spamvertized URLs. My bad :/ -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Information about PHP + MySQL E-book
James Mills writes: > On Wed, Jun 23, 2010 at 2:15 AM, J3p wrote: >> Hi, I need some Information from you. Someone told me to buy E-book >> about PHP + MySQL in >> http:// >> Does anyone have experience about this? > > This has nothing whatsoever to do with Python > except that Python has MySQL drivers. My guess is that this is just spam for a blog. Please don't copy spamvertized URLs. -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Stephen Hansen writes: > On 6/22/10 6:48 AM, lallous wrote: >> Hello, >> >> I wonder if anyone read this: >> http://www.amazon.com/PYTHON-2-6-Extending-Embedding-documentation/dp/1441419608/ref=sr_1_7?ie=UTF8&s=books&qid=1277214352&sr=1-7 >> or this: >> http://www.amazon.com/Python-Extending-Embedding-Documentation-Manual/dp/1441412743/ref=pd_sim_b_3 >> >> Are these books just a print out of the manual that comes w/ Python >> distribution or they are written in a different way and more organized >> way? > > Uhh, that looks like a scam. Uh, it looks like you're making a lot of drama and innuendo where none is required. The OP links show books which have *clearly* the version in the title. As for the 3 version, that's not different from the other books on 3 in my experience. For example the excellent (IMO) "Programming in Python 3: A Complete Introduction to the Python Language" (30 USD) just came out with a 2nd edition a month or 2 after I had bought the first. So if this is a scam how is publishing an "updated" version shortly after the first version, each book about 30 USD? (Mind, I am not complaining, I am happy that Mark decided to make an updated version available, I own both editions). > Someone scraped the Python docs and bundled > it up as a "book" to sell to naive people for outrageous prices; and put > Guido's name on it to give it legitimacy. > > It also bundles up the *tutorial* for $22. There's a number of very > good, large Python books which sell for that. Surely Fred L Drake and > Gudio aren't really involved in this. I wonder if they even know about > it. At 304 pages I think 22 USD is a reasonable price. Again, you make a lot of drama where there is none. And the product description makes /very clear/ what it's about: This is a printed edition of the official Python documentation from the PYTHON 2.6.1 distribution. For each copy sold $1 will be donated to the PYTHON SOFTWARE FOUNDATION by the publisher. Now let's hope that your asshat behaviour doesn't stop companies like this to continue to print those books. I have considered to buy the complete set a few times. And I hope you're not calling me naive... -- John Bokma j3b Hacking & Hiking in Mexico - http://johnbokma.com/ http://castleamber.com/ - Perl & Python Development -- http://mail.python.org/mailman/listinfo/python-list
conceptual model diagram builder
Hi folks. I design a lot of conceptual models and I usually do it on paper or on a white board. I sometimes need to send an image of a conceptual model (not a photo) and I really don't know of a good tool which works the way I'd like to make images of conceptual models. Particularly I'd like the layout to be automatic. So I built a conceptual diagram model builder in Python using WHIFF and released it as a WHIFF demo. It does auto-layout and also allows you to snapshot the model as a JSON structure. Here it is: http://whiffdoc.appspot.com/tests/schema/diagram# I will certainly continue to fiddle with it but I'm pretty pleased with how it works now, so I wanted to share it. More info: * Implemented in WHIFF: whiff.sourceforge.net. * Drawn using HTML 5 2D canvas feature http://dev.w3.org/html5/2dcontext/. * Interactive elements courtesy of jQueryUI http://jqueryui.com/. * Dynamic server/page interactions use AJAX technology. * Data encoding uses JSON http://www.json.org/. * Data modeling conventions adapted from Analysis Patterns: Reusable Object Models by Martin Fowler. * Distributed in the whiff test directory. Browse the source at this link. http://code.google.com/p/whiff/source/browse/#hg/trunk/test/root/schema Let me know what you think. If you want to get the source you will have to clone the google code mercurial archive (it isn't part of the whiff release yet). -- Aaron Watters === This one goes to 11. -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Jun 22)
QOTW: "It's hard to overestimate the variance you'll see when you start asking your users for information." - Cody Powell http://www.codypowell.com/taods/2010/01/production-aint-pretty-a-case-for-excessive-application-logging.html The second Release Candidate of Python 2.7 is available for testing: http://comments.gmane.org/gmane.comp.python.devel/113970 Do you want to help Python development? Easy: just review bug tracker items: http://groups.google.com/group/comp.lang.python/t/e9f27bae8afbc80b/ Why can I not catch the same exception I'm raising? http://groups.google.com/group/comp.lang.python/t/3ff0e94eaaad430e/ The Python way: polymorphism and duck typing explained to a visitor coming from C++: http://groups.google.com/group/comp.lang.python/t/bb154ff6a920087e/ A strange issue at interpreter shutdown involving generators: http://groups.google.com/group/comp.lang.python/t/b2aa1fa16b34a7d4/ Unfortunately, unicode handling in exception messages (in 2.x) is far from perfect: http://groups.google.com/group/comp.lang.python/t/f3d0a1f554583eac/ Generators and lazy evaluation of free variables: http://groups.google.com/group/comp.lang.python/t/bf3e25d9ee09c449/ Lots of people recommend against using CGI for developing web applications - so, what alternatives are better? http://groups.google.com/group/comp.lang.python/t/829d0338a399fb9b/ Mixing assembler and python - when does it make sense, if any? http://groups.google.com/group/comp.lang.python/t/237a9ef9fa862a03/ Is it possible to override __setattr__ for a module? http://groups.google.com/group/comp.lang.python/t/d87e775920978683/ Currently, the ssl module only ensures that you can have an encrypted talk with your attacker :-) http://groups.google.com/group/comp.lang.python/t/c16a4cea469d346a/ Everyone showing his favorite way of computing 1**2+2**2+3**2-4**2-5**2+6**2+7**2+8**2-9**2-10**2+...-2010**2: http://groups.google.com/group/comp.lang.python/t/b2b82ed474d9f165/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date nullege is an interesting search Web application, with the intelligence to distinguish between Python code and comments. It provides what appear to be relevant results, and demands neither Java nor CSS be enabled: http://www.nullege.com Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the wor
Re: print line number and source filename
On 6/22/10 10:26 AM, Shashwat Anand wrote: > begin - > import logging > logging.basicConfig(level=logging.DEBUG,format="%(asctime)s" > "%(levelname)-5.5s [%(name)s %(module)s:%(funcName)s:%(lineno)d]" > "%(message)s") > > def run(): >x = 5 >logging.debug("X = %d" % x) > > run() > - end - > > You can probably use string default concatenation feature of python. > Anyway, am just nitpicking. Loved your example, as I was unaware of > logging module. As a sort of personal policy, I never use string concatenation. I do not advocate this position or advise that others should follow it, but in my experience-- for me-- it does not scale. I find I often want to go back and modify or enhance an output with new data, and string concatenation ends up becoming cumbersome after awhile, and so I always use format strings so I don't have to rewrite the line to convert from + to % later. (And in a couple years when I can migrate to Py3, I'll start using .format()) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'open' is not a function according to inspect module?
On 6/22/2010 11:42 AM, Peng Yu wrote: 'open' is not a function according to inspect module. If you want to *learn* Python, perhaps you should ignore the inspect module. It is for advanced purposes. I only used it a couple of times in 13 years. If you want to know what something literally is, you can usually just print it. In 3.1 >>> list >>> list.append >>> [].append >>> open >>> def f(): def __init__(self): pass >>> f >>> f.__init__ These are all 'callables' , meaning that you can call them by appending '(args)'. For many purposes, the different classes of callables are not important. Some of the details above were different in 2.x. Sometimes you need to call type(ob) instead, if its string representation is not informative. >>> help Type help() for interactive help, or help(object) for help about object. >>> type(help) Help is a builtin instance of site._Helper, which has a custom .__str__ method that prints the instruction instead of the usual sort of description. Since we can call 'help', we may presume site._Helper has a .__call__ method that makes its instances callable. Let us check: >>> dir(type(help)) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] dir() is another tool that I use all the time. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
*** Proof - JEWS - the Enslavers of the Blacks ***
http://www.youtube.com/watch?v=kTn-w3xjprg&feature=related watch this Israel's deadly attack on USS Liberty emerges from the past http://www.youtube.com/watch?v=f98jxoUUrzg&feature=fvsr http://www.youtube.com/watch?v=52fm6zAHa-w http://www.youtube.com/watch?v=qL9hGmfGTXc The Secret Relationship Between Blacks & Jews http://www.youtube.com/watch?v=umdyu6hiEwE The crusaders were jews. After the spanish inquisition they became overtly christian but crypto jews. Only they did, not the moslims. Then they took the leadership by promoting profligate and impious whites. They were the knight templars. In jerusalem they murdered christians and moslems. The Armenian genocide was done by jews. The crypto jews of the turkish caliphate (read up on Shabtai Zvi) took control. Mustafa Kemal the drunkard was a crypto jew. Turkish empire controlled jerusalem and it was of importance to them. In Britian, another crypto jew benjamin disraeli rose to become a PM of the country. Rothshilds and he financed the profligate white, the murderous and racist, CECIL RHODES who started APARTHEID most likely at the tutoring of Rothschild. >From Amsterdam, the jews lured the dutch to loot and colonize indonesia. Then they made these same countries fight each other with chemical weapons, inventing it for them during WW1 and then atom bomb during WW2. They had decided to kill their own religious and pious ones by financing hitler. they channelized hitler's hatred to the jews because his grandmother Schickelgruber was raped by a roman polansky bankster by the name of Frankenberger where she worked. Anyone remember the FAIT ACCOMPALI of Wooody Allen with the daughter of the Korean he was dating ? Always, they have lured the white to crimes and immorality by cooking rationalizations. the secret relationship between blacks and jews.pdf ChristoFER COLUMBUS was a Jew http://mailstar.net/secret.html === http://www.blacksandjews.com/JewsBlackHolocaust.html Jews and the Black Holocaust - What are the Issues? Blacks and Jews have been involved in a re-evaluation of their current and historical relationship. Events of the past several years have raised both tensions and the level of rhetoric coming from all sides. The Secret Relationship Between Blacks and Jews is a historical accounting of the part of the relationship that has been ignored by both Blacks and Jews. Most people are not even aware of the extensive record of encounters between the two groups prior to the 20th century. The Honorable Louis Farrakhan referred to this well-documented history in 1984 and was immediately labeled an "anti-Semite." Merely questioning the belief that Jews were co-sufferers in the Black slave experience draws angry rebukes from Jews of all stripes. The book in question presents indisputable historical data from census records, wills, Jewish historians and scholars, rabbinical sermons, port records, court records, runaway slave notices, slave sale advertisements, etc., which forces all sides to grapple with the long- held mythology that Black people always found a friend in the Jews. Some Jews and their dutiful negros have hired the services of Dr. Harold Brackman of the Simon Wiesenthal Center in an effort to preserve the comfortable mythology which has obscured the actual historical record. But unbeknownst to them, Dr. Brackman's 1977 unpublished Ph.D. dissertation, entitled The Ebb and Flow of Conflict, goes far beyond The Secret Relationship in its claims of Jewish conspiracy in the Biblical origin of White supremacy. He clearly states that Jewish Talmudic scholars invented the Hamitic Myth which, through the story of Noah, everlastingly assigned to the African the role of slave and divinely cursed servant of White people. According to Dr. Tony Martin's book, The Jewish Onslaught, the Jewish invention of the Hamitic Myth "provided the moral pretext upon which the entire trade grew and flourished." "There is no denying," said Brackman of the story of Noah, "that the Babylonian Talmud was the first source to read a Negrophobic content into the episode..." Brackman pointed out further that two third century Jewish "Sages" provided homosexual embellishments for the Biblical story as well. This "curse" was the absolute basis for the Europeans' choice of dark- skinned Africans for chattel slavery. Many denominations of Christianity, Islam and Judaism believe it and teach it to this very moment! Southern plantation owners attacked the Abolitionists with it; its teaching was the foundation of the slaves' permitted religion; Black inferiority is based on it; the Ku Klux Klan relies on it; even the Mormons officially taught it until 1978. When the Jews invented it and promoted it to the world they sentenced the Black Race to a holocaust the likes of which no people have ever suffered. "Hate teaching" will forever be defined by this wicked belief system brought to us in the Jewish Holy Talmud via Harold Brackman.
Re: Book review / advise
On 6/22/10 11:01 AM, Terry Reedy wrote: > On 6/22/2010 11:49 AM, Stephen Hansen wrote: >> Uhh, that looks like a scam. Someone scraped the Python docs and bundled >> it up as a "book" to sell to naive people for outrageous prices; > > Various people have asked on this list for printed versions of the docs. > PSF has never provided them. As I once read the license, it allows > anyone to do so, and charge whatever price. I considered doing this once > myself, but they seem to have beaten me to it ... Its not a question of if it is illegal, or even a copyright violation. You can take Python itself and bundle it and sell it if you want. "Permitted" doesn't mean its not still a scam-- that unsuspecting people who don't quite know the difference aren't going to see this and buy it instead of one of the real books out there (with real editing and administrative costs) that'd be much better use of it. Because this book is by Guido himself. > Except that there is one possible scam aspect -- there is no version > listed on the cover. A reviewer of the ref manual said his was for > 3.0.1. Selling that now as the Python 3 Ref Manual (there is no such > thing) *is* a scam. There is no indication that it has been undated. If > I were to do this, I would be honest in this respect and publish the > "Python 3.1.2 Refence Manual", etc. Much more work to redo, better > service. I would publish through print-on-demand so there is no inventory. You give them far more credit then I think they deserve; they're going and taking: http://docs.python.org/py3k/tutorial/index.html And bundling that little section up together as a "book" and charging over $22 for those hundred odd pages. The whole manual would end up costing you $60+ -- with another $50 or so for the 'extending' then 'embedding' and 'distribution' "book" they are making. Its like those services which go and scrape up a few vaguely-related Wikipedia articles and package them as a "book". > Given editorial and administrative costs, printing cost, bookseller > markup, and "For each copy sold $1 will be donated to the Python > Software Foundation by the publisher", the price is not unreasonable. > The fixed costs have to be amortized over an unknown and probably not > large sales base. The standard author royalty might be $2, so they are > not saving that much on that score. We have dramatically different definitions of "reasonable" price, then. >> and put Guido's name on it to give it legitimacy. > > Guido and Fred Drake *were* the original author and editor and were once > listed as such. I am not sure who or what else the publishers should > list. Python Development Community ? (which includes me for snippets of > the docs). The license requires that they *not* put themselves as the > authors. Yes, he was the original author; yes, the other he was the original editor. "By Guido van Rossum" on a book cover, with "Fred L. Drake (Editor)" on same cover, conveys something though. For one thing, people will assume Guido had a direct hand in this: did he? And that Fred was involved in editing (and since at least one person on one of the Amazon sales remarked of how horribly the web->book transition was done, makes him look bad). There are ways you can credit the authors of the real documentation and not flagrantly cash in on their reputation to sell (for outrageous prices). > You would have to ask them. Perhaps the PSF should publish each edition > of the manuals. Assembly of the pdfs for say, Lulu (a print-on-demand > publisher) could probably be pretty well automated with Python and > Sphinx. There is already a .pdf version produced, but it would need some > tweaking. And this would need someone's time. I'm not saying such a thing couldn't be done; or that it shouldn't be done; or that someone producing the web docs->book doesn't even have a right to make a profit off of it. I'm not even saying what this company did isn't entirely permitted -- but permitted doesn't mean there's not some underhanded stuff going on at the same time and that its all above-the-board and ethical. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On 6/22/2010 11:49 AM, Stephen Hansen wrote: On 6/22/10 6:48 AM, lallous wrote: Hello, I wonder if anyone read this: http://www.amazon.com/PYTHON-2-6-Extending-Embedding-documentation/dp/1441419608/ref=sr_1_7?ie=UTF8&s=books&qid=1277214352&sr=1-7 or this: http://www.amazon.com/Python-Extending-Embedding-Documentation-Manual/dp/1441412743/ref=pd_sim_b_3 Are these books just a print out of the manual that comes w/ Python distribution or they are written in a different way and more organized way? Uhh, that looks like a scam. Someone scraped the Python docs and bundled it up as a "book" to sell to naive people for outrageous prices; Various people have asked on this list for printed versions of the docs. PSF has never provided them. As I once read the license, it allows anyone to do so, and charge whatever price. I considered doing this once myself, but they seem to have beaten me to it ... Except that there is one possible scam aspect -- there is no version listed on the cover. A reviewer of the ref manual said his was for 3.0.1. Selling that now as the Python 3 Ref Manual (there is no such thing) *is* a scam. There is no indication that it has been undated. If I were to do this, I would be honest in this respect and publish the "Python 3.1.2 Refence Manual", etc. Much more work to redo, better service. I would publish through print-on-demand so there is no inventory. Given editorial and administrative costs, printing cost, bookseller markup, and "For each copy sold $1 will be donated to the Python Software Foundation by the publisher", the price is not unreasonable. The fixed costs have to be amortized over an unknown and probably not large sales base. The standard author royalty might be $2, so they are not saving that much on that score. and put Guido's name on it to give it legitimacy. Guido and Fred Drake *were* the original author and editor and were once listed as such. I am not sure who or what else the publishers should list. Python Development Community ? (which includes me for snippets of the docs). The license requires that they *not* put themselves as the authors. It also bundles up the *tutorial* for $22. There's a number of very good, large Python books which sell for that. Surely Fred L Drake and Gudio aren't really involved in this. I wonder if they even know about it. You would have to ask them. Perhaps the PSF should publish each edition of the manuals. Assembly of the pdfs for say, Lulu (a print-on-demand publisher) could probably be pretty well automated with Python and Sphinx. There is already a .pdf version produced, but it would need some tweaking. And this would need someone's time. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: print line number and source filename
begin - import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s" "%(levelname)-5.5s [%(name)s %(module)s:%(funcName)s:%(lineno)d]" "%(message)s") def run(): x = 5 logging.debug("X = %d" % x) run() - end - You can probably use string default concatenation feature of python. Anyway, am just nitpicking. Loved your example, as I was unaware of logging module. -- http://mail.python.org/mailman/listinfo/python-list
Re: print line number and source filename
you can use __file__ On Tue, Jun 22, 2010 at 10:14 PM, Peng Yu wrote: > I want to print filename and line number for debugging purpose. So far > I only find how to print the line number but not how to print > filename. > > import inspect > print inspect.currentframe().f_lineno > > I found inspect.getsourcefile(), but I have to supply a class name to > it. I have searched online, but I don't find how to print the source > filename. Would you please let me know? > > Also, always importing the inspect module and getting the frame and > accessing the lineno from the frame is not very convenient to type. Is > there a shorter way to access the line number (for example, in C++ and > perl, __LINE__ can be used to access line number, which is much more > convenient than the way that I found in python). > > -- > Regards, > Peng > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: adding new function
On 6/22/2010 5:44 AM, Daniel Fetchinson wrote: how can i simply add new functions to module after its initialization (Py_InitModule())? I'm missing something like PyModule_AddCFunction(). in Python, for modules written in python import mymod mymod.fname = somefunc #or setattr(mymod, namestring, funcobject) I presume you use the C-API equivalent of setattr. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: print line number and source filename
On 6/22/10 9:44 AM, Peng Yu wrote: > Also, always importing the inspect module and getting the frame and > accessing the lineno from the frame is not very convenient to type. Is > there a shorter way to access the line number (for example, in C++ and > perl, __LINE__ can be used to access line number, which is much more > convenient than the way that I found in python). This all seems to be reinventing the wheel. Have you seen the logging module? Given this toy file: begin - import logging logging.basicConfig(level=logging.DEBUG,format="%(asctime)s %(levelname)-5.5s [%(name)s %(module)s:%(funcName)s:%(lineno)d] %(message)s") def run(): x = 5 logging.debug("X = %d" % x) run() - end - 2010-06-22 10:12:07,907 DEBUG [root test:run:6] X = 5 It outputs exact time, type of log message, the name of the logger (That's the 'root' -- you can skip if you only use one), the exact module (test.py), function (run) and line (6). -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: print line number and source filename
22:26:51 l0nwlf-MBP:~/Desktop$ cat test.py print __file__ 22:26:55 l0nwlf-MBP:~/Desktop$ python test.py test.py On Tue, Jun 22, 2010 at 10:26 PM, Shashwat Anand wrote: > you can use __file__ > > > On Tue, Jun 22, 2010 at 10:14 PM, Peng Yu wrote: > >> I want to print filename and line number for debugging purpose. So far >> I only find how to print the line number but not how to print >> filename. >> >> import inspect >> print inspect.currentframe().f_lineno >> >> I found inspect.getsourcefile(), but I have to supply a class name to >> it. I have searched online, but I don't find how to print the source >> filename. Would you please let me know? >> >> Also, always importing the inspect module and getting the frame and >> accessing the lineno from the frame is not very convenient to type. Is >> there a shorter way to access the line number (for example, in C++ and >> perl, __LINE__ can be used to access line number, which is much more >> convenient than the way that I found in python). >> >> -- >> Regards, >> Peng >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- http://mail.python.org/mailman/listinfo/python-list
print line number and source filename
I want to print filename and line number for debugging purpose. So far I only find how to print the line number but not how to print filename. import inspect print inspect.currentframe().f_lineno I found inspect.getsourcefile(), but I have to supply a class name to it. I have searched online, but I don't find how to print the source filename. Would you please let me know? Also, always importing the inspect module and getting the frame and accessing the lineno from the frame is not very convenient to type. Is there a shorter way to access the line number (for example, in C++ and perl, __LINE__ can be used to access line number, which is much more convenient than the way that I found in python). -- Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: Information about PHP + MySQL E-book
On Wed, Jun 23, 2010 at 2:15 AM, J3p wrote: > Hi, I need some Information from you. Someone told me to buy E-book > about PHP + MySQL in > http://php-mysql-ebook.blogspot.com > Does anyone have experience about this? This has nothing whatsoever to do with Python except that Python has MySQL drivers. --James -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Information about PHP + MySQL E-book
Hi, I need some Information from you. Someone told me to buy E-book about PHP + MySQL in http://php-mysql-ebook.blogspot.com Does anyone have experience about this? thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Why inspect.getsource() can not getsource for a class?
On Tue, Jun 22, 2010 at 9:53 AM, Peng Yu wrote: > Hi, > > It seems I don't completely understand how getsource works, as I > expect that I should get the source code of class A. But I don't. > Would you please let me know what I am wrong? > > $ cat main.py > #!/usr/bin/env python > > import inspect > > class A: > pass > > a=A() > > print inspect.getsource(a) You passed in an instance of the class, not the class itself. The following will work: print inspect.getsource(A) As will: print inspect.getsource(a.__class__) Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Why inspect.getsource() can not getsource for a class?
On Wed, Jun 23, 2010 at 1:53 AM, Peng Yu wrote: > It seems I don't completely understand how getsource works, as I > expect that I should get the source code of class A. But I don't. > Would you please let me know what I am wrong? If you "read" the documentation carefully: """ getsource(object) Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved. """ This "does not" include an object / instance (whichever you prefer). $ python main.py class A: pass $ cat main.py import inspect class A: pass a=A() print inspect.getsource(a.__class__) cheers James -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'open' is not a function according to inspect module?
On Wed, Jun 23, 2010 at 1:42 AM, Peng Yu wrote: > 'open' is not a function according to inspect module. But according to > help(open), it is a function. Is there something wrong with inspect > module? $ python Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) [GCC 4.4.4 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from inspect import isbuiltin, isclass, isfunction >>> type(str) >>> isbuiltin(str), isclass(str), isfunction(str) (False, True, False) >>> def foo(): pass ... >>> type(foo) >>> isbuiltin(foo), isclass(foo), isfunction(foo) (False, False, True) >>> type(open) >>> isbuiltin(open), isclass(open), isfunction(open) (True, False, False) >>> Notice anything ? --James PS: The Python REPL is your friend :) -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Why 'open' is not a function according to inspect module?
On Tue, Jun 22, 2010 at 9:42 AM, Peng Yu wrote: > Hi, > > 'open' is not a function according to inspect module. But according to > help(open), it is a function. Is there something wrong with inspect > module? > > $ cat main.py > #!/usr/bin/env python > > import inspect > > def hello(): > print "Hello World!" > return > > print inspect.isfunction(str) > print inspect.isfunction(open) > print inspect.isfunction(hello) inspect.isfunction returns True if the object is a *user-defined* function. For built-in functions, use inspect.isbuiltin. You might also be interested in the callable() function, which returns True if the object is any object that can be called. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Why inspect.getsource() can not getsource for a class?
Hi, It seems I don't completely understand how getsource works, as I expect that I should get the source code of class A. But I don't. Would you please let me know what I am wrong? $ cat main.py #!/usr/bin/env python import inspect class A: pass a=A() print inspect.getsource(a) $ ./main.py Traceback (most recent call last): File "./main.py", line 10, in print inspect.getsource(a) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 689, in getsource lines, lnum = getsourcelines(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 441, in getsourcefile filename = getfile(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object -- Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On 6/22/10 6:48 AM, lallous wrote: > Hello, > > I wonder if anyone read this: > http://www.amazon.com/PYTHON-2-6-Extending-Embedding-documentation/dp/1441419608/ref=sr_1_7?ie=UTF8&s=books&qid=1277214352&sr=1-7 > or this: > http://www.amazon.com/Python-Extending-Embedding-Documentation-Manual/dp/1441412743/ref=pd_sim_b_3 > > Are these books just a print out of the manual that comes w/ Python > distribution or they are written in a different way and more organized > way? Uhh, that looks like a scam. Someone scraped the Python docs and bundled it up as a "book" to sell to naive people for outrageous prices; and put Guido's name on it to give it legitimacy. It also bundles up the *tutorial* for $22. There's a number of very good, large Python books which sell for that. Surely Fred L Drake and Gudio aren't really involved in this. I wonder if they even know about it. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Why 'open' is not a function according to inspect module?
Hi, 'open' is not a function according to inspect module. But according to help(open), it is a function. Is there something wrong with inspect module? $ cat main.py #!/usr/bin/env python import inspect def hello(): print "Hello World!" return print inspect.isfunction(str) print inspect.isfunction(open) print inspect.isfunction(hello) $ ./main.py False False True >>>help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. -- Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple list problem that's defeating me!
Neil Webster a écrit : Hi all, I've got a simple problem but it's defeated me and I was wondering if somebody could point out where I'm going wrong 1/ not posting working code (got a NameError) 2/ not posting the expected output 3/ not posting the actual output or offer an alternative solution to the problem? When you'll have fixed the 3 problems listed above !-) (snip broken code) -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On Jun 22, 4:49 pm, James Mills wrote: > On Wed, Jun 23, 2010 at 12:27 AM, lallous wrote: > > For me it is not a matter of competency to seek a book: organized, > > structured and uniform way of presenting information. > > > Nonetheless, I always refer to the sources to get my questions > > answered...but a book (with the qualities I mentioned above) would > > make everyone's life easier. > > Like I said, no "phun" intended :) I don't know any off hand > and reading printed material is not something I enjoy! > Yes James, I understand. I did not mean to attack you or defend a point rather than make a point. I appreciate your feedback. Thank you Tim too. Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On Tue, 22 Jun 2010 03:02:15 -0700 (PDT) lkcl wrote: > so whilst ruby may be dynamic and compact, it's not beautiful, > readable or obvious as to what's going on. i look at a python > program, and it uses actual... like... y'know... words that make Python is executible pseudocode. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On Wed, Jun 23, 2010 at 12:27 AM, lallous wrote: > For me it is not a matter of competency to seek a book: organized, > structured and uniform way of presenting information. > > Nonetheless, I always refer to the sources to get my questions > answered...but a book (with the qualities I mentioned above) would > make everyone's life easier. Like I said, no "phun" intended :) I don't know any off hand and reading printed material is not something I enjoy! :) --James -- http://mail.python.org/mailman/listinfo/python-list
Using Unicode file names with ftplib and encodings.idna as a workaround?
Python 2.6.5 (Win32): Is there a work around for ftplib's (and ftputil's) apparent inability to support Unicode file names? I'm thinking that I might be able to use the encodings.idna as a work around for this? In other words, regardless of whether I'm getting or putting a file to the server, I would encode the remote paths like so: remotePath = encodings.idna.ToASCII( localPath ) I would then wrap the nlst command so that the list of returned file names would have the following transformation applied to each filename: [ encodings.idna.ToUnicode( item ) for item in os.listdir('') ] One downside is that processes on the server will also have to wrap directory access with a similar transformation. This wouldn't be too complicated for Python programs, but I'm not sure how convenient this would be for our PHP and shell scripters. (Just checked: There's a PEAR module for PHP4/5; oddly enough nothing pops up for .NET IDNA libraries) Another challenge: Which Python idna encoding technique to use? I just started a thread that points out that encodings.idna.ToASCII( fileName ) != fileName.encoding( 'idna' ). Thoughts? Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On 22/06/2010 15:27, lallous wrote: Hi James, For me it is not a matter of competency to seek a book: organized, structured and uniform way of presenting information. Nonetheless, I always refer to the sources to get my questions answered...but a book (with the qualities I mentioned above) would make everyone's life easier. I've never come across a published book *only* on the C API. The main docs [1] aren't bad, in my opinion, although what suits one person won't necessarily suit another. Mark Lutz's Programming Python [2] includes a couple of chapters which are essentially an alternative take on the material in the docs. There are a few published articles around, although not many I think. And there's the C-API mailing list [3] which is quite helpful. TJG [1] http://docs.python.org/py3k/c-api/ [2] http://oreilly.com/catalog/9780596009250 [3] http://mail.python.org/mailman/listinfo/capi-sig -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple list problem that's defeating me!
On 22/06/2010 15:06, Neil Webster wrote: Hi all, I've got a simple problem but it's defeated me and I was wondering if somebody could point out where I'm going wrong or offer an alternative solution to the problem? I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]]. I need to combine the two lists that have the same first character in this example 'a'. In reality there are 656 lists within the list. My attempt so far is: L = [[a,2,3,4],[b,10,11,12], [a,2,3,4]] d = [] z = 1 while z<= len(L): for a in L: if L.count(a[0])> 1: d.append(a[2:]) summed = [sum(pair) for pair in zip(d[0], d[1])] z = z+1 print summed Any pointers more than welcome. Thanks all. My simplistic approach. Sort the list (this happens in place). Use the itertools groupby function to place everything together, see http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby Combine the lists in the groups. HTH. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Google Adsense Account Approval With In 4 Hours
Google adsense account with in 4 hours. Send your name,address and phone number to "earnmoney9...@gmail.com". I will give ur account with in 4hrs. secure and Safe Account Approval , approved directly by adsense team. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple list problem that's defeating me!
On Wed, Jun 23, 2010 at 12:06 AM, Neil Webster wrote: > I've got a simple problem but it's defeated me and I was wondering if > somebody could point out where I'm going wrong or offer an alternative > solution to the problem? Is this a hypothetical/mathematical problem of sorts ? If so, do you have the actual problem description ? It's often better to come up with a different (perhaps better) solution without looking at someone else's :) --james -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I Learn Python or Ruby next?
On 6/22/10 4:51 AM, James Mills wrote: > On Tue, Jun 22, 2010 at 9:37 PM, Nathan Rice > wrote: >> As far as community support, Python has 4342 packages listed in sourceforge, >> Ruby has 705. Python is listed in ~0.4% of jobs at indeed.com's trend > > You are forgetting the 10278 (last count) or so packages, modules and what not > available on PyPi (1). In all fairness, then you need to compare the nearly nine thousand packages on RubyForge. But, otherwise, I refrain from this conversation. Obviously the users on this list prefer Python, in general. We may have many fine reasons for doing so, some of us may have used a bit of Ruby, but LanguageA or LanguageB conversations are never really useful. If you're doing this to solve a certain problem: specify the problem, and I may have some real insight for you. If you're learning this out of an academic desire to learn a new language, then learn both. Learning a new language is always a net win. Which first? Whatever you have the vaguest preference for after five minutes. No reason to be picky with adding tools to your mental toolbox. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Hi James, For me it is not a matter of competency to seek a book: organized, structured and uniform way of presenting information. Nonetheless, I always refer to the sources to get my questions answered...but a book (with the qualities I mentioned above) would make everyone's life easier. :) On Jun 22, 4:24 pm, James Mills wrote: > On Wed, Jun 23, 2010 at 12:14 AM, lallous wrote: > > Well, it seems the printed version of the manual. Can anyone suggest a > > nice book to learn more about the Python C Api? > > It's not really a book, but how about the source ? > > If you're a competent C programmer you're not really > going to even need a pretty book now are you ? :) > (No phun intended! > > --james > > -- > -- > -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple list problem that's defeating me!
On 23 June 2010 00:06, Neil Webster wrote: > Hi all, > > I've got a simple problem but it's defeated me and I was wondering if > somebody could point out where I'm going wrong or offer an alternative > solution to the problem? > > I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]]. I > need to combine the two lists that have the same first character in > this example 'a'. In reality there are 656 lists within the list. > Here's my take: >>> input = [['a',2,3,4], ['b',10,11,12], ['a',2,3,4]] >>> output = {} >>> for i in input: ... output[i[0]] = output.get(i[0], 0) + sum(i[1:]) ... >>> output {'a': 18, 'b': 33} Note in your example, a and b are not defined, so I used a string instead. Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On Wed, Jun 23, 2010 at 12:14 AM, lallous wrote: > Well, it seems the printed version of the manual. Can anyone suggest a > nice book to learn more about the Python C Api? It's not really a book, but how about the source ? If you're a competent C programmer you're not really going to even need a pretty book now are you ? :) (No phun intended! --james -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Hi again, Well, it seems the printed version of the manual. Can anyone suggest a nice book to learn more about the Python C Api? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Simple list problem that's defeating me!
Hi all, I've got a simple problem but it's defeated me and I was wondering if somebody could point out where I'm going wrong or offer an alternative solution to the problem? I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]]. I need to combine the two lists that have the same first character in this example 'a'. In reality there are 656 lists within the list. My attempt so far is: L = [[a,2,3,4],[b,10,11,12], [a,2,3,4]] d = [] z = 1 while z <= len(L): for a in L: if L.count(a[0]) > 1: d.append(a[2:]) summed = [sum(pair) for pair in zip(d[0], d[1])] z = z+1 print summed Any pointers more than welcome. Thanks all. -- http://mail.python.org/mailman/listinfo/python-list
encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna' )
Python 2.6.4 (Win32): Anyone have any explanation for the following encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna' ) Given that other processes may have to use the output of these methods, what is the recommended technique? Demonstration: >>> import encodings.idna >>> name = u'junk\xfc\xfd.txt' >>> name u'junk\xfc\xfd.txt' >>> encodings.idna.ToASCII( name ) 'xn--junk.txt-95ak' >>> name.encode( 'idna' ) 'xn--junk-3rag.txt' >>> encodings.idna.ToUnicode( encodings.idna.ToASCII( name ) ) u'junk\xfc\xfd.txt' >>> name.encode( 'idna' ).decode( 'idna' ) u'junk\xfc\xfd.txt' The good news is that the encodings.idna and string idna transformations appear to properly mirror when used with their matching transformation. The bad news is that encodings.idna and the equivalent str transformations can't be intermixed. Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Book review / advise
Hello, I wonder if anyone read this: http://www.amazon.com/PYTHON-2-6-Extending-Embedding-documentation/dp/1441419608/ref=sr_1_7?ie=UTF8&s=books&qid=1277214352&sr=1-7 or this: http://www.amazon.com/Python-Extending-Embedding-Documentation-Manual/dp/1441412743/ref=pd_sim_b_3 Are these books just a print out of the manual that comes w/ Python distribution or they are written in a different way and more organized way? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Second attempt WAS: From Dict to Classes yes or no and how
Jerry Rocteur wrote: On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur wrote: If you were able to ask us perhaps a more specific question and describe your problem a little more concisely perhaps I (and we) might have a bit more to offer you. I have a dictionary: users[key] = {'user': key, 'secnum' : secnum, 'name': name } Is it possible for me to code a class like this: class GRPUser(object): def __init__(self, user, secnum, name, groups=None): self.user = user self.secnum= secnum self.name = name Which would allow me to iterate through and access specific records ? How do I iterate through and access an individual user record! Thanks in advance," Jerry I believe you have a dictionary of dictionaries. The outer level one is called users, and a key to that dictionary is a string containing a user name. What you want to do is replace the inner dictionary with an instance of a custom class, and you'd like to know how. First, I'd point out that it's already a class, called dict. Using your own class can give some advantages, but you have to decide if you want or need them. I don't see how having the data for one user as a class object will make any difference in how you find that object, or how you iterate through a dictionary or list of such objects. But if it's what you want... class GRPUser(object): def __init__(self, mydict): self.user = mydict["user"] self.secnum = mydict["secnum"] self.name = mydict["name"] self.groups = None Now to find a particular user, say currentuser = "Joe" Just use users[currentuser] To loop through all the users, for user in users: ...do something with user... To change the groups attribute of a particular user, users[currentuser].groups = ...newvalue... DaveA -- http://mail.python.org/mailman/listinfo/python-list
xmlrpclib and errcode -1
I have a xmlrpc server and client running on same Windows computer. The server is part of a bigger program and client is a Cherrypy application that provides a http interface to this program. Problem is that sometimes (1 out of 100) I get xmlrpc ProtocolError without no apparent reason. The server receives the message and does everything it's supposed to do. However, the client gets error code -1. I have been trying to reproduce the error but it's difficult. The contents of the message don't seem to be the problem. There isn't a whole lot of traffic either, we are talking about a message per minute or so. This is what I get in the client program. 2010-06-22 15:15:40 ERROR exception occurred Traceback (most recent call last): File "C:\cygwin\home\Administrator\gsmsc\gsmschttp\gsmschttp.py", line 120, in smsgw_act server.add_outbound_from_dict(msg) File "c:\Python26\lib\xmlrpclib.py", line 1199, in __call__ return self.__send(self.__name, args) File "c:\Python26\lib\xmlrpclib.py", line 1489, in __request verbose=self.__verbose File "c:\Python26\lib\xmlrpclib.py", line 1243, in request headers ProtocolError: 2010-06-22 15:15:40 DEBUG url: localhost:8000/RPC2 2010-06-22 15:15:40 DEBUG headers: None 2010-06-22 15:15:40 DEBUG error code: -1 2010-06-22 15:15:40 DEBUG error msg: This -1 seems to come from httplib and HTTP.getreply(). try: response = self._conn.getresponse() except BadStatusLine, e: ### hmm. if getresponse() ever closes the socket on a bad request, ### then we are going to have problems with self.sock ### should we keep this behavior? do people use it? # keep the socket open (as a file), and return it self.file = self._conn.sock.makefile('rb', 0) # close our socket -- we want to restart after any protocol error self.close() self.headers = None return -1, e.line, None I'm not sure what this means. Probably I have some kind of http problem, connection closed before client reads reply etc. How should I go forward in solving this? Pasi -- http://mail.python.org/mailman/listinfo/python-list
Re: From Dict to Classes yes or no and how
Jerry Rocteur wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 06/22/2010 01:32 PM, Jerry Rocteur wrote: My input is NOT CSV, I used this format to try and make the question shorter. Although I could create a CSV file, I'd like to learn how to code a class to work the way I described in the question. Sorry for misunderstanding. Can you maybe give one example that's not CSV? Both your demonstrated files actually are CSV like. Can you be more specific on what actually changes constantly. (Fields given in the files, or the users in the files, or...) Can you tell us, why you want to use classes if the dict approach works great? As part of learning Python, I'm also learning OOP! That is why I want to know if this is doable using classes. The input is not important, I end up with the dictionary as described in the question and as I asked in the question, I'd like to access the dictionary as a class and I don't know how or if it is possible. Jerry Dictionary is already a class in python, everything is an object actually (even class are objects). A python OOP approach to your problem would be to subclass the builtin 'dict' class and override / add the methods. Here is an example how you can for your User dictionary to accept only some types of values. class User(object): def __init__(self, user, secnum, name): self.user = user self.secnum = secnum self.name = name def __str__(self): return "%(name)s <%(user)s> -- secnum :%(secnum)d" % self.__dict__ def __repr__(self): return self.__str__() class Users(dict): def __init__(self): dict.__init__(self) # call the baseclass constructor def __setitem__(self, user, value): if isinstance(value, User): dict.__setitem__(self, user, value) else: try: dict.__setitem__(self, user, User(user, value[0], value[1])) except KeyError: raise ValueError ("Invalid user format, it shoudl be either a User object or a tuple (secnum, name)") users = Users() users['jro'] = (1325,'john') # the overriden __setitem__ method wil ltake care of creating the User object for you. users['dma'] = User('dma', 654968, 'dominic') for user in users: print users[user] # Users objects inherit all dict method, values() for instance for user in users.values(): print user For more information: http://docs.python.org/reference/datamodel.html Read carefully the 3.4.6 section (Emulating container type) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Second attempt WAS: From Dict to Classes yes or no and how
On 06/22/2010 02:03 PM, Jerry Rocteur wrote: >> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur wrote: >> If you were able to ask us perhaps a more specific question >> and describe your problem a little more concisely perhaps >> I (and we) might have a bit more to offer you. > > I have a dictionary: > > users[key] = {'user': key, > 'secnum' : secnum, > 'name': name > } > > Is it possible for me to code a class like this: > > class GRPUser(object): > def __init__(self, user, secnum, name, groups=None): > self.user = user > self.secnum= secnum > self.name = name > So far your class is perfectly fine, representing the data in form of a class having an object for each individual user. > Which would allow me to iterate through and access specific records ? That actually is not part of the class nor should it even be part of the class. You would probably end up with something comparable to your initial dict to 'lookup' the objects. users = {} users['jdoe'] = GRPUser('jdoe', ...) ... This dict is something like an index from user id to user objects. You may then setup an index for the secnum (if unique) the same way: secnums = {} secnums[12345] = users['jdoe'] ... Note, that I did set the identical object in the other index dict. Modifying users['jdoe'] would modify secnums[12345]! This is what you actually want from an index... > How do I iterate through and access an individual user record! You iterate over the index... Andre -- http://mail.python.org/mailman/listinfo/python-list
Re: Second attempt WAS: From Dict to Classes yes or no and how
On Tue, Jun 22, 2010 at 10:03 PM, Jerry Rocteur wrote: >> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur wrote: >> If you were able to ask us perhaps a more specific question >> and describe your problem a little more concisely perhaps >> I (and we) might have a bit more to offer you. > > I have a dictionary: > > users[key] = { 'user' : key, > 'secnum' : secnum, > 'name' : name > } > > Is it possible for me to code a class like this: > > class GRPUser(object): > def __init__(self, user, secnum, name, groups=None): > self.user = user > self.secnum = secnum > self.name = name > > Which would allow me to iterate through and access specific records ? > > How do I iterate through and access an individual user record! > > Thanks in advance, I'm not sure what's wrong with your email client but I already answered this for you. To access an individual record given that you have a dict called "users" that holds a mapping of username to user record/object simply select an individual record by it's key (username). eg: >>> users["Bob Jane"] cheers James -- http://mail.python.org/mailman/listinfo/python-list
Second attempt WAS: From Dict to Classes yes or no and how
> On Tue, Jun 22, 2010 at 9:32 PM, Jerry Rocteur wrote: > If you were able to ask us perhaps a more specific question > and describe your problem a little more concisely perhaps > I (and we) might have a bit more to offer you. I have a dictionary: users[key] = {'user': key, 'secnum' : secnum, 'name': name } Is it possible for me to code a class like this: class GRPUser(object): def __init__(self, user, secnum, name, groups=None): self.user = user self.secnum= secnum self.name = name Which would allow me to iterate through and access specific records ? How do I iterate through and access an individual user record! Thanks in advance, Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: From Dict to Classes yes or no and how
Jerry Rocteur a écrit : (snip) As part of learning Python, I'm also learning OOP! That is why I want to know if this is doable using classes. > The input is not important, I end up with the dictionary as described in the question and as I asked in the question, I'd like to access the dictionary as a class I assume you mean "as an object" (or "as an instance of a class" - which is exactly the same thing). If you don't understand what this means, then you should first learn the difference between a class and an instance !-) and I don't know how or if it is possible. Well, Python being 100% object, your dict is already an object (an instance of the builtin 'dict' class). -- http://mail.python.org/mailman/listinfo/python-list
Re: Second attempt WAS: From Dict to Classes yes or no and how
On Tue, Jun 22, 2010 at 10:03 PM, Jerry Rocteur wrote: > How do I iterate through and access an individual user record! A much better question! :) You are in fact already demonstrating that you know full well how to access a specific user record - by accessing a parent dictionary holding a mapping of user -> user record. You select a user record by key. >>> users["Bob Jane"] Your example of a user record if perfectly fine to me. If you wanted to iterate over all user records: >>> for k, v in users.items(): ... # some code here cheers James -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: From Dict to Classes yes or no and how
On Tue, Jun 22, 2010 at 9:56 PM, Jerry Rocteur wrote: > As part of learning Python, I'm also learning OOP! That is why I want to know > if this is doable using classes. > > The input is not important, I end up with the dictionary as described in the > question and as I asked in the question, > I'd like to access the dictionary as a class and I don't know how or if it is > possible. I suggest you start playing around with python classes and objects. It's entirely possible you can create your own class that represents your data and store this in some fashion. You could also subclass (you'll learn about this) the dict class creating your own customized dict (if you will). The former approach may be better suited however instead of diving into things you may not yet come to fully understand until you really learn the inner workings of python :) cheers James -- -- -- "Problems are solved by method" -- http://mail.python.org/mailman/listinfo/python-list
Re: Serialization, save type information in file and restore them
En Fri, 18 Jun 2010 08:24:01 -0300, Timothy Wu <2hug...@gmail.com> escribió: I created a class that's able to manipulate tabulated data. I want to be able to dump the bulk of the data and other attributes as a tab-delimited text. I have trouble saving/restoring type information in the file. For example, some attributes are int, others may be float, etc. So I want to store the data type as well as the data value themselves in a file. And I don't think I want to use Pickle because I want it to be readily opened in vi and be readable as a tab-delimited file and be able to import into Excel as well. What's the best way to achieve this? I was able to write string like "attribute = int(value)" into a file. But how do I get the value back? I want the "int(value)" string to be loaded into the program and be executable so I can actually create the instance variable in the class. Use the csv module to write your data in the RDB file format. The RDB format is fairly simple: first line contains the column names (tab separated), second line stores type information (tab separated), remaining lines contain actual data (also, tab separated). (You may use any format you want, but why reinvent it, and you may even find an existing RDB parser/writer in Python) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list