Strong/weak typing
I'm writing Python as if it were strongly typed, never recycling a name to hold a type other than the original type. Is this good software engineering practice, or am I missing something Pythonic? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python conventions
Daniel Fetchinson wrote: > I'm sorry to disappoint you but this project has already been completed: > > http://www.python.org/dev/peps/pep-0008/ Daniel, PEP 8 is anything but complete. How much of the following simple question can you answer from there: Given that you can name things with UpperAndLower, lowerAndUpper, lower_and_underscore, etc., what is the convention for naming packages, modules, classes, ... PEP 8 very much reminds me of Sun's Java conventions - a start, but only a start. Also, in part, controversial. (How wide do you think Python code should be?) Finally, lacking in basic organization. (This seems to be a disease that infects almost all standards.) We can do better. As a guess, GvR would be happy to have someone fill out PEP 8. -- http://mail.python.org/mailman/listinfo/python-list
Python conventions
I assembled a good conventions set for Java. View it at http://www.martinrinehart.com/articles/code-conventions.html (is that better, Steve?) It followed a logical organization; it was built from four other extensive (if not well-organized) convention sets and it scrupulously avoided injecting my own biases. Where there were disagreements, they were noted and the opposing viewpoints explained. I'm appointing myself project secretary of a similar effort for Python, until we can find someone better qualified (Python experience pre-dating my late '07 start would be better qualified). The secretary's job is to ask questions and correctly record answers. First question: global (e.g., what language for comments) package module class methods data function statement expression variable Is this a good outer-level organization? For each topic, cover: documentation naming convention(s) format Second question: are the above the items we cover for each topic? Others? -- http://mail.python.org/mailman/listinfo/python-list
Re: import statement convention
Thanks, all. Good to know no one's been beheaded. Yes to separating test and non-test code, but no if that will just turn one modest module into two modules, smaller still. Amen to 'practicality beats purity.' Do wish we had a good, thorough convention set. I wrote one for Java. It took a lot of work. ( file:/home/martin/mrwebsite/articles/code- conventions.html ) -- http://mail.python.org/mailman/listinfo/python-list
import statement convention
By convention, I've read, your module begins with its import statements. Is this always sensible? I put imports that are needed for testing in the test code at the end of the module. If only a bit of the module has a visual interface, why pollute the global namespace with 'from Tkinter import *'? Wouldn't that be better done in a separate class or function? Can we do a better job with a thoughtful rewrite of this convention? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus made easy
[EMAIL PROTECTED] wrote: > menudef = """ > File > New,callNew,Ctrl-N > New Window, callNewWindow, Ctrl-Shift-N > __ > Open, lambda e=0:para(1), Ctrl-O Nice design. I looked at it for a few seconds and didn't even think about pressing F1. Mine does less. But you tell it less to do it. Is there no way to get underscore/ keyboard access for the main menu items? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus made easy
Guilherme Polo wrote: > there is a > gui designer tool for tkinter called GUI Designer (what a bad name), > which used to be called SpecTcl, where you can design the menus and it > then converts to python code. I tried it. after about 10 minutes I was as far as "help not found." Is anyone out there using this tool? Worth the learning curve? -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Text widget
Is there a way of translating from the Text widget's width/height (in characters) to pixels so you can open an appropriately sized window? -- http://mail.python.org/mailman/listinfo/python-list
Tkinter menus made easy
Writing Tkinter menu code used to be rather tedious, uninspiring work. I figured that I could delegate the job to a program: http://www.martinrinehart.com/articles/menus.py Run it. Then look at the source (bottom of file). There's a bit more doc in the doc comment at the top. Peer review is most welcome. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
Eric Brunel wrote: > BTW, this "standard" is not universal at all: e.g, there is no such > convention on Macs. Thanks for the info. It's standard on Windows and Linux/KDE. GNOME, anyone? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter menus from keyboard
Guilherme Polo wrote: > Set the underline option to the index of the desired letter Elegant simplicity in the dropdowns. Thanks! Now, how about main menu underscores? -- http://mail.python.org/mailman/listinfo/python-list
Tkinter menus from keyboard
Tkinter defaults to, for example, Alt+f = File (if File is your first menu name starting with "f"). I'd like to assign my own letters and have them underscored, per the universal standard. Can this be done? -- http://mail.python.org/mailman/listinfo/python-list
lists v. tuples
What are the considerations in choosing between: return [a, b, c] and return (a, b, c) # or return a, b, c Why is the immutable form the default? -- http://mail.python.org/mailman/listinfo/python-list
What's Going On?
(Accompanied by Marvin Gaye) >>> def f(list=[0]): ...list[0]+=1 ...return list[0] ... >>> f() 1 >>> f() 2 >>> f() # 'list' is a name bound to a list (mutable) so this makes sense 3 >>> f([5]) 6 >>>f() # What's Going On? 4 Off topic: Motown chief Berry Gordy tells Gaye he won't release the "uncommercial" song. Gaye tells Gordy he'll never have another Gaye song if he doesn't release it. Gordy backs down. 2.5 million singles plus title track for blockbuster album. -- http://mail.python.org/mailman/listinfo/python-list
Re: Better grammar.txt
Jeroen Ruigrok van der Werven wrote: > >http://www.martinrinehart.com/articles/python-grammar.html: > >Unknown host www.martinrinehart.com > > Works for me. Very interesting. The link I posted works for me, while the links quoted are 404 errors, though they look identical. This really is a superior version of the EBNF, so I wish it would work for everyone. Any ideas? -- http://mail.python.org/mailman/listinfo/python-list
Re: Better grammar.txt
[EMAIL PROTECTED] wrote: > It includes three corrections to grammar.txt (imagnumber, xor_expr and > and_expr) that I've reported. Make that four corrections. Add augop. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why """, not '''?
D'Arcy J.M. Cain wrote: > Where did you see that? The only place I saw it was the style guide > and it was only talking about docstrings. PEP 8 and 257, and you're right, they are both about docstrings. Also, I'd never seen an example of the triple apostrophe form until I dove into the formal syntax specification. -- http://mail.python.org/mailman/listinfo/python-list
Why """, not '''?
Why is """ the preferred delimiter for multi-line strings? -- http://mail.python.org/mailman/listinfo/python-list
Better grammar.txt
I previously posted a link to an improved, HTML-based, hyperlinked grammar.txt. Discard that one. This one is much better. http://www.martinrinehart.com/articles/python-grammar.html If you find it useful, thank Gabriel Genellina for encouraging me to get it really right. It includes three corrections to grammar.txt (imagnumber, xor_expr and and_expr) that I've reported. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Gabriel Genellina wrote: > About the generated page: I think it would be more useful if each symbol > links to its definition, instead of showing an alert(). This way it's > easier to navigate the tree, specially with complex declarations. That was my first shot. It didn't work. (Every line is its own table because you can't put named anchors inside a table, something I really regret.) If the production is already viewable, there's no jump when you click the link.. If the production is on the last page (many are) you jump to the last page and then have to hunt down the production. Remind me to figure out Ajax so you get what we really want: click on it and see its definition highlighted. > You can place the current text into a "title" attribute and most browsers > will show it as a tooltip. Great! Consider it done. Konqueror, Firefox, Opera and even MSIE. How would , and make our lives easier? I also tried putting the definitions into the status bar. If you ever feel tempted to do something similar, let the urge pass. (This now works in Firefox 2 if you use the correct settings to allow javascript to write to the status bar. It doesn't work in Konqueror or Opera and I can't even find the settings for MSIE.) Trying to get this to work DID get me to considerably improve the readability of the HTML, so it wasn't a total waste. The tooltips are a big step forward. Thanks again. Improved version at http://www.MartinRinehart.com/articles/python-parse-bnf.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Paul McGuire wrote: < plus sundry other parts of the kitchen > sink) that was passed BY PROJECT CODING STANDARDS to EVERY FUNCTION IN > EVERY MODULE! Supposedly, this was done to cure access problems to a > global data structure. Beautiful example of how totally stupid actions can be taken in the name of avoiding globals. Wikipedia and PEP 8 both agree with me, re globals. OK way to eliminate chained argument passing, but keep them within one module. _OFILE, by the way, is the output file. It's contract with the rest of the module was to be available for writing to anyone with data to write. I use the Java convention of ALLCAPS for naming things that I would declare as CONSTANT if Python had such a declaration. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Steve Holden wrote: > I wish you'd stop trying to defend this code and simply admit that it's > just a throwaway program to which no real significance should be > attached. *Then* I'll leave you alone ;-) You're hurting my program's feelings! Actually, I intend to keep this program as the nice HTML version of the BNF that it produces is a big advance over the source from GvR. I'll rerun this from time to time to keep my BNF up to date. A second intent was to have the next sorry coder who searched for 'Python BNF' get a better answer than I got, which is already the case. The discussion re globals is entirely academic, of course, with this little program being merely illustrative. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Gabriel and Steve, Poor globals! They take such a beating and they really don't deserve it. The use of globals was deprecated, if memory serves, during the structured design craze. Using globals is now considered bad practice, but it's considered bad practice for reasons that don't stand close scrutiny, this being a perfect example. ofile = ... # global writeHTML() def writeHTML(): ofile.write( .. ) writeBody() def writeBody(): ofile.write( ... ) writeEntries() def writeEntries() ofile.write( ... ) writeEntry() def writeEntry(): ofile.write( ... ) ... # "fixed" to eliminate the evil global writeHTML(ofile) def writeHTML(ofile): ofile.write( .. ) writeBody(ofile) def writeBody(ofile): ofile.write( ... ) writeEntries(ofile) def writeEntries(ofile) ofile.write( ... ) writeEntry(ofile) def writeEntry(ofile): ofile.write( ... ) ... # repeat above for another half dozen subs that also use ofile The code's simpler before the fix. So, as a nod to the anti-global school of thought, I changed 'ofile' to 'OFILE' so that it would at least look like a global constant. Then I changed to '_OFILE' as a reminder that this is a modular, not global, constant. Ditto for '_PRODUCTIONS'. Modular constants share exactly none of the coupling problems that globals can have. You'll let me use modular constants, right? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Implemented all your suggestions, with two exceptions. Changed file read to readlines(), but not open(...).readlines(). I love to say file.close(). Gives me a feeling of security. (We could discuss RAM waste v. I/O speed but this input file is just 10KB, so neither matters.) Removed one of the three globals, but left the other two. Couldn't see any real advantage to passing poor 'ofile' from hand to hand (writeHTML() to writeBody() to writeEntries() ...) as opposed to letting him rest easy in his chair, doing a little writing when called. Also changed the opening doc comment to give you appropriate credit. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's BNF
Thanks so much Gabriel. -- http://mail.python.org/mailman/listinfo/python-list
Python's BNF
I spent too long Googling for Python's BNF. Eventually found it at Python.org, but only by accident. I've put Python's BNF here: http://www.martinrinehart.com/articles/python-parse-bnf.html Extensively cross-referenced. Addenda: No, Google, I didn't want the Botswana daily news with its article on the Botswana National Front and another on a fellow arrested for having contraband python skins. Did this with a Python program. Used to use Perl for this sort of thing. Doubt I'll ever write another line of Perl. There's a link to the program, top-right of page. If anyone wants to look at this no-longer-quite-newbie's code and give a constructive critique, I'd be grateful. -- http://mail.python.org/mailman/listinfo/python-list
Array of functions, Pythonically
My parser has found an expression of the form CONSTANT_INTEGER OPERATOR CONSTANT_INTEGER. I want to fold this into a single CONSTANT_INTEGER. The OPERATOR token has an intValue attribute, '+' == 0, '-'== 1, etc. In C I'd put functions Add, Subtract, ... into an array and call ArithmeticFunctions[ intValue ] to perform the operation. Would I index into a list of functions in Python, or would IF/ELIF/ELIF ... be the way to go? -- http://mail.python.org/mailman/listinfo/python-list
Re: PHP Developer highly interested in Python (web development) with some open questions...
re encryption I ran a small software company in the '80s. We did the unthinkable: shipped our software with a money-back guarantee. Anyone could buy the software, copy it and then request a full refund. Return rate: 0.5%. Of the returns we guessed that about half of them were for perfectly legit reasons. Treat your customers as if they're all honest and ethical. Most of them will be. The rest will defeat your encryption efforts or just skip your product. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Missing the last piece of the puzzle
Simon Forman wrote: > yes! check out http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464635 > > HTH, > ~Simon Thanks, Simon. Looks like that will do it. Actually, it looks like that will overdo it. I'll be setting File/Save to enabled after every keystroke. Ideally, I'd like to set my statuses when the user clicks the File option or types Alt-F. This makes me wonder if there's a "mixin" that could find this event. Hmmm. Alternatively, could modify this code to NOT reset the modified flag, so I only get called on the first modification. Hmmm. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter: Missing the last piece of the puzzle
I have a simple editor built into my visual parser. It has a File menu with typical New, Open, Save, Save As ... options. I now know how to set the options [en/dis]abled and how to check the Text widget's modified flag. Now I want to [en/dis]able those options. Can I ask the text to notify me when the modified flag changes? Can I set the statuses when the user clicks File, before the options are displayed? Do I need to create a checker on an independent thread that looks at the flag every few millis? (Tkinter deserves more respect. I've got a good-looking application growing quickly.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Menu Item Activation
Rob Wolfe wrote: > But I think that you should read this: > http://effbot.org/zone/vroom.htm Rob, may the gods shower you with gold coins! -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Menu Item Activation
Tkinter definitely deserves more respect! I'm making rapid progress and it looks good. But am stuck on this: I want the File/Save state to change from disabled to enabled, depending on whether or not there is something to save (Text modified). Google returns results in every language except Python. Sub problems: how to change state of menu item? how to detect changes in Text widget? Help appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Globals or objects?
A fascinating, well-informed discussion. Thanks to all. Holden's suggestion re coupling and cohesion was most informative. I conclude that whether you use an object or a global (within a module, not across modules) is an implementation detail that has no impact on either cohesion or coupling. D'Aprano's discussion is persuasive but only in the case where you do not want multiple actors updating a single value. In my case multiple actors have legitimate interest in updating the value. (Actors within a single thread, fortunately.) I conclude that intra-module globals are NOT always evil. They get a bad rap because some of them are evil. Anecdote proving nothing: My count got wrapped into an object. I found additional uses for the object, so it stayed there. Finally, the count and the object got designed out of the module. RIP. -- http://mail.python.org/mailman/listinfo/python-list
Globals or objects?
I had a global variable holding a count. One source Google found suggested that I wouldn't need the global if I used an object. So I created a Singleton class that now holds the former global as an instance attribute. Bye, bye, global. But later I thought about it. I cannot see a single advantage to the object approach. Am I missing something? Or was the original global a better, cleaner solution to the "I need a value I can read/write from several places" problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
re being serious I am serious. I am seriously trying to develop a nice language for beginners. I was at Dartmouth in 1965 when BASIC was new. It let me use the computer without learning Fortran. It was very successful. I think it's past time for another one. I think we could have a lot more capability with more simplicity than you find in Visual Basic. re DLing source As a "solution" to the problem of wanting a program on my computer, it sucks. On Windows I'll DL an install package, "accept" a license agreement, click Next a few times (no, I can't make a cup of coffee because the minute I step away the "Wizard" will ask a question), ... With CNR the commitment is that I CAN walk away. I do not know who should be responsible for putting things in the warehouse. I do wish that the *n*x community would create some sensible standards so the 'our distro doesn't put things where others do' would stop being an issue. Looking in "/usr/bin" and its brethren makes "c:\Program Files" seem organized. re changing distros because apt-get could do the job I'll take your words for the superiority of Ubuntu. But I'll not change from one problem (can't find the python-devel that python.org says I need) to another (installing a new OS). I bought my Linspire computer with the OS installed. I've no interest in mastering the art of installing Linux. I'm a big fan of KDE, KATE and Konqueror and having a dozen desktops for a dozen projects. I do not miss crashes and viruses. I do not miss shelling out hundreds of bucks for an office suite. So for now I'll just pretend that Windows is desktop 13. A KVM helps. I'll remember that you don't type "uptime" in the DOS window. Oh, yeah. I'll remember that my NAV subscription expired. Gotta renew. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Paul Rubin wrote: > repz movsw is a pretty lame way to copy data on current x86's. > Use XMM instead. Thank you, Paul. I'm pretty sure you meant MMX, Multi-Media eXtensions. Paul's just told me to upgrade my 32-bit thinking to use newer 64-bit registers, even on a 32-bit cpu. Please divide my prior timings by two. Pentium or later required. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Steve Holden wrote: > You have a strange idea of "nearly free" ... > > Extending an integer array from 100 to 150 items is a pretty puny > operation when you compare it with the amount of data that might need to > be moved during a compactifying garbage collection of a 20MB Python > program image. 20 MBs = 5 M 32-bit words = 1.25 millis to move half of them on a 2GHz machine. Don't know how much a milli costs where you live. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Jeff Schwab wrote: > What's "the Intel architecture?" Do you mean the x86_64 architecture > that was actually developed by AMD, or x86 for x > some number, or do > you actually mean IA64? I mean chips of the family that goes back to the 8086 and 8088 chips, chips that support the REPZ prefix to the MOVSW instruction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
Paul Boddie wrote: > The whole CNR stuff and the > proprietary software slant of Linspire obscures the solution, in my > opinion. Thanks for all your help, Paul. CNR, which is now free, is absolutely marvelous when it's got what you need. If Python2.5 were in the warehouse, I'd have clicked, gone to make a cup of coffee and the appropriate icon would be on my desktop when I came back. If I were Python.org I'd not consider anything ready for release until it was in the warehouse. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
Paul Rubin wrote: > The problem here is with a high allocation rate, you have to GC a lot > more often, which typically involves copying live data. This is last century's issue. Copying data, RAM to RAM, is nearly free using the Intel architecture. This short article, http://www.martinrinehart.com/articles/repz.html explains why. I'd use one int per clock as a rule of thumb for the current copy rate in a single-core CPU. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
Paul Boddie wrote: > Here's one page which probably tells you stuff you already know: > > http://wiki.python.org/moin/BeginnersGuide/Download Thank you! It says I need Python (which I've got) and the Python-devel package, which sounds like it might include Tkinter and IDLE. Now if only I knew where to get the Python-devel package ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux/Python Issues
[EMAIL PROTECTED] wrote: > IOW: all this is assumed to be > common *n*x knowledge. Both GNOME and KDE put Windows to shame. An old Windows guy, like me, can just start using either one without needing 'common *n*x knowledge.' Too bad the *n*x community isn't more welcoming to outsiders. Linspire's CNR puts Windows DLs to shame, but Python2.5 isn't there. Ugh. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Confusion
Many thanks to all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter = Rodney Dangerfield?
Gabriel Genellina wrote: > I don't like Tk because the widgets are ugly, old-fashioned, and don't > have the right "look and feel". Take another look. A year or so back Tkinter went to platform native widgets. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Memory Manager
I researched this for some Java I wrote. Try to avoid shuffling physical memory - you'll write a lot less code and it will be faster, too. Use an "allocated" list and an "available" list. Keep them in address order. Inserting (moving list elements from insertion point to end) and deleting (vice-versa) are near-zero cost operations on Intel boxes. ( Two millis to move a million ints at 1GHz 5 years ago when I wrote http://www.martinrinehart.com/articles/repz.html - probably half that today.) The worst choice is the "best fit" allocation algorithm. (Grabbing most of a free bit leaves a probably useless small bit. Grab from the first big piece you find.) Circular first-fit is probably best. (Testing was for compiler-type applications.) When space is freed, insert link in ordered chain of free space blocks. Then combine with prev/next blocks if they are free. And when you find the function in Python that matches Java's System.arraycopy(), please tell me what it's called. I'm sure there must be one. -- http://mail.python.org/mailman/listinfo/python-list
Linux/Python Issues
I went to Python.org, DL'd Python 2.5 source code per the usual inadequate instructions and ran the make files successfully (sort of). Python 2.5 works fine. But "from Tkinter import *" gets a "What's Tkinter?" message. IDLE's no where to be found. What's not in the instructions is what directory should I be in when I download? Where should I put the ".bz2" file? What dir for running the make files? At present I'm working on a Windows machine, endangering what's left of my sanity. I'm using Linspire, so Debian directories are probably the ones that will get me up and running. Barring specific knowledge, even some good guesses would be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter Confusion
Everything I've read about Tkinter says you create your window and then call its mainloop() method. But that's not really true. This is enough to launch a default window from the console: >>>from Tkinter import * >>>foo = Tk() Google's great, but it has no truth meter. Do I inherit from Frame? Or is that a big mistake. (Both positions repeated frequently.) Do I use Tk() or toplevel()? (Support for both and if a cogent explanation of the differences exists, I didn't find it.) Here's the application. I'm creating a visual parser for my beginner's language. The starting position is a list of Statement objects, each being a list of Token objects. The statement is presented as a list of buttons with abbreviated token types ('Con_Int' for a CONSTANT_INTEGER token). Click the button and a dialog-like info display pops up with all the details about the token. During parsing, each recognition condenses tokens into productions, shortening the Statement. (Example: three Token buttons are replaced by one Addition production button.) An application window provides for stepping through the parsing and provides utility commands such as "Close all those token windows I've got lying all over". Much less complex than IDLE, but GvR and cohorts seem to understand what's really going on. I don't. Help appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Tkinter = Rodney Dangerfield?
Tkinter gets no respect. But IDLE's a Tkinter-based app and every example I've Googled up shows Tkinter as needing about half as much code as wx to do the same job. I'm beginning to Tkinter up my language application. Am I making a big mistake? -- http://mail.python.org/mailman/listinfo/python-list
Re: Operator overloading
Hexamorph wrote: > You mean you want the ability to change for example the + operator > for ints to something like calculating the cosine instead of doing > addition? Sure. Cosines are a monadic operation and the monadic '+' is a NOP, so why shouldn't I define +45 to return cosine of 45, (presuming I needed lots of cosines). I'd even let you define your own operators. Lots of programmers really liked '++' and '--', for examples. -- http://mail.python.org/mailman/listinfo/python-list
Re: Operator overloading
Diez B. Roggisch wrote: > No, there is no way. You would change general interpreter behavior if > you could set arbitrary operators for predefined types. > > Start grumping... Thank you, Diez. If I ever design a language, please remind me that complete, easy, well-documented access to the working of the internals (and the ability to change same) would be very, uh, what's the right word? Pythonic? -- http://mail.python.org/mailman/listinfo/python-list
Operator overloading
If it were my choice, the plus sign would do this: def itemadd( i1, i2 ): if ( type(i1) == str ) or ( type(i2) == str ): return str(i1) + str(i2) else: return i1 + i2 I'd like to redefine it so it works my way but operator overloading seems strictly confined to classes I create. Is there a way? Or do I just have to grump, "Even a kludge like Perl ..."? -- http://mail.python.org/mailman/listinfo/python-list
Newbie wants to get visual
I'm ready to start coding the parser for my Decaf (beginners) language. I think that a "visual" parser (one that shows what it's doing as it does it) would be nice. (And I think that it would help the parser author by saving the requirement for a bazillion print statements while debugging the tool.) Can someone point me toward the easiest possible way to get GUI? I've got the Rappin/Dunn book re wxPython, but suspect that this may be overkill for what I want. If I could do something that would work in a browser window, that would be wonderful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
Thanks to all for many helpful suggestions. Python, by the way, is verbose when compared to APL. (See http://catpad.net/michael/apl/ if you don't believe this.) You need to stick in an adverb (maybe "gracefully concise") as standalone "concise" is owned by APL. Basilisk96 wrote: > Did programmers stop writing programs on punch cards because they ran > out of punch paper? If you drive on the NYS Thruway, you still get a punch card when you enter. You turn it in when you pay your toll. -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
Matthew Woodcraft wrote: > I think [the olpc guidlines are] mostly PEP 8, with some notes added. Took a good look. You are absolutely correct. PEP 8 is basically word processing text stuck between and tags. OLPC is Wiki HTML. Good example of how the latter is a lot bigger than the former, with little extra content. -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
That's a great list, grflanagan! Thanks. I looked at each and copied to my disk either as a .txt (cut/paste from the browser) for a page or less or as .html (view source, chop off head and non-guideline stuff, save). This is the list plus PEP 8 minus the software. (No disrespect for the software, just sticking to written standards.) Zope may be a substantial guideline, but it linked to a page of Zope links, all of which were broken. This CSV file is sorted by filesize on my disk. One presumes that a relationship exists between size and extent of coverage. (Warning: Wiki text could be as much as twice the size of non-wiki for the same content.) The third column is empty (spacer between size and URL). A quick look (thorough analysis still required) shows that OLPC and PyPy are, indeed, extensive standards. one-laptop-per-child.html (olpc),74.3,,http://wiki.laptop.org/go/ Python_Style_Guide pypy.html,64.2,,http://codespeak.net/pypy/dist/pypy/doc/coding- guide.html pep-008.html,35.6,,http://www.python.org/dev/peps/pep-0008/ knight.html,33.7,,http://jaynes.colorado.edu/PythonGuidelines.html pep-257.html,23.8,,http://www.python.org/dev/peps/pep-0257/ webware.html,23.4,,http://www.webwareforpython.org/Docs/ StyleGuidelines.html twisted.html,23.3,,http://twistedmatrix.com/trac/browser/trunk/doc/ development/policy/co... voice-code.html,17.9,,http://voicecode.iit.nrc.ca/VoiceCode/uploads/ codingGuidelines.html fsl.html,15.0,,http://www-md.fsl.noaa.gov/eft/developer/ PythonCodingStandards.html wx.html,14.6,,http://www.wxpython.org/codeguidelines.php mnet.html,14.5,,http://mnet.sourceforge.net/coding_standards.html michael-foord.html,14.2,,http://www.voidspace.org.uk/python/weblog/ arch_d7_2006_04_01.shtml#e296 bazaar.html,10.4,,http://doc.bazaar-vcs.org/bzr.dev/en/developer-guide/ HACKING.html#cod... ipython.html,10.2,,http://ipython.scipy.org/moin/Developer_Zone/ Developer_Guidelines barry-warsaw.html,6.2,,http://barry.warsaw.us/software/STYLEGUIDE.txt django.html,5.6,,http://www.djangoproject.com/documentation/ contributing/#coding-style chandler.txt,4.0,,http://chandlerproject.org/Projects/ ChandlerCodingStyleGuidelines pyblosxom.txt,3.8,,http://pyblosxom.sourceforge.net/blog/static/ development#coding freevo.txt,3.4,,http://jaynes.colorado.edu/PythonGuidelines.html sql-object.txt,2.7,,http://www.sqlobject.org/DeveloperGuide.html#style- guide biopython.txt,2.5,,http://biopython.org/wiki/ Contributing#Coding_conventions tracdev.txt,1.8,,http://trac.edgewall.org/wiki/TracDev/CodingStyle docutils,1.8,,http://docutils.sourceforge.net/docs/dev/ policies.html#python-coding-... moinmoin.txt,1.8,,http://moinmoin.wikiwikiweb.de/CodingStyle cherrypy.txt,1.5,,http://www.cherrypy.org/wiki/CodeConventions skeletonz-naming.txt,1.4,,http://orangoo.com/skeletonz/Developer_guide/ Naming_convention/ mercurial.txt,0.9,,http://www.selenic.com/mercurial/wiki/index.cgi/ Basic_Coding_Style skeletonz-coding.txt,0.6,,http://orangoo.com/skeletonz/Developer_guide/ Coding_convention/ software-carpentry.txt,0.1,,http://www.swc.scipy.org/lec/style.html zope.txt,0.0,,http://wiki.zope.org/zope3/CodingStyle -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
Guilherme Polo wrote: > foo = [ > 'too long', > 'too long too', > ... > ] OK, I'll put it there too, and it will be easy for us to read each other's code (at least in this particular). -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm searching for Python style guidelines
Thank you both. Stupid me, went to Python.org and found Style Guidelines and thought that was the last word. Oh well. PEP 8 reminds me a lot of Sun's Java conventions, in ways I wish it didn't. The overall structure seems like a random list of topics and it omits a lot. For Java I went from Sun to other conventions to try to compile a meta-convention ( http://www.MartinRinehart.com/articles/code-conventions.html ). Here's just one of my questions: foo = [ 'some item, quite long', 'more items, all demanding there own line as they are not short', ... Where would you put the closing ']'? -- http://mail.python.org/mailman/listinfo/python-list
code doesn't reference immutables?
>From the manual: "code objects are immutable and contain no references (directly or indirectly) to mutable objects" (3.2) I thought my code worked with both mutable and immutable objects. Whassup? -- http://mail.python.org/mailman/listinfo/python-list
I'm searching for Python style guidelines
There's a lot of dumb stuff out there. "Algorithms should be coded efficiently ..." Thanks, I'll keep that in mind. van Rossum's guidelines tend toward "pick something and stick to it" which is OK if you have enough experience to pick something Pythonic. I'm a relative newbie, not qualified to pick. Anything written somewhere that's thorough? Any code body that should serve as a reference? -- http://mail.python.org/mailman/listinfo/python-list
Python's great, in a word
I'm a Java guy who's been doing Python for a month now and I'm convinced that 1) a multi-paradigm language is inherently better than a mono-paradigm language 2) Python writes like a talented figure skater skates. Would you Python old-timers try to agree on a word or two that completes: The best thing about Python is ___. Please, no laundry lists, just a word or two. I'm thinking "fluid" or "grace" but I'm not sure I've done enough to choose. -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic inheritance question
Jeroen Ruigrok van der Werven wrote: > Shouldn't this be: > > self.startLoc = start > self.stopLoc = stop Thanks! Of course it should. Old Java habits die slowly. -- http://mail.python.org/mailman/listinfo/python-list
Basic inheritance question
Working on parser for my language, I see that all classes (Token, Production, Statement, ...) have one thing in common. They all maintain start and stop positions in the source text. So it seems logical to have them all inherit from a base class that defines those, but this doesn't work: import tok class code: def __init__( self, start, stop ): startLoc = start stopLoc = stop class token(code): pass x = token( tok.Loc(0, 0), tok.Loc(3, 4) ) print x.startLoc.repr(), x.stopLoc.repr() AttributeError: token instance has no attribute 'startLoc' 1) Is my design thinking good, or hopelessly unPythonic? 2) If it's good, how do you access base class data attributes? (The doc is rich in method access info, impoverished when it comes to other attributes.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Fortran to Python
Jeroen Ruigrok van der Werven wrote: > I got someone who asked me to make changes in an old Fortran program she is > using for some calculations. Why convert? Modern Fortran is an object oriented, structured language with the singular advantage that it can run old Fortran programs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a �crit : > > > > Bruno Desthuilliers wrote: > > > >>... that's definitively not > >>something I'd store in global. > > > > > > So where would you put it? > > You don't have to "put" functions arguments anywhere - they're already > local vars. Bruno, right now I've got this: def __init__ ( self, t ): """ Constructor, called with array of strings. """ self.text = t ... Some other program will say: tok = Toker( text_array ) tokens = tok.tokenize() So how does the constructor make the array of strings available to the tokenize() method? -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Dennis Lee Bieber wrote: > Great if one is using a teletype as editor The original Dartmouth computer room was a basement that featured 8 teletypes. The original BASIC, Dennis, was implemented on a time-shared "mainframe" with a gigantic 8k words (20-bit words, if I remember) of core memory. Designing a language for such a machine, I'd bet you, too, would choose single-letter names. ('A' was a numeric. 'A$' a string.) If you compare the teletype to a tube it was lame. But that's not the right comparison. The Fortran technology was cards, punched on a card punch, carried to the operator. Wait your turn (hours more commonly than minutes). Get a report off the line printer. Repunch the offending cards. Indeed, the teletype with line numbers was a giant step forward. No operator. No waiting. Compiler complains. Retype the offending line. A miracle in its day. You didn't even have to start your statements in column 7! -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
Tokenizer accepts "0x" as zero. Spec says its an error not to have at least one hex digit after "0x". This is a more serious bug than I had originally thought. Consider this: Joe types "security_code = 0x" and then goes off to the Guardian-of- the-Codes to get the appropriate hex string. Returning to computer, Joe's boss grabs him. Tells him that effective immediately he's on the "rescue us from this crisis" team; his other project can wait. Some hours, days or weeks later Joe returns to the first project. At this point Joe has a line of code that says "security_code = 0x". I think Joe would be well-served by a compiler error on that line. As is now, Joe's program assigns 0 to security_code and compiles without complaint. I'm pretty sure any line of the form "name = 0x" was a product of some form of programmer interruptus. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Steven D'Aprano wrote: > Context is all gone, so I'm not sure that I remember what "it" is. I > think it is the text that you're parsing. Yes. I'm tokenizing today. Parsing comes after Christmas. > TEXT = "placeholder" > > def parse(): > while True: > token = get_next_token() # looks at global TEXT > yield token Classic, but I'm not going to go there (at least until I fail otherwise). My tokenizer returns an array of Token objects. Each Token includes the text from which is created, locations in the original text and, for something like CONSTANT_INTEGER, it has an intValue data member. > # Run as many independent parsers as I need: > parser1 = parse(open("filename", "r").read()) > parser2 = parse(open("filename2", "r").read()) > parser3 = parse("some text") Interesting approach, that. Could have a separate parser for each statement. Hmmm. Maybe my tokenizer should return a list of arrays of Tokens, one array per statement. Hmmm. I'm thinking about an OO language construction that would be very easy to extend. Tentatively, I'll have Production objects, Statement objects, etc. I've already got Tokens. Goal is a really simple language for beginners. Decaf will be to Java as BASIC was to Fortran, I hope. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
Chris Mellon wrote: > You don't seem to be implementing the > lexer in Python I am absolutely implementing my language in Python, a language I have now been writing for two entire weeks. This list has been more than helpful, tolerating numerous newbie questions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Bruno Desthuilliers wrote: > ... that's definitively not > something I'd store in global. So where would you put it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Hendrik van Rooyen wrote: > I wonder if you have some COBOL data divisions under your belt? Hendrik, I go way back but somehow I missed COBOL. Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Hi, Bruno. Merry Christmas! By "constant" I meant that it did not change during the lifetime of the Toker. -- http://mail.python.org/mailman/listinfo/python-list
How to handle multi-line quotes
Thinking about unclosed multi-line quotes. When you open a multi-line quote (type '"""') what does your editor do? Does it color the remainder of your text as a quote, or does it color the line with the open quote as a quote and leave the rest of your code alone? What do you want it to do? This is a tokenizer question in disguise, of course. The simple way to handle it, which is what my editor sees, is for the tokenizer to return the remainder of the text as one great UNCLOSED_MULTILINE_QUOTE token. The alternative is to assume that the line with the unclosed quote is in error and to continue to tokenize the rest. An editor might blink or otherwise draw attention to the unmatched quote. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
Chris Mellon wrote: > Is there some reason that you think Python is incapable of > implementing lexers that do this, just because Python lexer accepts > it? Absolutely not. My opinion is that it's a bug. A very, very minor bug, but still six-legged. > Note that if you're using your lexer to mark up or pretty print or > whatever Python source, it's wrong - 0x is (rightly or not) a valid > Python literal. My lexer is for my language, Decaf, which, in this particular, is the same as Python. Here's what I find at at python.org/ref: (2.4.4). hexinteger ::= "0" ("x" | "X") hexdigit+ Implementation differs from specification. In this case, I think the spec is more sensible. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
If I get to add multi-line strings today, I'll have a complete tokenizer. Interior looks a lot like C minus semi-colons. (Though I did figure out that there wasn't any need for tokens that didn't come from a real to have a doubleValue field. In C++ or Java all the Tokens had a doubleValue, because one needed it.) Theory: there are some problems which, by their nature, end up looking a lot like C, regardless of language. I wrote a Perl-to-HTML pretty-printer. It lets you embed HTML in comments and creates a table of contents hyperlinked to the individual functions. It's at http://www.MartinRinehart.com , output and source code, in the Articles section. I started with a Perl-style solution: regex for the chars left of "#" and for the chars to the right. One line of Perl. Nice, except that it won't work when applied to itself. It will split the line based on the "#" in the regex, of course. Kludged around that, but then met "#" embedded in strings, "#" embedded in regex passed to functions, ... Ended up marching down the input line, one character at a time, like a C program. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
Gabriel Genellina wrote: > Do you have to validate input based on that grammar? I've built a standalone tokenizer. It returns an array of Token objects. These include tokens such as UNCLOSED_QUOTE and MALFORMED_NUMBER ('1E' not followed by sign or digit, for instance). You could use this in a code editor to colorize. You could use it in a documentation writer to emit source in HTML. You could use the tokens in a parser. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to in Python
John Machin wrote: > Use a proper lexer written by somebody who knows what they are doing, > as has already been recommended to you. My lexer returns a MALFORMED_NUMBER token on '0x' or '0x '. Try that in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
Sion Arrowsmith wrote: > Michael Sparks <[EMAIL PROTECTED]> wrote: > >def bar(): > >global x > >x[0] += " another" > >print id(x[0]) > > ... and for bonus marks, explain why the "global x" in this function > is not required. Because x does not appear as an LHS in bar(), just about the first thing I learned here. More seriously, I can and do use lots of globals. In the tokenizer I'm writing, for example, all the token types(COMMENT_EOL = 0, CONSTANT_INTEGER = 1, ...) are global constants. The text to be tokenized is a global variable. (Actually, the text is unchanging once the Tok object is created, so this "variable" may be another constant.) Passing global constants to functions is a case of CPU abuse. Structured purists gave globals a bad rap, years ago. Time to stick up for them. They're good citizens. Don't blame them if some dumb coder abuses them. It's not their fault. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
Tokenizer bug reported. [EMAIL PROTECTED] wrote: > >>>int('0x', 16) > 0 > > I'm working on a tokenizer and I'm thinking about returning a > MALFORMED_NUMBER token (1.2E, .5E+) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this a bug in int()?
Duncan Booth wrote: > Why would you return a token rather than throwing an exception? Tokenizers have lots of uses. Colorizing text in an editor, for example. We've got a MALFORMED_NUMBER when you type '0x'. We've got an INTEGER when we get your next keystroke (probably). -- http://mail.python.org/mailman/listinfo/python-list
Is this a bug in int()?
>>>int('0x', 16) 0 I'm working on a tokenizer and I'm thinking about returning a MALFORMED_NUMBER token (1.2E, .5E+) -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing by reference
... the first element of the list to which x refers is a reference to the new string and back outside foo, the first element of the list to which x refers will be a reference to the new string. Right? -- http://mail.python.org/mailman/listinfo/python-list
Passing by reference
Is the following correct? x = "some string" x is a reference to "some string" foo(x) Reference is passed to function. In foo: x += " change" Strings are immutable, so x in foo() now points to a different string than x outside foo(). Right? Back outside foo. x = ["some string"] x is a reference to a list whose first element is a reference to a string. foo(x) Within foo: x[0] += " other" Another string is created, the first element of x is modified to point to the new string and back outside foo(), x[0] will point to the new string. Right? -- http://mail.python.org/mailman/listinfo/python-list
How to in Python
I've got a pointer to a position in a line of code that contains either a digit or a period (decimal point). I've got this comment: Numbers are one of these: integers: digit+ 0xhex_digit+ decimals: digit+.digit*[E['+'|'-']digit+] .digit+[E['+'|'-']digit+] digit+[.digit*]% .digit+% Common metacode: '*' = 0 or more, '+' = 1 or more, [] = optional, | = or, ... Now I need to instantiate the comment. How would an experienced Python coder proceed? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie design question
This morning block comments disappeared from the Decaf design. Maybe later today they'll be instantiated in the tokenizer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie observations
> My 2 cents. Eurozone? That would be 3 cents US. I meant colon, not semi-colon. I did the tutorial. I did objects 3 times. In Java, the agreed convention is to use lowerAndUpper naming for member variables. (See http://www.MartinRinehart.com/articles/code-conventions.html#5_1 .) 10 days is not enough. But I don't have any more clarity in my Python classes than I did in Java. Just more "self"s. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie design question
> My 2 cents... Thanks for the feedback, Bruno. Seriously thinking about ditching the block comments and adding multi-line strings. (Block comments are the last item on my tokenizer's "todo" list. Multi-line strings would be easier.) Beginners will be programming fun things in a GUI environment. Think games. Brightly colored bouncing balls. Remember Pong? That's a Decaf- level program. -- http://mail.python.org/mailman/listinfo/python-list
Newbie observations
Warning! Complaints coming. The good news is that 10-days of part-time Python coding has convinced me that I picked the right language. Now, observations. First, it is absolutely horrible being a newbie. I'd forgot how bad it was. In addition to making a fool of yourself in public, you have to look up everything. I wanted to find a substring in a string. OK, Python's a serious computer language, so you know it's got a function to do this. But where? Look it up in the function reference. OK, where's the function reference? A line of code that you'd type in a second is a ten-minute search. Thank God for google. Second, would anyone mind if we tossed the semi-colon (which this newbie is forever forgetting)? I think the language is parsable without it. Third, could our classes be a little more selfless? Or a lot more selfless? The Stroustrup's idea of having the compiler, not the programmer, worry about the self pointer was an excellent decision. What was van Rossum thinking? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie design question
Sion Arrowsmith wrote: > Given a one-or-the-other choice, any editor worth using can do > "comment/uncomment region", and if only to-EOL comments are > available, it will do that for you instead of using block > comments. So block comments are not really a useful language > feature. I'd expect the complete beginner to start in Notepad, and stay there for just long enough to realize that something better is needed. region commenting might be the perfect reason for upgrading. On the other hand, block comments are very useful for documentation. On the other, other hand, commenting out a region as the editors do makes it very obvious that the code is dormant. On yet another hand, editors also colorize, so the commented-out nature of block comments is apparent. There are other options. We could borrow and from HTML to have code and non-code regions. (In Java, where HTML is allowed in the doc comments, I wanted my editor to toggle between HTML editing and code editing. Not all wishes get fulfilled.) I'd like to hear from people who use Python's multi-line strings other than in doc comments. > What would you have to say about a language which > had no specialised comment syntax whatsoever, and expected > you to use semantically irrelevent string literals? I'd say the language predated Fortran, which means "Amazing" Grace Hopper wrote it. Perhaps A-0 didn't have comments? -- http://mail.python.org/mailman/listinfo/python-list
Re: Another newbie design question
Fortran (1957) had line comments. C (1972) replaced these with non- nested block comments. C++ (1983) added here-to-EOL comments. Python (1991) keeps here-to-EOL comments but replaces block comments with multi-line quotes. Block comments and multi-line quotes both serve the same purpose as doc comments. Block comments, especially if they nest, are helpful for commenting out code. Multi-line quotes serve to add text. Is Python, in this particular, an advance over C++? I wrote a lot of Java (here-to-EOL and block comments) without ever feeling the need for multi-line quotes. I've written a little Perl and found multi-line quotes useful for responding to -help switches. On the other hand -help switches are very old-fashioned, a direction I'll not be pointing my tiny beginner's language. (A brief article on programming language geneology is at http://www.MartinRinehart.com/articles/history-programming-languages.html .) -- http://mail.python.org/mailman/listinfo/python-list
Another newbie design question
I've designed a language, Decaf, for beginners. I've got block comments but not multi-line strings. If you can only have one or the other, which is more helpful? Should I have both? (Make a strong argument here: my design principal is, "Designed by a backpacker: when in doubt, leave it out.") -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie design problem
Bruno Desthuilliers wrote: > Then the first move is to carefully eval existing solutions: > http://wiki.python.org/moin/LanguageParsing Always good advice, Bruno. How did you come by that list address? Google or is there something special known to Python experts? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie design problem
Jonathan Garnder said: > Well, if using something like PLY ( http://www.dabeaz.com/ply/ ) is > considered more Pythonic than writing your own parser and lexer... Lex is very crude. I've found that it takes about half a day to organize your token definitions and another half day to write a tokenizer by hand. What's the point of the second half-day's work? My hand-written tokenizer returns everything (white space tokens, comment tokens) while Lex leaves these out. With a full token set you can use the tokenizer to color-highlight text in an editor, to emit an HTML version of source, process doc comments, etc. Python sports a tokenizer module, http://docs.python.org/lib/module-tokenize.html, but it's Python-specific. I'm working on a language for beginners, defined at http://www.MartinRinehart.com/posters/decaf.html (an 11"x17" poster-like display.) Decaf, designed before I'd even looked at Python, is surprisingly Pythonic. But not totally Pythonic. I want an array of Token objects, not a list of tuples, for example. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie design problem
Most unclear. My apologies. I'm trying to structure a tokenizer. The stupid concatenations are just placeholders for the actual tokenizing work. By rebuilding the input they demonstrate that the framework correctly processes all the input. I'm currently using a C-style design (my own pointers into an array of strings) but I suspect I've got the solution an old C guy would have. As a Python newbie I don't yet think in Python. -- http://mail.python.org/mailman/listinfo/python-list
Newbie design problem
Thanks to a lot of help, I've got the outer framework for my tokenizer down to this: for line_number, line in enumerate(text): output = '' for char_number, char in enumerate(line): output += char print 'At ' + str(line_number) + ', '+ str(char_number) + ': ' + output, Or do I? My other tokenizers all worked with array indices. When I came to, say, an open quote character, I passed control to the get_a_string() method. That would, locate the end of the string, push a string token onto the stack and then forward the char array index to point to the next character in the line. Is there a pythonic design I'm overlooking? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie NameError problem
Thanks to all! I will put my class defs first (tho not without expressing my disappointment that this is required in a late 20th century language); learn about enumerate as it looks like exactly what I need and discard my C++/Java based object model because this is a totally other thing. If someone who knows both object models would comment on Python's model v. C++/Java's model that would be helpful. -- http://mail.python.org/mailman/listinfo/python-list
Newbie NameError problem
I don't understand what I don't understand in the following: -- # reader.py - testing char-by-char marching methods f = open('sample_decaf.d', 'r') text = f.readlines() f.close() # this is C-style, 15 lines, in Python: end_line = len(text) line_ptr = 0 while line_ptr < end_line: input = text[line_ptr] output = '' char_ptr = 0 end_char = len(input) while char_ptr < end_char: output += input[char_ptr] char_ptr += 1 print output, line_ptr += 1 # this is Python, 7 lines: for line in text: output = '' for char in line: output += char print output, # but I need locations, so this is impure, 11-line, Python: line_ptr = 0 for line in text: output = '' char_ptr = 0 for char in line: output += char char_ptr += 1 print output, line_ptr += 1 # with a Loc object, 10 lines (not counting the Loc class): loc = Loc(0,0) # Name error: name 'Loc' is not defined for line in text: output = '' for char in line: output += char loc.nextChar() print output + Loc.repr(), loc.nextLine() class Loc: line = 0 char = 0 def __init__(self, l, c): line = l char = c def nextChar(self): char += 1 def nextLine(self): line += 1 char = 0 def repr(self): return 'Loc: line='+str(line)+', char='+str(char) # end of class Loc # end of reader.py -- http://mail.python.org/mailman/listinfo/python-list
Re: Block comments
Bruno Desthuilliers wrote: > Is the array of lines the appropriate data structure here ? I've done tokenizers both as an array of lines and as a long string. The former has seemed easier when the language treats EOL as a statement separator. re not letting literal strings in code terminate blocks, I think its the tokenizer-writer's job to be nice to the tokenizer users, the first one of which will be me, and I'll definitely have string literals that enclose what would otherwise be a block end marker. > While we're at it, you may not know but there are already a couple > Python packages for building tokenizers/parsers The tokenizer in the Python library is pretty close to what I want, but it returns tuples, where I want an array of Token objects. It also reads the source a line at a time, which seems a bit out of date. Maybe two or three decades out of date. Actually, it takes about a day to write a reasonable tokenizer. (That is, if you are writing using a language that you know.) Since I know the problem thoroughly, it seemed like a good starting point for learning Python. There's a tokenizer I wrote in java at http://www.MartinRinehart.com/src/language/Tokenizer.html . Actually, that's an HTML page written by my "javasrc" (parallel to Sun's javadoc) based on the Tokenizer's tokenizing of its own source. Have I got those quotes right? -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
re top posting Thanks for explaining. google groups hides the quoted text, so I didn't see it. Bruno Desthuilliers wrote: > [EMAIL PROTECTED] a �crit : > > Martin, would you _please_ learn to quote properly ? top-posting and > keeping the whole text of the previous posts are two really annoying > practices. TIA > (snip) -- http://mail.python.org/mailman/listinfo/python-list
Block comments
Tomorrow is block comment day. I want them to nest. I think the reason that they don't routinely nest is that it's a lot of trouble to code. Two questions: 1) Given a start and end location (line position and char index) in an array of lines of text, how do you Pythonly extract the whole block comment? (Goal: not to have Bruno accusing me - correctly - of writing C in Python.) 2) My tokenizer has a bunch of module-level constants including ones that define block comment starts/ends. Suppose I comment that code out. This is the situation: /* start of block comment ... BLOCK_COMMENT_END_CHARS = '*/' ... end of block comment */ Is this the reason for """? (If this is a good test of tokenizer smarts, cpp and javac flunked.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb newbie back in shell
I'm less confused. If someone can explain the wisdom of this design, I'd be grateful. If someone can explain why the following compiles successfully, I'd be even more grateful: def get_toks( text ): global line_ptr, last_line while line_ptr < last_line: while char_ptr < len(text[line_ptr]): if matches_EOI(): tokens.append( Token(EOI) ) elif matches_EOL(): tokens.append( Token(EOL) ) line_ptr += 1 char_ptr = 0 Shouldn't "char_ptr" be flagged as an error, appearing in line 4 before being a lhs in the last line? Martin [EMAIL PROTECTED] wrote: > Peter, > > question is, why did the first one work? In my real code I've got > module-level vars and an error msg trying to use them in a function. > In my test example I've got them accessed from within a function w/o > error message. > > I am confused. > > Martin > > Peter Otten wrote: > > MartinRinehart wrote: > > > > > However, here's the little tester I wrote: > > > > > > # t.py - testing > > > > > > global g > > > g = 'global var, here' > > > > > > def f(): > > > print g > > > > > > f() > > > > > > It prints 'global var, here,' not an error message. Wassup? > > > > Try it again with a modified f(): > > > > def f(): > > print g > > g = 42 > > > > In Python variables that are assigned to in a function are > > function-local by default. > > > > Peter -- http://mail.python.org/mailman/listinfo/python-list