Re: Hashtables in pyhton ...
Konrad Mühler wrote: > Hi, > > are there predefinded chances to use hashtables in python? How can I use > Hashtable in python? Or do I have to implement this on my own? > > Thanks A Java Hashtable/Hashmap is equivalent to a Python dictionary, which is a builtin objects (and not a second-class citizen in some distant, dark, cold library full of Evil Things ©). You can access it either via the regular constructor `dict()` or via the syntaxical shorcut { key1: val1, key2: val2, key3: val3} -- http://mail.python.org/mailman/listinfo/python-list
Re: python debugging question
[EMAIL PROTECTED] wrote: > I am a python newbie. I have writen some 500 lines of code. There are 4 > classes and in all 5 files. > > Now, I am trying to run the program. I am getting wrong values for the > simulation results. > Is there any debugging facilities in python which would let me go step > by step and check the values of the variables at every step. I have > done something like this in MS Visual Stdio 6.0 sometime back. > > For python, I am using SPE. > > what is a good way of debugging such large and iterative programs ? Any > tips. > > Every help is appreciated. > > Thanks > Check the PDB standard package, reading Debugging in Python (http://www.ferg.org/papers/debugging_in_python.html) may also help. And I think SPE provides WinPDB, check the user manual. I'd suggest trying to work out why it doesn't work at a higher level instead of relying on the debugger already, 500 lines is not much code to go through, a few well placed prints or sys.stderr.write() should be more than enough. -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about zip...
KraftDiner wrote: > I had a structure that looked like this > ((0,1), (2, 3), (4, 5), (6,7) > > I changed my code slightly and now I do this: > odd = (1,3,5,7) > even = (0,2,4,6) > all = zip(even, odd) > > however the zip produces: > [(0, 1), (2, 3), (4, 5), (6, 7)] > > Which is a list of tuples.. I wanted a tuple of tuples... > tuple(zip(even, odd)) and if you fear for memory efficiency tuple(iterator.izip(even, odd)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Use python from command line
trixie wrote: > Using WinXP and Python24 on generic desktop. > Being used to linux and command line operations I cannot make Windows accept > the 'python myprog.py' command. > Any help appreciated. > Bob > > I think you could've given us the error message that this command yields. Issue is probably that the Python directory isn't on your path -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you move to a new line in your text editor?
John Salerno wrote: > So I'm wondering, how do you all handle moving around in your code in > cases like this? Is there some sort of consistency to these things that > you can write rules for your text editor to know when to outdent? It > doesn't seem like you can do this reliably, though. Under windows, I'm using SciTE which is an extremely lightweight editor, but it handlers "smart unindent": pressing backspace at the beginning of a line unindents one level, whether you're indenting with tabs (and need to remove a tab) or space (and need to remove 2, 4, 8 spaces) doesn't matter. And since SciTE also has Visual Studio's smart home key (home brings you first at the beginning of the text == current indent, then at the beginning of the line itself == indent level 0) SciTE also features "somewhat smart" indent from time to time: it indents one level after a ":". This is good for if/else/while/..., but it also indents one level after ":" in dicts, which is way bad. Oh, and it automatically unindents one level after a "return" statement. Other than that, SciTE doesn't really "understand" python, if you want a really pythonic editor you need to check Stani's Python Editor, WingsIDE or Komodo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why I chose Python over Ruby
Torsten Bronger wrote: > Yes, however, this is also true for Python in my opinion. > Ruby's ability to generate DSLs is an order of magnitude better than Python's at least. I only know of the Lisp dialects that get better at DSLs. Check Rails' validation methods (in the models), or if you don't want to dwelve into rails (which I do understand), go check Why's "Dwemthy's Array" (http://poignantguide.net/dwemthy/) (note: you may need to read Why's Poignant Guide to Ruby first, the creation of the Array itself is fairly tough stuff with metaprogramming black magic and all). -- http://mail.python.org/mailman/listinfo/python-list
Re: Why I chose Python over Ruby
Bil Kleb wrote: > Xavier Morel wrote: >>> 2) Ruby does not have true first-class functions living in the same >>> namespace as other variables while Python does : >>> >>> In Ruby you need extra syntax that ruins the "first-class-ness" : >>> >> The extra syntax is a side-effect of the parensless call of method, it >> doesn't mean that methods are not first-class objects. > > The parensless calls also allow one to write beautiful > DSLs with Ruby. > > -- > Bil > http://fun3d.larc.nasa.gov Yes, they're a tradeoff, they have both advantages and inconvenients. Matz decided that the advantages were more than worth the inconvenients, and it is often true indeed for Matz built the language with this very feature (and some others) in mind. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why I chose Python over Ruby
I'll just play the devil's advocate here Francois wrote: > 1) In Ruby there is a risk of "Variable/Method Ambiguity" when calling > a method with no parameters without using () : > Yes, but that's in my opinion a programmer error, not necessarily a language error. > 2) Ruby does not have true first-class functions living in the same > namespace as other variables while Python does : > > In Ruby you need extra syntax that ruins the "first-class-ness" : > The extra syntax is a side-effect of the parensless call of method, it doesn't mean that methods are not first-class objects. And Ruby solved this issue with blocks/procs (that and closures are the only reasons I found for blocks to exist in ruby). In python you pass functions around, Ruby's equivalent of unbound functions are blocks/procs, what your code created here is a ruby method, equivalent to a bound method in Python, the semantics are really different (and in Python using this bound method would also require extra work). -- http://mail.python.org/mailman/listinfo/python-list
Re: How to do an 'inner join' with dictionaries
[EMAIL PROTECTED] wrote: > Let's say I have two dictionaries: > dict1 is 1:23, 2:76, 4:56 > dict2 is 23:A, 76:B, 56:C > > How do I get a dictionary that is > 1:A, 2:B, 4:C > >>> dict1 = {1:23,2:76,4:56} >>> dict2 = {23:'A',76:'B',56:'C'} >>> dict((k, dict2[v]) for k, v in dict1.items()) {1: 'A', 2: 'B', 4: 'C'} >>> ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure python implementation of string-like class
Ross Ridge wrote: > Xavier Morel wrote: >> Not if you're still within Unicode / Universal Character Set code space. > > Akihiro Kayama in his original post made it clear that he wanted to use > a character set larger than entire Unicode code space. > > Ross Ridge > He implies that, but in later messages he 1. Implies that he wants to use the Unicode private spaces, which are in the Unicode code space 2. Says explicitly that his needs concern Kanji encoding, which do fit in the existing Unicode code space, even if you take the largest estimates of the number of existing Kanjis (~8), and which are (I think) already partially represented by the CJK Unified Ideograms and CJK Unified Ideograms extension A sets of regular Unicode. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure python implementation of string-like class
Ross Ridge wrote: > Steve Holden wrote: >> "Wider than UTF-16" doesn't make sense. > > It makes perfect sense. > > Ross > Ridge > Not if you're still within Unicode / Universal Character Set code space. While UCS-4 technically goes beyond any Unicode Transformation Format (UTF-7, 8, 16 and 32 stop at 10) it also goes beyond the range of the UCS itself (0-10). UTF-32 is the limitation of UCS-4 to the Unicode standard. While it could be argued that Unicode/UCS limit of 10 was chosen _because_ of the limitations of UTF-16, It's probably irrelevant to the discussion. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure python implementation of string-like class
Akihiro KAYAMA wrote: > Sorry for my terrible English. I am living in Japan, and we have a > large number of characters called Kanji. UTF-16(U+...U+10) is > enough for practical use in this country also, but for academic > purpose, I need a large codespace over 20-bits. I wish I could use > unicode's private space (U+6000...U+7FFF) in Python. > > -- kayama I think the Kanji are part of the Han script as far as Unicode is concerned, you should check it (CJK unified ideograms and CJK unified ideograms extension A), they may not all be there, but the 27502 characters from these two tables should be enough for most uses. Oh, by the way, the Unicode code space only goes up to 10, while UCS-4's encoding allows code values up to and including 7FFF the upper Unicode private space is Plane Sixteen (10–10), the other private spaces being a part of the Basic Multilingual Plane (U+E000–U+F8FF) and Plane Fifteen (U+F–U+F) and even UTF-32 doesn't go beyond 10. Since the Dai Kan-Wa jiten "only" lists about 50,000 kanji (even though it probably isn't perfectly complete) it fits with ease in both plane fifteen and sixteen (65535 code points each). -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing text using python
Fredrik Lundh wrote: > did you read the string chapter in the tutorial ? > > http://docs.python.org/tut/node5.html#SECTION00512 > > around the middle of that chapter, there's a section on slicing: > > "substrings can be specified with the slice notation: two indices > separated by a colon" > Fredrik, how would you use slices to split a string by groups of 3 characters? -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing text using python
nuttydevil wrote: > Hey everyone! I'm hoping someone will be able to help me, cause I > haven't had success searching on the web so far... I have large chunks > of text ( all in a long string) that are currently all in separate > notebook files. I want to use python to read these strings of text, > THREE CHARACTERS AT A TIME. (I'm studying the genetic code you see, so > I need to read and analyse each sequence one codon at a time > effectively.) Does anyone have any idea of how to do this using python? > > > I'm going to be optimistic and thank you for your help in advance! > Samantha. > Since you're reading from files, the "read" operation of file-like objects takes an argument specifying the number of characters to read from the stream e.g. >>> f = file("stuff.txt") >>> f.read(3) 'car' >>> f.read(3) 'act' >>> f.read() 'erization' Would that be enough for what you need? -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Rene Pijlman wrote: > David Isaac: >> I would like to be able to define a loop statement >> (nevermind why) so that I can write something like >> >> loop 10: >>do_something >> >> instead of >> >> for i in range(10): >>do_something >> >> Possible? If so, how? > > Yes. By implementing a compiler or an interpreter for your programming > language. Or a preprocessor that converts your language to Python, or some > other suitable intermediate language. Or a programmer, that converts your > pseudocode and some coffee to the desired algorithm :-) > Or by hacking through the Python source and creating his own "somehow pythonish but absolutely not python" language -- http://mail.python.org/mailman/listinfo/python-list
Re: define loop statement?
Rene Pijlman wrote: > David Isaac: >> I would like to be able to define a loop statement >> (nevermind why) so that I can write something like >> >> loop 10: >>do_something >> >> instead of >> >> for i in range(10): >>do_something >> >> Possible? If so, how? > > Yes. By implementing a compiler or an interpreter for your programming > language. Or a preprocessor that converts your language to Python, or some > other suitable intermediate language. Or a programmer, that converts your > pseudocode and some coffee to the desired algorithm :-) > Or by hacking through the Python source and creating his own "somehow pythonish but absolutely not python" language -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Forms, Databases
Tempo wrote: > Larry I do see your point. There does seem to be a lot more support for > PHP and MySQL together than there is Python and ASP. But I want to > first try to accomplish my goal by using Python first before I give up > and revert back to PHP. So if I was going to parse HTML forms and place > the data into a MySQL database, what should I use? CGI module? Zope? > Webware? Thanks for any and all help. > If you're talking about a pair of page and nothing more, the CGI module and manually handling your stuff (with a DBAPI2 MySQL module for the DB link) is more than enough. If you want to create something more complex (a full database driven website), it would probably be a good idea to check some of Python's web frameworks, Django for example. -- http://mail.python.org/mailman/listinfo/python-list
Re: appending to a list via properties
Alex Martelli wrote: > Carl Banks <[EMAIL PROTECTED]> wrote: >... >>> class better_list (list): >>> tail = property(None, list.append) >> This is an impressive, spiffy little class. > > Yes, nice use of property. > > Alex I don't know, I usually see people considering that properties are "cool" as long as they don't have side effects, as long as they're virtual members. The tail property doesn't behave like member data at all, the semantics are strange, counter-intuitive (tail would usually be the end of the list, either [-1] or [1:], in this case it's some magic position at the end of the list). And it has one hell of a side effect. -- http://mail.python.org/mailman/listinfo/python-list
Re: Create dict from two lists
Diez B. Roggisch wrote: > py wrote: > >> I have two lists which I want to use to create a dictionary. List x >> would be the keys, and list y is the values. >> >> x = [1,2,3,4,5] >> y = ['a','b','c','d','e'] >> >> Any suggestions? looking for an efficent simple way to do this...maybe >> i am just having a brain fart...i feel like this is quit simple. > > dict(zip(x,y)) > > Diez I'd even suggest using izip (from itertools), it's often much faster than zip (end result is the same). Demo: >>> from itertools import izip >>> l1 = range(5000) >>> l2 = range(5000, 1) >>> from timeit import Timer >>> t1 = Timer("dict(zip(l1, l2))", "from __main__ import l1, l2") >>> t2 = Timer("dict(izip(l1, l2))", "from __main__ import l1, l2, izip") >>> min(t1.repeat(5, 1)) 17.989041903370406 >>> min(t2.repeat(5, 1)) 10.381146486494799 >>> 42% speed gain from using izip instead of zip (memory was not an issue during the test, machine had 1.3Gb of available ram) -- http://mail.python.org/mailman/listinfo/python-list
Re: creat a DOM from an html document
Mark Harrison wrote: > I thought I saw a package that would create a DOM from html, with > allowances that it would do a "best effort" job to parse > non-perfectly formed html. > > Now I can't seem to find this... does anybody have a recommendation > as to a good package to look at? > > Many TIA! > Mark While it doesn't generate a W3C DOM, BeautifulSoup is probably your best bet for parsing less-than-perfect HTML and get something useable out of it. Once you have your (parsed) document, you can either use it as is or try to convert it to a valid W3C DOM though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ternary Operator Now?
Ben Wilson wrote: > I read somewhere else that Python was getting a ternary operator (e.g. > x = (true/false) ? y : z). I read the PEP about it and that the PEP had > been approved this past Fall. Has this been released into the wild yet? > > IIRC, the operator is like: > > x = y if C : else z > PEP 308 "Conditional Expressions" has been accepted for Python 2.5, I'm pretty sure implementation hasn't even started yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: A __getattr__ for class methods?
Oh, and I wondered too: is your goal to build an ORM, or do you just need an ORM? Cause if it's the latter then Python does already have some fairly good ORMs such as SQLAlchemy or PyDO2, you don't *need* to create yours. -- http://mail.python.org/mailman/listinfo/python-list
Re: A __getattr__ for class methods?
Dylan Moreland wrote: > I'm trying to implement a bunch of class methods in an ORM object in > order to provide functionality similar to Rails' ActiveRecord. This > means that if I have an SQL table mapped to the class "Person" with > columns name, city, and email, I can have class methods such as: > > Person.find_by_name > Person.find_by_city_and_name > Person.find_by_name_and_city_and_email > > I have a metaclass generating basic properties such as .name and .city, > but I don't want to generate a class method for every permutation of > the attributes. I'd like to have something much like __getattr__ for > instance attributes, so that if a method like > Person.find_by_city_and_email cannot be found, I can construct a call > to the basic find method that hides the SQL. Is there any way of doing > this, or am I trying to mirror a functionality that Python simply does > not have? > I'm not sure that the way you tackled this is the good approach: while it's quite flexible as far as the search criteria go, it'll require less than obvious code to match keywords (field names) and values, will lead to somewhat verbose syntax (especially with many criteria), and the syntax itself is unforgiving (every new search field requires at least 5 additional characters on top of the field name itself), brittle (you'll have to do an extensive validation of your method name and fields unless you want everything to break, and Python doesn't support your syntax) and not really pythonic. Since you seem to know ActiveRecord, you're probably familiar with the way AR does this task: with a hash of column_name, value pairs. The syntax is quite straightforward especially due to the fact that any "key => value" comma-separated pairs sequence generates a hash, without requiring explicit hash boundaries ( { and } ). The syntax is extremely straightforward since it relies on the language's syntax itself, and the correctness of the grammar is checked by the compiler/interpreter itself since no custom syntax is built. This construct is therefore quite solid, on top of being obvious to a Rubyist. Now, you're in luck, because Python has even better than that: **kwargs, the optional keyword arguments. As you probably know, Python has a good support for keyword args, allowing you to fill your arguments out of order (and leave the 3th argument at it's default value while specifying the value of the 5th argument). But **kwargs goes beyond the regular explicit keyword arguments: when specified, **kwargs is a dict populated with the implicit keyword arguments (keyword:value pairs), the ones you haven't specified in the argument tuple of your method. This means that if I define a function as def foo(bar=0, **kwargs): print kwargs Then calling foo() will print an empty dict As will calling foo(3) or foo(bar=3), because the explicit "bar" keyword argument is used. Now if I call foo(something=5, somethingelse="woohoo"), kwargs will evaluate to {"somethingelse":"woohoo","something":5} This means that all you have to do is replace your method definition with >>> def find_by(cls, **kwargs): pass and in the method itself iterate over the key:value pairs of kwargs to automagically get both the field names and the values upon which your search shall be performed. Calling the method would then look something like: >>> Person.find_by( name="thenameyoulookfor", city="somecity") the syntax is fairly obvious and pythonic, has a low verbosity, and Python itself will do the parsing and the grammatical validation of your method calls for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hi reliability files, writing,reading and maintaining
Terry Reedy wrote: > "John Pote" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> I would wish to secure this data gathering against crashes of the OS, > > I have read about people running *nix servers a year or more without > stopping. > He'd probably want to check the various block-journaling filesystems to boot (such as Reiser4 or ZFS). Even though they don't reach DB-level of data integrity they've reached an interresting and certainly useful level of recovery. > To transparently write to duplicate disks, lookup RAID (but not level 0 > which I believe does no duplication). > Indeed, Raid0 stores data across several physical drives (striping), Raid1 fully duplicates the data over several physical HDs (mirror raid), Raid5 uses parity checks (which puts it between Raid0 and Raid1) and requires at least 3 physical drives (Raid0 and Raid1 require 2 or more). You can also nest Raid arrays, the most common nesting are Raid 01 (creating Raid1 arrays of Raid0 arrays), Raid 10 (creating Raid0 arrays of Raid1 arrays), Raid 50 (Raid0 array of Raid5 arrays), and the "Raids for Paranoids", Raid 15 and Raid 51 arrays (creatung a Raid5 array of Raid1 arrays, or a Raid1 array of Raid5 arrays, both basically means that you're wasting most of your storage space for redundancy informations, but that the probability of losing any data is extremely low). -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky regular expressions
Ernesto wrote: > Xavier Morel wrote: >> Ernesto wrote: >>> I'm not sure if I should use RE's or some other mechanism. Thanks >>> >> I think a line-based state machine parser could be a better idea. Much >> simpler to build and debug if not faster to execute. > > What is a line-based state machine ? > Parse your file line-by-line (since it seems that it's the way your data is organized). Keep state informations somewhere. Change your state based on the current state and the data being fed to your parser. For example, here you basically have 3 states: No Title, which is the initial state of the machine (it has not encountered any title yet, and you do stuff based on titles) Title loaded, when you've met a title. "Title loaded" loops on itself: if you meet a "Title: whatever" line, you change the title currently stored but you stay in the "Title loaded" state (you change the current state of the machine from "title loaded" to "title loaded"). Request loaded, which can be reached only when you're in the "Title loaded", and then encounter a line starting with "Request: ". When you reach that stage, do your processing (you have a title loaded, which is the latest title you encountered, and you have a request loaded, which is the request that immediately follows the loaded title), then you go back to the "No Title" state, since you've processed (and therefore unloaded) the current title. So, the state diagram could kind of look like that: (it's supposed to be a single state diagram, but i suck at ascii diagrams so i'll create one mini-diagram for each state) NoTitle =0> TitleLoaded =0> Event: on encountering a line starting with "Title: " Action: save the title (to whatever variable you see fit) Change state to: TitleLoaded TitleLoaded =1> TitleLoaded || 2 \/ Request =1> Event: on encountering a line starting with "Title: " Action: save the title (replace the current value of your title variable) Change state to: TitleLoaded =2> Event: on encountering a line starting with "Request: " Action: save the request?; immediately process the Request state Change state to: Request Request =3> NoTitle || 4 \/ TitleLoaded =3> Event: the Request state is reached, the request is either "Play" or "Next" Action: Do whatever you want to do; nuke the content of the title variable Change state to: NoTitle =4> Event: the Request state is reached, the request is neither "Play" nor "Next" Action: Nuke the content of the request variable (if you saved it), do nothing else Change state to: TitleLoaded As a final note, i'd recommend reading "Text Processing in Python", even though it puts a quite big emphasis on functional programming (which you may or may not appreciate), it's an extremely good initiation to text-files handling, parsing and processing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python good for web crawlers?
Paul Rubin wrote: > Generally I use urllib.read() to get > the whole html page as a string, then process it from there. I just > look for the substrings I'm interested in, making no attempt to > actually parse the html into a DOM or anything like that. > BeautifulSoup works *really* well when you want to parse the source (e.g. when you don't want to use string matching, or when the structures you're looking for are a bit too complicated for simple string matching/substring search) The API of the package is extremely simple, straightforward and... obvious. -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky regular expressions
Ernesto wrote: > I'm not sure if I should use RE's or some other mechanism. Thanks > I think a line-based state machine parser could be a better idea. Much simpler to build and debug if not faster to execute. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dual Core outlook
malv wrote: > Maybe this is too simplistic, but given two programs, one in Python the > other in Java or C#. Would this mean that running the latter on a dual > core processor would significantly increase execution speed, whereas > the Python program would be running in one processor only without any > speed up? > This is extremely dependent on the way the program is built. To get significant increases in execution speed, you need multiple *computational* threads, that means that you need 2+ threads that do the heavy work (number crunching, compression, ...), if you have one thread with heavy computations and the others handling low-computation parts of the program (UI) you may get a more _responsive_ program, but it won't be _faster_ (at least not noticeably), because the bottleneck of the application (the heavy computations) will still run on a single core/processor. Multicore/multiprocessor is not magic, and it's not trivial at all, it's hard to create correct multithreaded programs, and even harder to parallelize the heavy computation part between various threads. > Is a Java program capable of this "out of the box" or does this require > specific additional code? > Java and C# both use unlocked OS threads any time you use their threads. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dual Core outlook
malv wrote: > Of course, multiprocessing has been used for many years but this always > involved a much higher level of sophistication on the part of the > designers. This point seems to be largely hidden from the public, > ignorant and semi-ignorant, by the chip manufacturers. > Will new languages see the light rendering the spreading of > applications over many processors quasi transparent? > What is the outlook for Python? Would Ironpython with .net do better? > What about talk by the Java lobby that Java would be very much suited > for taking advantage of dual-core? Is there any thruth to this? > Python has support for OS threads, but it also has the GIL (a global lock from the interpreter). This means that Python behaves the same way Java or C# do as far as threads are concerned but for one field: multiprocessor (or multicore) situations. While C# or Java can execute two threads of the same process on two separate cores/processors Python can't. This means that you can't choke a multiprocessor/multicores machine with Python threads, and that if you want to scale in a multiprocessor/multicore environment (e.g. make use of all the available cores/processors) you have to use processes not threads (e.g. you have to launch multiple instances of the Python interpreter, each one having the ability to execute on a different core/processor). Now the question is: do you want to do it? Do you have several extremely demanding computational threads? If yes, then Python probably isn't what you need (unless you implement your computations in specific C modules and get rid of the GIL issue). If not (a single computational thread and several low-resources GUI/network/whatever threads), it's a non-issue. -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
Dave wrote: > Anyone familiar with PHP? I'm trying to make a translation. In PHP you > can get the current object's name by going like this: > > get_class(item) == 'ClassName' > > I've tried type(item), but since I can't be sure if I'll be in __main__ > or as a child object, I can't guarantee what that value will return, so > I can't just manipulate that value as a string. > Type doesn't return a string, it returns a reference to a class object. You look like you want to test if the class of an object is . For that purpose, check isinstance. > Is there a simple way to get the current object's name? You would think > __name__ would work, right? It doesn't. > What do you call "the current object's name"? A python object usually has no name per se (only functions and classes do have one I think). > Now here's another, similar one: > > You can reference an object's parent object directly in PHP, like so: > > //note the charming use of semi-colon. isn't it cute? > parent::__construct( > $stuffInAWeirdSyntaxThatDoesntMeanAnythingWhenYouReadIt); > > I'd like to avoid passing a reference to an object's parent in > __init__, but is there a built in way in Python to say "You, Parent > Object, do ...stuff!" > > Thanks! > I guess it's a parent in the inheritance meaning of the term. If so, you can use either the call-by-class syntax or the `super` construct. For the call-by-class, see the Python tutorial, chapter 9.5 "Inheritance", last paragraph. For the `super` construct, check the help on the subject, and the document "Unifying types and classes in Python 2.2" by the BDFL (http://www.python.org/2.2.3/descrintro.html) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: > I asked to keep it simple! Anyway, ill try Dive into Python, thanks > It is simple, merely explicit and with some details. -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing a class, please help...
Jorgen Grahn wrote: > You are rude to an obvious newbie here ... please keep in mind that today's > stupid newbies are tomorrow's Python professionals. > I didn't mean to be rude and apologize if that's the way it came out. > Maybe he /is/ running Jython and failed to explain that properly? > No, he explicitely stated that he's using Python 2.4 (I'm pretty sure Jython's latest release is 2.1) and SPE (which didn't handle Jython last time I tried it) > If I > understand things correctly, jar files are not tied to Java but to the java > bytecode format -- which Java and Jython share. > Yes, it's used to store/package compiled java classes (.class bytecode files) and various metadata associated to the classes (resources, ...) and therefore tied to the bytecode (or the JVM) indeed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: >> parse the expression, extract the operands and the operation, apply the > operation to the operands > > How? Give me some example code, but please keep it simple. > >> are you trying to code a calculator? > > Not intending to, just trying to learn Python. Suppose what i'm trying > to code is a but like a CLI calculator, but i'm just writing it for my > own educational beifits. > Side note: have you read Dive into Python (http://diveintopython.org/) yet? If you haven't -- and are done reading the whole python tutorial -- you should, it's a very good and practical read. Now about the calculator, let's do a simple RPN notation (they're much simpler to compute than the "regular" notation, see http://en.wikipedia.org/wiki/RPN for some informations about RPN) First, we need an input --> expression = raw_input("> ") <-- Now we need to handle this input. An RPN expression is a space-separated list of tokens, these tokens being either operands (numbers) or operations. This means that we merely need to split our expression at the spaces --> expression = raw_input("> ") tokens = expression.split() # split a string using spaces as default split delimiter <-- Now we have a list of tokens. RPN calculations involve a stack, to keep the current operands. Python's `list` has everything you need to emulate a stack --> expression = raw_input("> ") tokens = expression.split() # split a string using spaces as default split delimiter stack = list() <-- Now, we have to handle each token. Either a token is a number (an operand), in which case we have to convert it to an integer (it's currently stored as a string), or it's an operation, in which case we have to apply the operation on the last two tokens of the computation stack and store the result back on the stack. This means that we have to store addition, substraction, multiplication and division. Luckily, there is the python module `operator` that stores an accessor to these operations (add, sub, mul, div). We could store them in a dictionary with an operation token as index: we feed the operation token to the dict, it outputs the operation function. --> import operator operations = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div } expression = raw_input("> ") tokens = expression.split() # split a string using spaces as default split delimiter stack = list() <-- Good, now all we need to know is to feed each token to the `operations` dict, let's try with the first token of the RPN expression "1 2 + 4 * 3 +" >>> operations['1'] Traceback (most recent call last): File "", line 1, in -toplevel- operations['1'] KeyError: '1' Well, there is no "1" key in our dictionary, so we get an error. Kind of obvious. The Python dictionaries also have a "get" method that takes a key and a value, and they return the value (default) if the key doesn't exist, how would that one fare? >>> operations.get('1',None) >>> operations.get('2',None) >>> operations.get('+',None) >>> Ok, it's return the operation function if it knows the token we feed it, and "None" if it doesn't. Now all we have to do is check if it returns None, and if it does we know it's an operand and not an operation. First we need to loop on the list of tokens: --> import operator operations = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div } expression = raw_input("> ") tokens = expression.split() # split a string using spaces as default split delimiter stack = list() for token in tokens: operation = operations.get(token, None) if operation: # If operation is not "None", therefore if the token was an operation token pass # do nothing for now else: # if operation is "None" == if the token is an operand token pass # do nothing either <-- Ok, what are we supposed to do if the token is an operand? Convert the operand (token) to an integer (the token is a string), and then add it to our computational stack. The last part is done via the `append` methods of Python's list. If the token is an operation, we have to apply the operation to the last two operands of the stack, and push the result back on the stack To get the last operation of a Python list, we use the `pop`method, it defaults to returning the last value of a list. --> import operator operations = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div } expression = raw_input("> ") tokens = expression.split() # split a string using spaces as default split delimiter stack = list() for token in tokens: operation = operations.get(token, None) if operation: # If operation is not "None", therefore if the token was an operation token result = operation(stack.pop(), stack.pop()) # apply the operation on the last two items of the stack stack.append(result) # put the result back on the stack
Re: Learning Python
Byte wrote: > Assumption. Im also new to programing, so could do something stupid > like think a Windows path is a command/input/etc. (really, ive done > things like that before.) > Don't assume anything when you have no reason to, and especially don't assume that a cross-platform programming language behaves differently from a platform to another, especially on built-in basic functions > Now, im running this on a terminal, but am acctually writing my scripts > in a text editor. How can I get a script to do a sum with the editor? > e.g. it asks for a sum, then does it etc. > parse the expression, extract the operands and the operation, apply the operation to the operands (are you trying to code a calculator?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: > http://docs.python.org/tut/node6.html#SECTION00610 > --> >>> x = int(raw_input("Please enter an integer: ")) <-- Unless my eyes fail me, it's written "int", not "input", the goal of this line is to convert the return value of raw_input (a string) into an integer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: > p.s. Xavier Morel, you seem to be using Windows, not Linux > I don't see how this may even remotely be relevant, Python is cross platform and (mostly) works the same regardless of the OS > I got > the idea of stacking input on a raw_input from the official Python > Tutorial. > Reference please, I never saw that anywhere in the tutorial -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
Byte wrote: > x = input(raw_input("Please enter your name: ")) > if x==myself: print 'OK' > > It kinda works - I can get to the please enter your name bit but then > it simply reprints your input as output. Someone please HELP! > --> C:\>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(input) Help on built-in function input in module __builtin__: input(...) input([prompt]) -> value Equivalent to eval(raw_input(prompt)). >>> help(raw_input) Help on built-in function raw_input in module __builtin__: raw_input(...) raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. <-- Where the hell did you get the idea of stacking input on a raw_input in the first place? -- http://mail.python.org/mailman/listinfo/python-list
Re: Importing a class, please help...
anon wrote: > Would somebody please drop me a hint, please? > Yeah, the definition of "JAR" is Java ARchive, why the hell would a Python script be able to read a JAR in the first place (truth is it is, a JAR file is nothing but a renamed ZIP, therefore the zipfile module allows you to read it's content) and -- more importantly -- import Java classes. Notice the difference between *Python* script and *Java* class? That's because they're two different languages. If you want to use Java classes and modules in a Pythonic context, you want Jython (http://www.jython.org/) not Python (http://www.python.org/) -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
Scott David Daniels wrote: > pyluke wrote: >> I'm parsing LaTeX document and want to find lines with equations blocked >> by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]" >> so, in short, I was to match "\[" but not "\\]" I've tried: >> check_eq = re.compile('(?!\%\s*)\[') > > check_eq.search(line) > > this works in finding the "\[" but also the "\\[" > > If you are parsing with regular expressions, you are running a marathon. > If you are doing regular expressions without raw strings, you are running > a marathon barefoot. > > Notice: len('(?!\%\s*)\[') == 13 > len(r'(?!\%\s*)\[') == 15 > >> so I would think this would work >> check_eq = re.compile('(?![\%\s*])\[') >> check_eq.search(line) >> >> but it doesn't. Any tips? > Give us examples that should work and that should not (test cases), > and the proper results of those tests. Don't make people trying to > help you guess about anything you know. > > --Scott David Daniels > [EMAIL PROTECTED] To add to what scott said, two advices: 1. Use Kodos, it's a RE debugger and an extremely fine tool to generate your regular expressions. 2. Read the module's documentation. Several time. In your case read the "negative lookbehind assertion" part "(?http://mail.python.org/mailman/listinfo/python-list
Re: Python on Windows
Grant Edwards wrote: > Definitely. Nobody does single .exe file windows programs > anymore. A single-file installer is almost as easy. > uTorrent, Process Explorer or Media Player Classic are single .exe windows programs. Granted, most of them are under-150kb-works-of-arts, but MPC isn't (well it's a work of art, but it's well over 5Mb now), but even then, some people STILL do single .exe windows programs, and some of these are the best programs in their fields (utorrent certainly is one of the best Torrent programs on windows, and it clearly has the very best features/exe size and features/ram consumption ratios, and I haven't seen anything that could even remotely close on to Process Explorer, RegMon or FileMon) -- http://mail.python.org/mailman/listinfo/python-list
Re: classmethod and instance method
[EMAIL PROTECTED] wrote: > Yes that's better. Didn't know about the __class__ attribute. I > thought there must be a way to access this but couldn't find it in the > docs. > > Thanks, > > Andy > dir(), help() and the interactive interpreter (IDLE or CLI) are your best friends. Any time you wonder what an object does, or if you do something to an object, fire the interpreter, create your object, abuse it via dir/help/whatever, and then use dir/help/whatever on the results of dir'ing your object. Oh, and use new style classes too (explicitly inherit from `object` or a built-in type), they are much more flexible and interesting than old-style classes >>> class Test: # old style class pass >>> test = Test() >>> dir(test) # are completely uninteresting ['__doc__', '__module__'] >>> class Test(object): # new style classes on the other hand pass >>> test = Test() >>> dir(test) # have 2500% more sexyness ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__'] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Windows
Simon Faulkner wrote: > I've just written my first (simple) WxPython program - yy! > > What would folks suggest is the easiest way to package it to run on > other windows PCs? > > I would love a single .exe file that would run without ANY OTHER FILES > even if it was 50 Mb! > > TIA > > > Simon Py2Exe -- http://mail.python.org/mailman/listinfo/python-list
Re: classmethod and instance method
[EMAIL PROTECTED] wrote: > Hi, > > I'm trying to write a method that needs to know both the class name and > the instance details > > Any suggestions? > What's the point of using a classmethod and an explicit cls argument when you can get the class object from the instance itself? >>> class Test(object): def meth(self): print self print self.__class__ print type(self) >>> test = Test() >>> test.meth() <__main__.Test object at 0x00FA1710> >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Steven Watanabe wrote: > I know that the standard idioms for clearing a list are: > > (1) mylist[:] = [] > (2) del mylist[:] > > I guess I'm not in the "slicing frame of mind", as someone put it, but > can someone explain what the difference is between these and: > > (3) mylist = [] > > Why are (1) and (2) preferred? I think the first two are changing the > list in-place, but why is that better? Isn't the end result the same? > > Thanks in advance. > -- > Steven. The solution (1) and (2) clear the content of the list (replace the content of the list by an empty list for (1), or delete the content of the list for (2) while the solution (3) creates a new list and binds the old name to the new list. This means that you don't actually modify (clear) the initial list. Just try it out: >>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b = a >>> b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> c = a >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> a.append(10) # assert that a, b and c point to the same list >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> b = [] >>> b [] >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> del c[:] >>> c [] >>> a [] >>> Here we can see that using method (3) on b didn't modify the content of a (even though we asserted that they were the same list). Using method (2) on c, the other hand, did modify the content of a. This is because method (3) on b actually created a new list and bound "b" (as a name) to that new list, without modifying the list "b" used to be bound to (which is the one "a" and "c" are still bound to). -- http://mail.python.org/mailman/listinfo/python-list
Re: Decoupling the version of the file from the name of the module.
[EMAIL PROTECTED] wrote: > Now suppose I have make a new version with __version__ = 1.1. What > shall I call this file and (I don't want to overwrite the old file if I > need to go back to it) how do I import it from the shell. Your advice > sounds nice, but I would appreciate if you could give me (or point me > to) a simple example. > > Thanks > As Kirk, Roy and Peter suggested (nay, commanded), use a versioning system, either CVS or Subversion for example (both are quite simple, Subversion has a 1 click installer for Windows boxes, and there is a small book/user manual with it so that you're not lost), they'll do what you need (keep the old versions around "just in case") and much more to boot. Spending a day or two learning about how the versioning system you'll have chosen work is an investment that you'll get back tenfold in no time, so don't get intimidated or scared. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decoupling the version of the file from the name of the module.
[EMAIL PROTECTED] wrote: > I'm a newbie experimenting with Python. I want to incrementally develop > a module called 'circle'. The problem is now that the file name is used > for two purposes. To keep track of the version number and as the name > for the module. So when I develop the first version of my file I have > to call it circle_a.py. The name of the module then automatically > becomes circle_a. But when I develop the next increment and call my > file circle_b.py the module name changes as well. > > Basically I want to decouple the version of my file from the name of > the module. > > Is there a *simple* way out of this dilemma. > You have two choices: 1- Just get rid of the version number in the name (what's the point) and define a __version__ attribute in the module, that's what is usually done. 2- create a wrapper module called "circle.py" whose content will be something along the lines of "from your_current_module_with_version import *" I'd strongly suggest the first choice, there is no point in giving the version number into the file name of a module. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting date to milliseconds since 1-1-70
NateM wrote: > Thank you! If I am reading in dates as strings from a text file, like > "5/11/1998", how do I convert that to a format I can pass into mktime? > Thanks again. > Check time.strptime() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate graphics dynamically on the web using Python CGI script?
Steve Holden wrote: > Luiz Geron wrote: >> I don't have experience on this, but I think that you can make the >> script return the image "contents" directly to the img tag, without >> passing it to a img file, so you can use something like this: >> >> >> >> wich saves some processing and I/O. >> > No it doesn't, because the script that generates the graphic is then a > different script from the one that generates the referring HTML. I agree > that scripted generation of the graphical content is a viable option > that I overlooked, though it seems from the OP's inquiry that he already > uses CGI to generate the HTML. > > regards > Steve Generate inline base64 encoded images in your HTML page and you're done. (yes, this is ugly, but it generates both HTML and graphics in the same script) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to generate graphics dynamically on the web using Python CGI script?
Steve Holden wrote: > Debashis Dey wrote: >> Hello, >> >> I have a python CGI program. I would like to show a graph within a HTML >> plage. I would like to dynamically generate the graph using the python >> CGI script on the web server side and send it to the browser. >> >> My question is how can I do this in python? Is there a free tool to do >> this? Can someone please send me some simple python code to draw simple >> graphics within HTML (e.g. draw a line or a circle). >> > Unfortunately HTML does not include graphics facilities, simply the > ability to refer to graphical resources. > > The typical way to include a created graphic would be: > > 1. Create a (.png, .jpg, .gif) file showing the > image you want > > 2. Store it in a temporary file whose name will be > unique to the current session > > 3. Generate an HTML response including an > tag referring to the newly created graphic > > Step 1, which is what you seem to be asking about, can be handled by a > number of packages, perhaps the best-known of which is PIL, the Python > Imaging Library - see > >http://www.pythonware.com/products/pil/ > > This is open source, and available at no cost. There's a wealth of > information on how to use it on the web, and many regular readers of > this group are skilled with it! > > regards > Steve Well, some people have been crazy enough lately to generate more or less imageless bar graphs though, see Eric Meyer's "Bar Graphs with Style" (http://meyerweb.com/eric/thoughts/2005/12/20/bar-graphs-with-style/) for more informations on the subject (http://meyerweb.com/eric/css/edge/bargraph/demo.html for a demo) -- http://mail.python.org/mailman/listinfo/python-list
Re: Arithmetic sequences in Python
Paul Rubin wrote: > I don't think this is a valid objection. Python is already full of > syntactic sugar like indentation-based block structure, infix > operators, statements with keyword-dependent syntax, etc. It's that > very sugar that attracts programmers to Python away from comparatively > sugarless languages like Scheme. Indeed, Python is considered by many > to be a sweet language to program in, and they mean that in a nice > way. > > If you want, you can think of it as "flavor" rather than "sugar". We > aren't after syntactic minimalism or we'd be using Scheme. The > criterion for adding something like this to Python should be whether > makes the language taste better or not. I don't know, most of the syntactic sugar I see in Python brings something to the language, or trivialize the generation of structures and constructs that may be complex or awkward without it, it has a natural, honey-ish sweetness full of flavor, it does not taste like some cancer-spawning artificial sweetener ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: forced spaces when inserting a variable between strings
mjteigen wrote: > I'm very new at Python, but have been trying it in conjunction with > CGI. I've encountered a problem that I'm pretty sure is a trivial one, > but I don't know enough Python to work it out. Here's an example. > Imagine that I have a file named "5.jpg" in the same directory as this > Python script: > >print "content-type: text/html\n" >number = 5 >print "" > > My goal is print out ''. However, when I view the > source on the generated html page, I see this: > > > > In other words, that "5" has a space tacked on either side of it, and > of course a browser can't find the file. Is there a way I can avoid the > tacking of spaces on either side of a variable inserted between two > strings? > > TIA :-) > -- > m j teigen > 1- Use sys.stdout.write(), it doesn't add any kind of formatting to the data 2- You may also use string interpolation, either in sys.stdout.write or in print 3- I'd suggest you to use a templating system in order to separate the displayed data and the retrieval/computations of said data, and prevent from mixing logic and presentation in your scripts (which always leads to an unmaintainable system) -- http://mail.python.org/mailman/listinfo/python-list
Re: Arithmetic sequences in Python
Steven D'Aprano wrote: > On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote: > >> For those who'd need the (0..n-1) behavior, Ruby features something that >> I find quite elegant (if not perfectly obvious at first), (first..last) >> provides a range from first to last with both boundaries included, but >> (first...last) (notice the 3 periods) > > No, no I didn't. > > Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately > uses a simple, consistent system of indexing from the start to one past > the end specifically to help prevent signpost errors, and now some folks > want to undermine that. > > *shakes head in amazement* > > Steven, I never said that Python should use this syntax, I merely showed how it was done in Ruby. It's nothing more than a ... basis of discussion... not a "I want that !!ONE" post (if I did, i'd be using Ruby and posting on c.l.r) (and you didn't what by the way?) Ok scratch that, you didn't notice the 3 periods. -- http://mail.python.org/mailman/listinfo/python-list
Re: Arithmetic sequences in Python
Steven D'Aprano wrote: > On Mon, 16 Jan 2006 12:51:58 +0100, Xavier Morel wrote: > >> For those who'd need the (0..n-1) behavior, Ruby features something that >> I find quite elegant (if not perfectly obvious at first), (first..last) >> provides a range from first to last with both boundaries included, but >> (first...last) (notice the 3 periods) > > No, no I didn't. > > Sheesh, that just *screams* "Off By One Errors!!!". Python deliberately > uses a simple, consistent system of indexing from the start to one past > the end specifically to help prevent signpost errors, and now some folks > want to undermine that. > > *shakes head in amazement* > > Steven, I never said that Python should use this syntax, I merely showed how it was done in Ruby. It's nothing more than a ... basis of discussion... not a "I want that !!ONE" post (if I did, i'd be using Ruby and posting on c.l.r) (and you didn't what by the way?) -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: excellent book on information theory
Tim Peters wrote: > Non-English translations have real challenges, and because this series > is more popular than the Python Reference Manual these days, there's a > lot of fascinating info to be found. For example, I think the > Japanese translator deserves a Major Award for their heroic attempt to > translate Ron's "Uranus" pun: > >http://www.cjvlang.com/Hpotter/wordplay/uranus.html > The translations of Pratchett's works are also quite amazing feats. I think that when they were looking for a polish translator one of the people they auditioned told them something along the lines of "You can't even think like this in polish." -- http://mail.python.org/mailman/listinfo/python-list
Re: Arithmetic sequences in Python
Paul Rubin wrote: > There's something to be said for that. Should ['a'..'z'] be a list or > a string? To me, the most obvious result would be either a range object as a result, or always a list/generator of objects (to stay perfectly consistent). If a range of numbers translate into a list of numbers, then a range of characters should likewise translate to a list of characters, and a join would be required to get a regular string. This also adds more consistency between the two proposals of the initial post (e.g. list-based range and generator-based range), for while the list-based range could be expanded into a string a generator-based one couldn't/shouldn't, and the abstraction breaks (because two constructs that should be more or less equivalent become extremely different and can't be swapped transparently). This would also be consistent with other languages providing a native "range" object such as Ruby or or Ada ranges. The only thing that bothers me about the initial proposal is that there would not, in fact, be any "range object", but merely a syntactic sugar for list/generator creation. Not that I really mind it, but, well, syntactic sugar for the purpose of syntactic sugar really doesn't bring much to the table. For those who'd need the (0..n-1) behavior, Ruby features something that I find quite elegant (if not perfectly obvious at first), (first..last) provides a range from first to last with both boundaries included, but (first...last) (notice the 3 periods) excludes the end object of the range definition ('a'..'z') is the range from 'a' to 'z' while ('a'...'z') only ranges from 'a' to 'y'). -- http://mail.python.org/mailman/listinfo/python-list
Re: instance attributes not inherited?
John M. Gabriele wrote: > I'm having a hard time finding the documentation to the super() function. > I checked the language reference ( http://docs.python.org/ref/ref.html ) > but didn't find it. Can someone please point me to the relevant docs on > super? > > help( super ) doesn't give much info at all, except that super is actually > a class, and calling it the way we are here returns a "bound super object", > but I don't yet see what that means (though I know what bound methods are). > Super is a bit magic, quite complicated, and some people don't like it (basically, super is mainly to be used in complex inheritance case with diamond shape hierarchies and such, to automate the method resolution order). If you want to give a try at understanding "super", you should read Guido's `Unifying types and classes in Python 2.2`, chapters on MRO, super and cooperative methods (http://www.python.org/2.2.3/descrintro.html#mro) (nb: you may also read the rest of the document, it lists all the magic introduced in the language with 2.2). -- http://mail.python.org/mailman/listinfo/python-list
Re: More than you ever wanted to know about objects [was: Is everything a refrence or isn't it]
Alex Martelli wrote: > Steve Holden <[EMAIL PROTECTED]> wrote: >... >>> 3. If two objects are equal with "==", does that >>> mean their values are the same? >> Almost universally, yes, although if you know enough about how the >> interpreter works "under the hood" you can define the response of >> instances of your own classes to the "==" operator (by defining their >> __eq__ method), and even define a class whose instances aren't equal to >> anything, even to themselves! > > Hmmm... now this may be just be, but I'm quite vary of saying that, > since 1 == 1.0 == 1.0+0j, those three objects's values "are the same". > > "Are equal", sure. But I intuitively see "being the same" as a stronger > condition than "being equal". > One could check use Common Lisp's "=", "eq" and "eql" operators (which respectively check for "being equal" as in "having the same set of values", "being very equal" as in "having the same set of values and the same type" and "being the same" as in being exactly the same object e.g. identity equality) > In mathematics, 1 is not "the same" as 1.0 -- there exists a natural > morphism of integers into reals that _maps_ 1 to 1.0, but they're still > NOT "the same" thing. And similarly for the real-vs-complex case. > I disagree here, 1 and 1.0 are the same mathematical object e.g. 1 (and the same as "1+0i"), the difference due to notation only makes sense in computer science where integers, real and complex ensembles are disjoin. In mathematics, Z is included in IR which is included in C (note: this is not mathspeak, but I have no idea how to say it in english), and this notation -- at best -- merely determines the ensemble you're currently considering. There is no "natural morphism" of integers into reals because there is no mathematical difference between integers and reals, the real ensemble is merely a superset of the integers one. Or so it was last time i got a math course. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a string to an array?
Tim Chase wrote: > The closest hack I could come up with was > > import random > s = "abcdefg" > a = [] > a.extend(s) > random.shuffle(a) > s = "".join(a) > > This lacks the beauty of most python code, and clearly feels like > there's somethign I'm missing. Is there some method or function > I've overlooked that would convert a string to an array with less > song-and-dance? Thanks, > > -tim > Would >>> import random >>> s = "abcdefg" >>> data = list(s) >>> random.shuffle(data) >>> "".join(data) 'bfegacd' >>> fit you better? -- http://mail.python.org/mailman/listinfo/python-list
Re: Freezing
[EMAIL PROTECTED] wrote: > The first line of that example has to be: > > s = |set([1, 3, 5])| > > But I don't know/remember why set() can't accept many values like > max/min: > > max([1,2,5]) > max((1,2,5)) > max(1,2,3) > > Bye, > bearophile > How about just providing a freeze method on `object` (since everything will inherit from object) that can freeze the object? In fact the freeze protocol could provide 2 methods: freeze and frozen, the former would freeze the object in place (e.g. freeze the object it's applied to) while the later would return a frozen copy of the object it's applied to. That way, it could even be used as a const-like parameter to a function (with frozen) Examples: >>> l = [0, 1, 2, 3] >>> l.append(5) >>> l [0, 1, 2, 3, 5] >>> l.frozen() [0, 1, 2, 3, 5] >>> fl = l.frozen() >>> l.append(7) >>> l [0, 1, 2, 3, 5, 7] >>> fl.append(7) Traceback (most recent call last): ... WhateverError: frozen 'list' object cannot modified >>> fl [0, 1, 2, 3, 5] >>> l.freeze() >>> l [0, 1, 2, 3, 5, 7] >>> l.append(9) Traceback (most recent call last): ... WhateverError: frozen 'list' object cannot modified One could even dream of a melt/molten method pair that'd behave at the opposite of the freeze/frozen pair (to have the ability to "unfreeze" an object if needed) No new keyword, no new token, no new structure, no new builtin, same functionalities. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to improve this simple block of code
Forget about the previous mail, i just saw you were converting the string to float beforehand, in which case he would more than likely run into the good ol' float imprecision issue sooner than later. Not to mention that %g formats to scientific notation (e.g. exponential format with the exponent always being a multiple of 3), he'd probably use "%f". -- http://mail.python.org/mailman/listinfo/python-list
Re: how to improve this simple block of code
Mel Wilson wrote: > py wrote: >> Say I have... >> x = "132.00" >> >> but I'd like to display it to be "132" ...dropping the trailing >> zeros... > > print '%g' % (float(x),) > > might work. > > Mel. > The input is a string, %g expects a float, TypeError exception. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problema con le RE....
Alessandro wrote: > Problema con le RE > Ho questa stringa "3 HOURS, 22 MINUTES, and 28 SECONDS" e la devo > 'dividere' nelle sue tre parti "3 HOURS", "22 MINUTES", "28 SECONDS". > La cosa mi viene molto con le RE...(inutile la premessa che sono molto > alle prime armi con RE e Python) > Qesito perchè se eseguo questo codice > > regex=re.compile("[0-9]+ (HOUR|MINUTE|SECOND)") > print regex.findall("22 MINUTE, 3 HOUR, AND 28 SECOND") > ottengo come output: > > ['MINUTE', 'HOUR', 'SECOND'] > > e non come mi aspettavo: > > ['3 MINUTE', '22 HOUR', '28 SECOND'] > > Saluti e grazie mille... > Alessandro > Would probably be slightly easier had you written it in english, but basically the issue is the matching group. A match group is defined by the parenthesis in the regular expression, e.g. your match group is "(HOUR|MINUTE|SECOND)", which means that only that will be returned by a findall. You need to include the number as well, and you can use a non-grouping match for the time (with (?: ) instead of () ) to prevent dirtying your matched groups. >>> pattern = re.compile(r"([0-9]+ (?:HOUR|MINUTE|SECOND))") Other improvements: * \d is a shortcut for "any digit" and is therefore equivalent to [0-9] yet slightly clearer. * You may use the re.I (or re.IGNORECASE) to match both lower and uppercase times * You can easily handle an optional "s" Improved regex: >>> pattern = re.compile(r"(\d+ (?:hour|minute|second)s?)", re.I) >>> pattern.findall("3 HOURS 22 MINUTES 28 SECONDS") ['3 HOURS', '22 MINUTES', '28 SECONDS'] >>> pattern.findall("1 HOUR 22 MINUTES 28 SECONDS") ['1 HOUR', '22 MINUTES', '28 SECONDS'] If you want to learn more about regular expressions, I suggest you to browse and read http://regular-expressions.info/ it's a good source of informations, and use the Kodos software which is a quite good Python regex debugger. -- http://mail.python.org/mailman/listinfo/python-list
Re: Spelling mistakes!
Antoon Pardon wrote: > I don't think unit tests are that helpful in this case. > Unit tests help you in finding out there is a bug, they > don't help that much in tracking down a bug. > > I for some reason a person is reading over the difference > between sumLongName and someLongName and doesn't notice > the different spelling in his source a unit test won't > be of much help. > Since 1- The unit test will obviously fail in this case, telling you in which code unit the issue is 2- Unit Test favor extremely modular coding with very short increments (as a somewhat extreme example, Robert Martin gets nervous if his test suites don't validate the code every 5 minutes, you usually don't write 200 lines and their unit tests in 5 minutes) We can deduce that unit testing will detect the typo extremely early and that the field of research will span about 5 to 10 lines, making the tracking quite easy to perform. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stackless Python
Christian Tismer wrote: > Xavier Morel wrote: > >> Would anyone have more informations about that? It doesn't seem to be an >> issue on my side (since I tried to access the Stackless site from two >> different connections and 3 computers) but I can't rule it out. > > Thanks to Carl Friedrich, I restarted the Zope process. > > I have no idea why it broke, the site was running since 38 days > without problems. The Zope/Plone process was still there, blocking > the port. > > Maybe I should go for something simpler than Plone... > > Don't hesitate to ask on the mailing list for all the things > you will not find on the site. The list works :-) > > ciao - chris Ah yes, much better now, thank you very much (BTW the first time I got a dead stackless.com was between xmas and new year's eve, so the website has probably been down for more than 10 days, just so you know, if you want to check your logs or something). -- http://mail.python.org/mailman/listinfo/python-list
Stackless Python
Some time ago, I finally decided to check what Stackless was (exactly) and which were the theorical concepts behind it (continuations and all). I managed to find some documentations and papers, but most if not all of them are related to pre-2.0 Stackless. The issue is, I just can't seem to reach the Stackless website (http://stackless.com). Some specific pages of the site do work (http://stackless.com/spcpaper.htm), but the index itself always yields a 502 gateway error. Would anyone have more informations about that? It doesn't seem to be an issue on my side (since I tried to access the Stackless site from two different connections and 3 computers) but I can't rule it out. I should also note that Google is no good in this case as mostly yields fairly old results... -- http://mail.python.org/mailman/listinfo/python-list
Re: python speed
James Tanis wrote: > Quite honestly I've never heard of java being faster than.. well.. > anything. Faster than Python? I really doubt it. Their are several > libraries for game programming specifically as well as opengl, sdl, as > well as several different audio systems/daemons.. I'd suggest browsing > through the categories in python.org's module search engine. > > Disclaimer (:P): The majority of generalizations have some amount of > exceptions, the java crack above was just my opinion - it was not > really intended to offend any java addicts out there (the poor, > miss-guided souls). > While java is much slower than Python in developer-time (e.g. the time it takes to generate a working app, and the number of lines involved), (good) Java code running on the hotspot (JIT) VM is usually at least an order of magnitude faster than the equivalent Python code, if not faster. What's dog slow in Java is primarily the VM startup, and then the memory bloating, but as far as execution speed goes, pure Java code is much faster than pure Python much more often than the opposite (now that may change with Pypy, but Pypy is not done yet) Xavier -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem?
Pierre Barbier de Reuille wrote: > Xavier Morel a écrit : >> Pierre Barbier de Reuille wrote: >> >>> Well, I would even add : don't use super ! >>> Just call the superclass method : >>> >>> MyClass.__init__(self) >>> >>> >>> >>> Simon Percivall a écrit : >>> >>>> Don't use self.__class__, use the name of the class. >>>> >> Bad idea if you're using new-style classes with a complex inheritance >> hierarchy and multiple inheritance. > > As a reference : > > http://fuhm.org/super-harmful/ > > I may say this is the only place I ever saw what "super" *really* is > for. The behavior is far too complex and misthought. All I can say is : > don't use it ! It solves *nothing* and creates too many bugs in the long > run. My own encounter with the subject was Guido's "Unifying types and classes in Python 2.2" (http://www.python.org/2.2.3/descrintro.html#mro for the part on super itself), but I'll keep your link close by. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or Java or maybe PHP?
Alex Martelli wrote: > Xavier Morel <[EMAIL PROTECTED]> wrote: >... >> Wouldn't it be possible to change the `def` statement to return a >> reference to the function, and allow omitting the function name thereby >> bypassing the default binding (current behavior)? > > It's _possible_ (doesn't introduce syntax ambiguities) though it does > introduce incompatible interactive-interpreter behavior, as you say: > >> >>> # Extended behavior >> >>> # returns a reference to the function >> >>> def foo(*args, **kwargs): >> pass >> > > This could be avoided if 'def ' remained a statement like > today, and a separate expression 'def' returned a function object > as a result; this would have the aded plus of avoiding the totally new > (to Python) idea of "statement returning a value" (_expressions_ return > a value). > True that, I didn't even consider the possibility to create an independent expression. And it completely remove the possibility to generate the first "con". >> * May allow for blocks-like constructs (I'm not sure of the current >> state of the closures over Python functions though, these may have to be >> extended to "full" closures if they aren't) and be considered by some as > > Python's closures are 'full', but don't allow inner functions to rebind > names in the namespace of outer functions. > > I'm not sure a PEP like this has ever been proposed, but the idea of > anonymous def is not new (bar some details of your proposal): if a PEP > doesn't exist, you could write one, at least to firm up all details. > > > Alex Or maybe start by creating a thread on the subject of an anonymous def expression on this list first? -- http://mail.python.org/mailman/listinfo/python-list
Re: Translate this to python?
Heiko Wundram wrote: > Xavier Morel wrote: >> I think that xrange is also soon-to-be deprecated (xrange eats a little >> less memory and is slightly faster to _create_, but much slower to >> _iterate over_ than range) > > It might be slower to iterate using xrange, but xrange certainly has its > place in Python... Try the following on your computer: > > for x in range(10**10): > print x > > for x in xrange(10**10): > print x > > Tell me which one doesn't overflow your memory. ;-) And before you come > telling me that these constraints are articial, I've _written_ programs > that had to iterate over 2**24 (the set of 10.* IP addresses), and I most > certainly wouldn't have wanted the machines to contain 384+ MB of RAM just > to store the number objects that range creates. > > --- Heiko. While xrange does have it's place in Python, it has very few actual uses (yours being one of the few), and is usually more harmful than beneficial. While the deprecation of xrange is not that "soon", it is part of the Python 3000 PEP (http://www.python.org/peps/pep-3000.html#id38) along with the deprecation of most FP-facilities of Python (filter, map, reduce). It should also be noted that reimplementing xrange when needed is trivial and can be done with a 5-lines generator for the minimal version (1 argument, 0-n range) and probably less than 10 lines for the full blown version equivalent to the current one (including start, end and step arguments) -- http://mail.python.org/mailman/listinfo/python-list
Re: Spelling mistakes!
KraftDiner wrote: > I've spent hours trying to find a bug that was a simple spelling > mistake. > > in an init method I declare a variable self.someLongName > > later in a different method of the class I use > self.sumLongName > Now I really meant self.someLongName. > In fact I don't want a variable called sumLongName. > Frankly how are you ever to know if this type of error is occuring? > PyChecker and PyLint sound like the perfect remedy to this issue (I know one of them is able to warn you if you *create* an attribute outside of __init__, maybe both are but at least one of them is) I just run them when I save my files, they don't take long and even though the default configuration is *extremely* annoying (especially PyLint's, it generates heaps of warnings) once configured to one's need, they're extremely valuable for both personal and team development. -- http://mail.python.org/mailman/listinfo/python-list
Re: - E04 - Leadership! Google, Guido van Rossum, PSF
Ilias Lazaridis wrote: > I estimate that there is a "unfreeze" operation, too - which would lead > to flexibity. > There is none, you have to make a copy of the object via the "dup" (duplicate) method to get an unfrozen copy (note: clone yields an exact copy, which means that it's still frozen). Unfreezing an object is forbidden in Ruby. Alex Martelli wrote: > At the other extreme, Ruby's very productive choice is to > allow freeze and unfreeze of everything (I believe -- but you should > double check with a Ruby expert) I'm no ruby expert, but I'm pretty sure there is no way to unfreeze a frozen ruby object, you *have* to create a molten copy with the "dup" method. Ilias Lazaridis wrote: > Alex Martelli wrote: >> Ilias Lazaridis <[EMAIL PROTECTED]> wrote: > [...] - google stuff > >>> http://lazaridis.com/case/lang/python.html#simple_variable_access >>> >>> this leads to a new limitation: >>> >>> "#LIMITATION: large amount of repetitive code" >> One normally does not define large numbers of identical accessors (there > [...] - (extensive elaboration) > > possibly one can provide the code for something similar to the ruby > attr_accessor: > > class Talker >def sayHello > puts "Hello world" >end > >attr_accessor :name, :age > > end > > thus they can later be accessed this way > > john.age = 19 > > print john.age > There is no point, these exist because a ruby attribute can *never* be accessed from outside the object, a Ruby attribute is always private while a Python attribute is always public. This means that you *have to* declare properties to have the ability to access an attribute of a Ruby object, which lead to attr_accessor, attr_reader and attr_writer as shortcut-declarations of basic properties. The Pythonic equivalent of Ruby's attr_accessor is merely to do nothing, because what the attr_accessor does is: attr_accessor :something generates def something @something end def something= value @something = value end but not doing it would prevent any access to the "something" attribute. (attr_reader only declares the getter method, making the attribute read-only, and attr_writer only defines the setter, making the attribute write-only) One thing that is very important is that in Ruby you *never* deal with member attributes from outside the object, only methods (messages to the object). In Python, you deal either with methods (messages) or attributes (datas), but these attributes can be either "real" attributes (real unchecked data) or properties, e.g. virtual attributes (that may generate side-effects, sanity check on the data, or _may not map to any existing unique data in the object_) and unless you really try to, you don't have any way to distinguish a "real" attribute from a property ("virtual" attribute), and you don't care. > > thus if I make a typo, I create a new attribute? > Why yes of course, what were you expecting? -- http://mail.python.org/mailman/listinfo/python-list
Re: inline function call
Peter Hansen wrote: > Riko, any chance you could post the final code and a bit more detail on > exactly how much Psyco contributed to the speedup? The former would be > educational for all of us, while I'm personally very curious about the > latter because my limited attempts to use Psyco in the past have > resulted in speedups on the order of only 20% or so. (I blame my > particular application, not Psyco per se, but I'd be happy to see a > real-world case where Psyco gave a much bigger boost.) > > Thanks, > -Peter > Someone I know created an application to compute Markus Lyapunov fractals (aka heavy mathematical computations) (he pretty much did it to learn Python). Last time I checked, his code ran in roughly 3 minutes (179s) on my box (Athlon64/3000+) without psyco and 46 seconds with psyco enabled under Windows 2000. Someone else got respectively 2mn34s and 13s (without and with psyco) on a Linux box with an Athlon XP 2600+ (same frequency as my 3200+ btw, 2GHz). My tests show a 74% speedup, and the Linux test shows a 91% speedup. In any case, the gain is significant because the actual code is very short (less than 200 lines, and the algorithm itself fits in under 50 lines) and is called very often (from my notes, the main function is called 16 times during the computation of the fractal) -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem?
Pierre Barbier de Reuille wrote: > Well, I would even add : don't use super ! > Just call the superclass method : > > MyClass.__init__(self) > > > > Simon Percivall a écrit : >> Don't use self.__class__, use the name of the class. >> Bad idea if you're using new-style classes with a complex inheritance hierarchy and multiple inheritance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Translate this to python?
[EMAIL PROTECTED] wrote: > For some reason, ocassionally when I see xrange, I think "But wasn't > that deprecated since range is now a . . oh wait that's xreadlines". > xrange is a cool thing the few times where you really need it. > > john > >> Not sure what i is really for, but j seems to be independent, >> so perhaps (also untested, and caveat: it's past bedtime) >> >> i = nPoints - 1 >> for j in xrange(nPoints): >> # whatever >> i = j >> >> Regards, >> Bengt Richter > I think that xrange is also soon-to-be deprecated (xrange eats a little less memory and is slightly faster to _create_, but much slower to _iterate over_ than range) -- http://mail.python.org/mailman/listinfo/python-list
Re: One-step multiples list generation?
Damien Wyart wrote: > Thanks for these important and useful additions, they are very welcome ! > > In writing my answer I had immutables in mind, but mutables are a bit > more dangerous, here... > Not *that* much though. The first construct can't be used, but he can use >>> [copy.copy(Foo) for _ in range(20)] And he should be ok. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python or Java or maybe PHP?
Mike Meyer wrote: > That doesn't sounds like "hates" to me. More like "doesn't like the > baggage." > > >> # Current behavior >>> def foo(*args, **kwargs): pass >>> print foo >>> # Extended behavior >>> # returns a reference to the function >>> def foo(*args, **kwargs): pass >>> >>> # Anonymous functions >>> def (*args, **kwargs): pass >>> foo = def(*args, **kwargs): pass Note that the function wouldn't "have" it's own name anymore (no more "__name__" attribute? Or a blank one?) Since functions can already be defined inline, the only thing that'd be left would be to end the function's definition when the "wrapper" structure ends: >>> doSomething(def (*args, **kwargs): pass, arg) # End of the function definition at the end of it's argument >>> doSomethingElse(def (*args, **kwargs): ... # Multiline ... pass ...) I'm not too sure about the multi line version (and it looks very ugly with a non-monospaced font), but: Pros (I think): * Backwards-compatible (I think, since the new uses of `def` are currently errors) * Fairly obvious syntax * No `lambda` or `macros` baggage, the new form of def would merely define an anonymous function instead of a named one. * No new keyword, or structure, or idiom * Existing idioms are merely slightly extended without changing their current meaning Cons: * May reduce readability when misused, and may be used in Very Stupid Ways that reduce readability a lot (but then again most construct may be abused in some way), e.g.: doSomething(arg1, arg2, arg3, def foo(a): manipulate(a)) # binds a function to `foo` _and_ sends it to `doSomething` ... [a few lines of code] ... foo(value) # where the hell did that "foo" come from? * Replaces lambdas with something much more powerful, which may go against the goal of getting rid of lambdas (unless the aforementioned goal is mostly because of the historical baggage of lambdas/macros) Unsure: * Shows that Python is the Ultimate Language, people are not ready yet. * May allow for blocks-like constructs (I'm not sure of the current state of the closures over Python functions though, these may have to be extended to "full" closures if they aren't) and be considered by some as yielding to the hype (even though the structure itself is more or less 35 years old) -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] - Requesting Comments for Process Definition and Presentation
Ilias Lazaridis wrote: > b) to retrieve feedback subjecting the Process Definition itself > (content of diagramms, clarity, terminology etc.) > This is a lie, and you know it. You are merely some kind of strange troll. You've built something that you consider the only "object model" worth using within your mind and proceed to try bashing OO languages such as Py or Ruby because they don't fit your own object model and terminology. No one in either c.l.p or c.l.r need you, no one wants your object model, no one wants your so-called evaluations (especially about the community leaders, your various comments about both Guido van Rossum and Yukihiro "Matz" Matsumoto are insulting and disrespectful), please do everyone a favor: create your damn own language, or head over to comp.lang.lisp and implement your object model in this language, Lisp is a meta-language and _nothing_ stops you from heading over and creating a new object model from scratch (that's been done countless times anyway, and the CLOS probably wouldn't fit your personal object model, so go ahead). The fact is that you don't live in reality, you generate more buzzwords and empty acronyms than a well-trained marketroid, but guess what? that doesn't matter, unless you can prove that what you advocate _works_. And you can't. Both Ruby's object model and Py's object models work. They have flaws, they evolve, they grow and change, but they work, they are used in real world situations and they fit the needs of their respective communities. "Ilias Lazaridis Majic Object Model" doesn't. Period. Just stop posting altogether, implement your damn blasted object model (or try to) in an existing language or create a new language to implement it and just leave us. And stop spamming your damn worthless website too. Thank you very much. >> I can't see anything at this site what would make sense to me. > > you mean, you don't understand _anything_? > No, he means that your website just doesn't make sense. There is no purpose, no consistency, no way to understand what the website is supposed to hold, no way to find *informations* (and your colorful graphs with an informative level of somewhere below 0 do not count as information BTW). I'll add that the color/style schemes are awfully misleading (why the hell are random words in bold-ocre, please go read a few books on interfaces and websites creation because you obviously don't have a clue there, Steve Krug's "Don't Make Me Think" would be a much required start), that the various categories are unclear, fuzzy and *never explained anywhere* and that you claiming that you can *review websites* (for a fee on top of that) is insulting to people with actual skills in the field. -- http://mail.python.org/mailman/listinfo/python-list
Re: Try Python update
Mike Meyer wrote: > After spending time I should have been sleeping working on it, the try > python site is much more functional. It now allows statements, > including multi-line statements and expressions. You can't create code > objects yet, so it's still more a programmable calculator than > anything real. > > I've got some of the tutorial text (literally) up as well. I hope to > make it easier to read the tutorial and interact with python at the > same time in the near future. > > The url is http://www.mired.org/home/mwm/try_python/. Reports of > problems would appreciated. > > If you want to try an online P{ython tool that lets you save code, try > Devan L's at http://www.datamech.com/devan/trypython/trypython.py. > > http://mail.python.org/mailman/listinfo/python-list
Re: When Python *Eggs* better than Python *distutils*?? What's Eggs?
[EMAIL PROTECTED] wrote: > So basically Python Eggs precompiles and compresses > binaries for you so you just have to load it to run > your app? > Nah, Eggs is a packaging system, what you don't have to do is compile/configure, because the packaging does that for you. It also handles things like pre-required packages (the packages that this package uses), even though that doesn't always work atm. If you ever used a debian-based linux system, think of Eggs as a Python-specific apt-get. The most advanced kind of language-specific installer atm is the Ruby Gems packaging and distribution system (http://docs.rubygems.org/), go check it for more insight of what Eggs wants to be (and I hope it'll evolve to be as good as gems) (and the install software should be named eggs or hatch, not easy_install, ugly). -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you pass functions as arguments?
[EMAIL PROTECTED] wrote: > I want to calculate f(0) + f(1) + ...+ f(100) over some function f > which I can change. So I would like to create a function taking f as > argument giving back the sum. How do you do that in Python? > Python functions (and classes, and modules) are first-class objects, so you can use them as regular objects: send them as arguments, generate and return them from functions, ... BTW, if your goal is to create that kind of sums of function results, I think you'd be interested in using both Python's _generators_ and the built-in function *sum*. -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlopen
JabaPyth wrote: > Hello, > I'm trying to use the urllib module, but when i try urllib.urlopen, it > gives me a socket error: > > >>import urllib > >>print urllib.urlopen('http://www.google.com/').read() > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\urllib.py", line 77, in urlopen > return opener.open(url) > File "C:\Python24\lib\urllib.py", line 180, in open > return getattr(self, name)(url) > File "C:\Python24\lib\urllib.py", line 296, in open_http > h.endheaders() > File "C:\Python24\lib\httplib.py", line 794, in endheaders > self._send_output() > File "C:\Python24\lib\httplib.py", line 675, in _send_output > self.send(msg) > File "C:\Python24\lib\httplib.py", line 642, in send > self.connect() > File "C:\Python24\lib\httplib.py", line 610, in connect > socket.SOCK_STREAM): > IOError: [Errno socket error] (11001, 'getaddrinfo failed') > > Any ideas on what i did wrong? > Works for me, do you have a proxy or some strange setup for accessing to the web? Try using the urllib2 module, too. -- http://mail.python.org/mailman/listinfo/python-list
Re: RoR like (was : SPE 0.8.1.b Python IDE...)
Adrian Holovaty wrote: > bruno at modulix wrote: >> RoR is not an IDE, it's a web framework. The closest things in Python >> are TurboGears (good Ajax/js support via Mochikit), Subway (never >> tested), and Django (no Ajax support AFAIK). > > Note that "no Ajax support" is misleading. Of course you can use Ajax > with Django, just as you can use it with *any* Web framework. That's > because Ajax is a browser-side technology (JavaScript), not a > server-side technology (Python). Django is just as capable of producing > JavaScript as it is of producing (X)HTML or whatever else. > > Hope that clears things up! > > Adrian > The so-called Ajax, standing for Asynchronous Javascript + XML is NOT a "browser-side technology", it's a bunch of technologies used together in a client-server environment. If you only use Javascript without communicating with any server, you're not using the so-called Ajax, you're merely using Javascript (not that it's a bad thing, mind you). Please refer to the article that started the hype (http://www.adaptivepath.com/publications/essays/archives/000385.php) for more insight about what Ajax is (or is supposed to be). An ajax-integrating framework would therefore be a framework that could generate both the client-side javascript and the server-side variations of the resources that can be called, retrieved and used by the client in a seamless and transparent way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuples
Tuvas wrote: > Let's say I make a program something like follows: > > x=[] > x.append([1,2,3]) > x.append([4,5,6]) > print x > print x[0] > print x[0][1] > x[0][1]=5 > > Okay, everything works here as expected except the last line. Why won't > this work? Thanks for the help! > Works for me, do you have more informations? >>> x = list() >>> x.append([1,2,3]) >>> x.append([4,5,6]) >>> print x [[1, 2, 3], [4, 5, 6]] >>> print x[0] [1, 2, 3] >>> print x[0][1] 2 >>> x[0][1] = 5 >>> print x[0][1] 5 >>> Now if you're really using tuples, that last line won't work because tuples are immutable e.g. you can't modify a tuple's elements after the tuple's creation >>> y = list() >>> y.append((1,2,3)) >>> y.append((4,5,6)) >>> print y [(1, 2, 3), (4, 5, 6)] >>> print y[0] (1, 2, 3) >>> print y[0][1] 2 >>> y[0][1] = 5 Traceback (most recent call last): File "", line 1, in -toplevel- y[0][1] = 5 TypeError: object does not support item assignment >>> And the reason is explicitly stated (tuples don't support item assignment) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why and how "there is only one way to do something"?
Aahz wrote: > In article <[EMAIL PROTECTED]>, > Steve Holden <[EMAIL PROTECTED]> wrote: >> (Part of) Python's credo (which you can read in context by typing >> >> import this >> >> at an interactive command prompt) is "There should be one (and >> preferably only one) way to do it". > > Actually, I've gotten used to doing > > python -c 'import this' Which can be built even more easily with $ python -m this (no quotes needed btw) It's usually useful to pipe it through grep too, in order to get only the piece of zen knowledge you need. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I load python script into Html ??
PatPoul wrote: > I want to do the same thing as > > > but with a python script : > > > == > if xxx.py : > def mytest(): > alert("test") > window.document.write('test') > == > and test.html : > > > > > mytest() > > > == > > I always got this error : > NameError : name 'mytest' is not defined > > Thx ... > Patrick Poulin > Long story short, no. The browser needs binding to the language, and either the ability to use the external interpreter or embed an interpreter, and no browser currently has that kind of thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I load python script into Html ??
Shouldn't have hit the "send" button so fast... Addendum: the script element doesn't have any language attribute, the attribute you're supposed to use is "type" and it takes the MIME type of your script as a value. s/language="javascript"/type="text/javascript"/ -- http://mail.python.org/mailman/listinfo/python-list
Re: IsString
Steven D'Aprano wrote: > name = "spam spam spam spam" > > the value of the variable "name" is a pointer, and not a string. Riiight. > Yes, it's a reference to an object of type string holding the value > def increment(n): > """Add one to the argument changing it in place.""" > # In Pascal, I would need the var keyword to get this behaviour, > # but Python is call by reference so all variables are passed > # by reference. > n += 1 > > x = 1 > increment(x) > assert x == 2 > > but that doesn't work in Python either. > That example is mightily flawed since Python's integers are immutable objects. Here, python creates a new integer object of value "n+1" and binds the _local_ name "n" to this new object. n isn't bound to it's initial object anymore (the one x is bound to), and therefore can't modify it. Now use a mutable type instead of an immutable int and you'll notice a pass-by-reference behavior. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i change the default python?
Koray Bostancı wrote: > Hi all, > > When i type python in terminal it runs the python2.3 interpreter, but i > want to use 2.4 and Python2.4 package is already installed. > > How can i change the default python in my system? I searched google for > a little but couldn't find. > > Using Debian GNU/Linux. > > > koray "python" is usually merely a link on your "main" python distribution (it's the same for many other things, gcc for example). python (and all the python versions) are in /usr/bin for the deb'. To rebind it, just remove the current link $ rm /usr/bin/python then create a new symbolic link to /usr/bin/python2.4 $ ln -s /usr/bin/python2.4 /usr/bin/python (you may have to use *sudo* to perform these operations BTW) Voila, you're done, calling python now starts the python2.4 interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Horribly noobful string question
Fredrik Lundh wrote: > "SeNTry" wrote: > >> My first post here as I just begin to learn programming in general and >> python in particular. I have all the noobie confused questions, but as I >> work thru the tutorials I'm sure I'll find most my answers. >> >> This one is eluding me tho... I am working in the tutorials, writing scripts >> as presented and then modifying and expanding on my own to try to learn. >> I'm working with one that asks the user to 'guess a number I'm thinking', >> and with simple while loop, flow control and operands, returning an answer >> to guess again or you got it. I've added a 'playagain' function I've got >> working, but what I want is to stop the program from crashing when someone >> enters a string value instead of a int value. I know strings are immutable, >> and they can be changed to an int equivalent, but I just want the script to >> recognize the input as a string and print a simple "that's not a number, try >> again' type of message. I can't find the syntax to include in the >> if/elif/else block to include a line that says something like, > > assuming you're using raw_input() to get the guess, you always > have a string (in python's sense of that word). > > what you seem to want is to check if the string contains a number > or not. here's one way to do this: > > guess = raw_input("make a guess: ") > if guess == secret: > print "congratulations!" > elif not guess.isdigit(): > print "that's not a number! please guess again!" > ... > that, or just write something like guess = raw_input("Make your guess > ") try: if int(guess) == secret: # ok except ValueError: # no good -- http://mail.python.org/mailman/listinfo/python-list
Re: "0 in [True,False]" returns True
Mike Meyer wrote: > But this isn't necessarilly true: is perfectly legal. > > http://mail.python.org/mailman/listinfo/python-list
Re: IsString
Tom Anderson wrote: > In what sense are the names-bound-to-references-to-objects not variables? > In the sense that a variable has various meta-informations (at least a type) while a Python name has no information. A Python name would be equivalent to a C void pointer, it can mean *any*thing and has no value/meaning by itself, only the object it references has. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is incredible!
Luis M. Gonzalez wrote: > You are not the first lisper who fell inlove with Python... > Check this out: > http://www.paulgraham.com/articles.html > Paul Graham is not in love with Python though, he's still very much in love with Lisp. He merely admits being unfaithful to Lisp from time to time (and clearly states that Python is one of the non-Lisp languages he likes best). -- http://mail.python.org/mailman/listinfo/python-list
Re: Displaying error message in a try except?
Fredrik Lundh wrote: > assuming that "true" means "the message you would get if you hadn't > used a try/except", the traceback module is what you want: > > you can also inspect the exception status via the sys.exc_info() call. > e.g. > There is also the third way of catching an exception explicitly and printing it's arguments and class (doesn't give exactly the same information, but gives relevant informations nonetheless) -- >>> try: 1/0 except ZeroDivisionError, e: print e print e.args print repr(e) integer division or modulo by zero ('integer division or modulo by zero',) -- (catching Exception instead of ZeroDivisionError would yield the same result, but would also act as an Exception trap that voids any exception raised) -- http://mail.python.org/mailman/listinfo/python-list
Re: OO in Python? ^^
Matthias Kaeppler wrote: > Why would I want to use an attribute in Python, where I would use > getters and setters in Java? I know that encapsulation is actually just > a hack in Python (common, "hiding" an implementation detail by prefixing > it with the classname so you can't access it by its name anymore? Gimme > a break...), but is that a reason to only write white box classes? ^^ > > - Matthias > If you've ever written non-trivial code in Java, you can't deny that most of the classes are littered by pages and pages of -- protected FooClass foo; FooClass getFoo() { return foo; } void setFoo(FooClass foo) { this.foo = foo; } -- This is more or less equivalent to a simple -- public FooClass foo; -- but allows you to change the implementation details of the class without having to bork your whole interface later. Now, you have no reason to do this in python, you can use a regular "real" attribute, and if you need to change the implementation details, you can remove the real attribute and replace it with a virtual attribute through properties without changing the class' interface. -- >>> class Bar(object): def __init__(self): self.foo = 5 >>> bar = Bar() >>> bar.foo 5 >>> >>> # now let's change the Bar class implementation and split foo in boo and far >>> >>> class Bar(object): def __init__(self): self.boo = 2 self.far = 3 def _getfoo(self): return self.boo + self.far foo = property(_getfoo) >>> bar = Bar() >>> bar.foo 5 -- And this is completely transparent for anyone using the Bar class, they don't give a damn about what happens inside. You can also use it to add checks on the allowed values, for example -- >>> class Bar(object): def __init__(self): self._foo = 5 def _getfoo(self): return self._foo def _setfoo(self,foo): if not 0 <= foo <= 10: raise ValueError("foo's value must be between 0 and 10 (included)") self._foo = foo foo = property(_getfoo, _setfoo) >>> bar = Bar() >>> bar.foo 5 >>> bar.foo = 2 >>> bar.foo 2 >>> bar.foo = 20 Traceback (most recent call last): File "", line 1, in -toplevel- bar.foo = 20 File "", line 8, in _setfoo raise ValueError("foo's value must be between 0 and 10 (included)") ValueError: foo's value must be between 0 and 10 (included) >>> -- or everything else you'd use Java's getters/setters for, but without having to over-engineer your classes and wrap everything just because the language doesn't allow you to change your mind if you ever realize you made mistakes in the previous implementations. -- http://mail.python.org/mailman/listinfo/python-list
Re: Great books on Python?
Tolga wrote: > I am not unfamiliar to programming but a newbie in Python. Could you > recommend me (a) great book(s) to start with? Free online books or > solid books are welcome. > > Thanx in advance. > I'd call Dive Into Python a reference, it's an extremely clear yet pythonic book, and it's available online for free. And I guess that you already checked it, but the Python's Tutorial is -- of course -- imperative. -- http://mail.python.org/mailman/listinfo/python-list
Re: double underscore attributes?
[EMAIL PROTECTED] wrote: > Could someone explain the use of __add__ (and similar double underscore > attributes) and what their use is. > > Bob > Methods with double leading and trailing underscores are basically "magic methods" with specific meanings for the Python interpreter. You're not supposed to use them directly (in most cases) as they are wrapped by syntactic sugar or part of protocol's implementation. __add__, for example, is the definition of the "+" operator, using "(5).__add__(8)" is exactly the same as using "5+8". To get a list of most of these magic methods, check the Python documentation on the "operator" module. These magic methods allow you to emulate numbers, sequences, iterators, or even callables (allowing you to use an object as a function). Be really careful with them though, one of the things that plagued (and still plague) C++ is the abuse of operators overloading and modification of their meaning. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie question
Mike Meyer wrote: > And you've once again missed the point. The reason you don't > manipulate the attributes directly is because it violates > encapsulation, and tightens the coupling between your class and the > classes it uses. It means you see the implementation details of the > classes you are using, meaning that if that changes, your class has to > be changed to match. > One of Python's greatnesses is that a property is, for all means an purposes, a fully virtual instance attribute/member. If you follow the KISS principle, as long as your (naive? probably) implementation of the class has "real" attributes and their manipulation is meaningful & makes sense from an external point of view, just leave it at that. If you happen to change the implementation for whatever reason and happen to remove the real attributes, just create virtual attributes with a property and be done with it. Wrapping everything just because you can and considering that encapsulation is only truly done if you never happen to touch what's under the hood (even without knowing it) is the Java Way, this is Python. In Python, the interface of an object instance is always virtualized because you can never know if you're manipulating "real" attributes or property-spawned virtual attributes. _that_, in my opinion, is not knowing about the implementation details. While a Java object is mineral (set in stone) and trying to abstract everything from the start (and generate 50 pages documentation for each class to be sure that you didn't miss anything) kind of makes sense, a Python object is an organic, morphing, living entity. Don't abstract everything and over-engineer from the start just because you can and because you'd do it in Java or C#, only abstract (from your point of view) when you *have to*. And remember that "Java's Object Oriented Programming" is not the only one worth using, even though some people would like to make you believe it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: Inline Import
Shane Hathaway wrote: > Thoughts? >>> import re; name_expr = re.compile('[a-zA-Z]+') >>> name_expr <_sre.SRE_Pattern object at 0x00F9D338> >>> the import statement can be called anywhere in the code, why would you add strange syntactic sugar that doesn't actually bring anything? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect the presence of a html file
Phoe6 wrote: > Operating System: Windows > Python version: 2.4 > > I have bookmarks.html and wumpus.c under my c: > > When I tried to check the presence of the bookmarks.html, I fail. > os.path.isfile('c:\bookmarks.html') > False os.path.isfile('c:\wumpus.c') > True > os.path.exists('c:\wumpus.c') > True os.path.exists('c:\bookmarks.html') > False > os.access('c:\bookmarks.html',os.F_OK) > False > > I can assure you that c:\bookmarks.html exists! and I opened this and > checked it in the browser as well. > > Why is this behavior? And How Should I check for the presence of this > file? > > Any help appreciated. > > Thanks! > Senthil > Have you tried escaping the "\"? try >>> os.path.exists('c:\\bookmarks.html') '\w' is not a special sequence and therefore gets automagically translated to the escaped "\\w", but "\b" is equivalent to "\x08" and your functions therefore see the string "c;\x08ookmarks.html". If you don't want to escape your strings, use rawstrings (prepend your strings with "r", "c:\bookmarks.html" therefore becomes r"c:\bookmarks.html") -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find the type ...
Lad wrote: > Hello > How can I find out in Python whether the operand is integer or a > character and change from char to int ? > Regards, > L. > You may want to try the "type" command. And there is no character type in cPython (unless you're using ctypes that is) There is not much point though, you can use the "int" construct on your expression, Python'll try to convert the expression to an integer by itself (and throw an exception if it can't) >>> a = 3 >>> int(a) 3 >>> a = "3" >>> int(a) 3 >>> a = "e" >>> int(a) Traceback (most recent call last): File "", line 1, in -toplevel- int(a) ValueError: invalid literal for int(): e >>> You can even do base conversions with it: >>> a="0xe" >>> int(a) Traceback (most recent call last): File "", line 1, in -toplevel- int(a) ValueError: invalid literal for int(): 0xe >>> int(a,16) # Silly me, 0xe is not a decimal 14 >>> -- http://mail.python.org/mailman/listinfo/python-list