file system iteration
In Unix, the file system hierarchy is like a tree that has a base or 'root' that exposes objects (files and folders) that can easily be iterated over. \ \ | / / \ \ | / / \ \|/ / \ | / \|/ | | Root So, when I do os.chdir('/') I am at the base of the tree and can now use something like os.walk() to work with all of the file system objects. In Windows, the file system is disjointed and there is now real 'root' At least none that I can see. It looks more like this: | | | | | | | |_|_|_|_|_|_| A B C D E F G How do you guys handle this when working with scripts that need to touch all files and folders on a Windows machine? I've been looping through A-Z like this: import os.path paths = [] if os.path.isdir('A:/'): paths.append('A:/') if os.path.isdir('B:/'): paths.append('B:/') ... That's a kludge, but it works OK. I'm sure WMI may have a function that returns mounted volumes, but under the circumstances currently, I can only use the standard Python library. Any ideas on how to do this better? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: file system iteration
Gerrit Holl wrote: > The very least you can try: > > import string > string.ascii_uppercase > > for c in string.ascii_uppercase: > if os.path.isdir('%s:/' % c): > ... > > etc. > But I suppose there should be a better way. Oh yes, I do that. I spelled out the example very explicitly for clarity. I don't actually type in A-Z :) -- http://mail.python.org/mailman/listinfo/python-list
Re: file system iteration
Georg Brandl wrote: > Which application needs to walk over ALL files? Normally, you just have a > starting path and walk over everything under it. Searching for a file by name. Scanning for viruses. Etc. There are lots of legitimate reason to walk all paths from a central starting point, no??? -- http://mail.python.org/mailman/listinfo/python-list
Re: file system iteration
Fredrik Lundh wrote: > what's the difference between a "starting path" and a "starting point" ? None. What starting path or point would you suggest under Windows? Is there something obvious that I'm missing? I see no starting point under windows as my initial question clearly stated. -- http://mail.python.org/mailman/listinfo/python-list
Re: file system iteration
Tim Golden wrote: > [Rick] > | Searching for a file by name. Scanning for viruses. Etc. > | There are lots > | of legitimate reason to walk all paths from a central > | starting point, no??? > > Well, to get you started, I think this is the kind > of thing you'll want. Uses ctypes, which is built-in > to Python 2.5 so presumably legit. > > > import ctypes > import string > > GetDriveType = ctypes.windll.kernel32.GetDriveTypeA > > for letter in string.uppercase: > print letter, "=>", GetDriveType ("%s:" % letter) > > Thanks, I'll give this a try. I appreciate everyone's input. -- http://mail.python.org/mailman/listinfo/python-list
Re: file system iteration
Thanks Tim and Rob... this works really well! -- http://mail.python.org/mailman/listinfo/python-list
block devices
What's the best way to read a byte of data directly from a block device (a scsi hard drive) on Linux using Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: block devices
Diez B. Roggisch wrote: > Reading it? Using read? > > f = open("/dev/foo") > f.read(1) > > Diez Wow, I didn't realize it was that simple. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
invert or reverse a string... warning this is a rant
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x[::-1] Ruby: x = 'a_string' # Reverse the string print x.reverse The Ruby approach makes sense to me as a human being. The Python approach is not easy for me (as a human being) to remember. Can that be changed or should I just start blindly memorizing this stuff? P.S. I like Python better than Ruby 90% of the time and use Python 90% of the time, but 10% of the time, little things such as this drive me crazy! -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
Demel, Jeff wrote: > Ok, let me re-phrase: > > ...[snip]... > I've been programming professionally for over 10 years, and have never > once needed to reverse a string *or detect a palindrome*. Maybe it's a > lack of imagination on my part, but I can't think of a single instance > this might be necessary. > ...[snip]... I read files backwards all the time. Just for the heck of it. Now, maybe I don't *need* to do this, but I do and I'd like to be able to do so like this: x = open('file_name') print x.read().reverse() *OR* print reverse(x.read()) x.close() To me, that makes sense. Of course, like I said earlier, I think backwards. -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
Tim Chase wrote: > Well, there you go! Apparently, your wet paper bag has no "detect a > palendrome" exit. While you're installing such an egress to your soggy > dead-tree satchel, you could also provide similar "write a binary Glad you guys are enjoying this. We're getting off-topic and I think my point is being lost to jest. As humans, we know very little. But one of the basics of our knowledge is order or sequence. 1,2,3,4 is natural so is 4,3,2,1 (count down to blast off for example). When we put our shirt on inside-out or watch someone moon walk (Micheal Jackson) it's immediately obvious and easy to see that the sequence is reversed. Backwards is pure, simple and easy. This is not so in Python and it should be. That's all I have to day about that. -- http://mail.python.org/mailman/listinfo/python-list
Re: invert or reverse a string... warning this is a rant
Fredrik Lundh wrote: > "Brad" <[EMAIL PROTECTED]> wrote: > >> Do you have children? How would your child feel if he brought you >> something he had made and you then told him it was awful in *sooo* many >> ways. > > If you're arguing that everything a child does and says should be rewarded... I'm not arguing that. Only that one should be polite and considerate when giving advice. That's all. foo[::-1] is acceptable. So is the helper function that you posted: > def reverse(s): > return s[::-1] My 2 min hack is awful to some, and I'm OK with that and fully expect it. But it works OK for me. Is there not room for solutions such as this in Python? No hard feelings. Let's close this thread. I'll accept the slicing and memorize it. Thanks guys. -- http://mail.python.org/mailman/listinfo/python-list
Re: introspection
Fredrik Lundh wrote: > brad tilley wrote: > >> How do I import a module and then ask it to show me its methods or >> other aspects about itself during execution? I'd like to do something >> such as this: >> >> import win32api > > dir(win32api) > help(win32api) > > and also > > import inspect > help(inspect) > > > Great info guys! Thanks. -- http://mail.python.org/mailman/listinfo/python-list
optparse
Consider the following piece of code: parser = optparse.OptionParser(usage="usage: %prog [options]", add_help_option=False) parser.add_option("-d", type="string", action="store", dest="DELIM", default="|", help="single character delimiter in quotes (default: |)") (options, args) = parser.parse_args() Is there any way I can add help for the arguments ( and ) in the same table that optparse generates above the options section. Ideally, I would like the output as: == usage: DelimTOFixedWidth.py [options] required: input filename name of the delimited input file output filename name of fixed-width output file options: -d DELIM single character delimiter in quotes (default: |) == Is that possible using optparse? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: optparse
OK, using that convention, how would I create help for , , etc. Thanks. On 9/27/2006 12:44 AM, Ben Finney wrote: > rick <[EMAIL PROTECTED]> writes: > >> usage: DelimTOFixedWidth.py [options] > > That's not the command-line argument style that optparse models. It > should be: > > command_name [options] > > In other words, the options (optionally) appear before the non-option > arguments. This is the convention followed by most command-line tools, > and it's what users expect. > > There are other command-line parser modules (e.g. argparse), perhaps > you can look to them for different functionality. > -- http://mail.python.org/mailman/listinfo/python-list
turbogears app deployment
I am trying to host a TuboGears app using Apache and mod_python on a machine running Windows XP SP2 Professional. Version info: apache_2.2.3-win32-x86-no_ssl.msi, python-2.4.4.msi, mod_python-3.2.10.win32-py2.4-apache2.2.exe, mpcp-1.5.tar.gz, turbogears-1.0b2-py2.4 = 1. Installed Apache. 2. Installed python, turbogears, mod_python. Added LoadModule python_module modules/mod_python.so to conf\httpd.conf. The mod_python example is working. 3. In order to host a simple TG application, I am using the bookmarker application which is in the TurboGears book (v1 from Chap 4). That works when I run it locally on my machine (also a WinXP SP2 box). Copied the application to "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs" 4. Made the following changes to conf\httpd.conf Changed AllowOverride for .htaccess to: AllowOverride All 5. Renamed start file to bookmarker_start.py. Created a file called .htaccess in bookmarker directory which has the following SetHandler mod_python PythonHandler mpcp PythonDebug On PythonOption cherrysetup bookmarker_start::mp_setup 6. Copied mpcp.py to the bookmarker directory (tried with installing it using easy_install -Z mpcp, didn't help). 7. Changed bookmarker_start.py #turbogears.start_server(Root())<--- commented this line and added the lines below. def mp_setup(): pass if __name__ == "__main__": cherrypy.server.start() = I have restarted the Apache daemon multiple times. When I try to connect to http://machine/bookmarker, I get: Mod_python error: "PythonHandler mpcp" Traceback (most recent call last): File "C:\Python24\Lib\site-packages\mod_python\apache.py", line 299, in HandlerDispatch result = object(req) File "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/bookmarker/mpcp.py", line 38, in handler setup(req, options) File "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs/bookmarker/mpcp.py", line 22, in setup cherrypy.server.start(init_only=True, server_class=None) File "c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\_cpserver.py", line 72, in start Engine.start(self) File "c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\_cpengine.py", line 91, in start autoreload.main(self._start, freq=freq) File "c:\python24\lib\site-packages\CherryPy-2.2.1-py2.4.egg\cherrypy\lib\autoreload.py", line 63, in main sys.exit(restart_with_reloader()) SystemExit: 1 Any idea what the problem is? Thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Simple server using asyncore/asynchat
Hey folks. I'm trying to create a (fairly) simple server that listens for connections and when it receives one sends a message to the client and then waits for a response (and would continue to do that). My problem is, every time my client connects, the server doesn't send the text and then immediately closes the connection with the client, but DOES print that the client was connected. Anyone know why? Here's my code: # conn.py import socket import asyncore import asynchat import string host = 'localhost' #socket.gethostname () port = 8017 buf = 1024 class ConnChannel (asynchat.async_chat): def __init__(self, conn): self.conn = conn def handle_connect(): self.send(self.conn, "Hello, Welcome to BasicMUD.\r\n") # it doesn't do thise self.numberclients = self.numberclients + 1 # or this self.send(self.conn, "There are " + self.numberclients + " players online.") # or this print "Client connected!" # it prints this def handle_read(self): print self.recv(8192) def handle_write(self): print "sending" class ConnTube (asyncore.dispatcher): def __init__(self, hostd, portd): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM ) self.bind ( ( hostd , portd ) ) self.listen ( 5 ) self.numberclients = 0 def handle_accept(self): channel, addr = self.accept() ConnChannel(channel) connTube = ConnTube(host, port) asyncore.loop() Thanks everyone! Rick -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling gives very different predictions of best algorithm
Sorry, I'm running the function: def debugsuite(): import profile,pstats profile.run('runsuite()','prof') prof = pstats.Stats('prof') prof.strip_dirs().sort_stats('time').print_stats(15) where runsuite() runs the Hartree-Fock energy of a water molecule, and is given by: import unittest,logging from PyQuante.CI import CIS from PyQuante.Molecule import Molecule from PyQuante.MP import MP2 from PyQuante.OEP import oep_hf,oep_hf_an from PyQuante.PyQuante2 import SCF,SubspaceSolver,DmatSolver class UnitTests(unittest.TestCase): def setUp(self): from PyQuante.Molecule import Molecule self.h2o = Molecule('h2o',[(8,(0,0,0)),(1,(1.,0,0)),(1, (0,1.,0))], units="Angstrom") def testH2OHF(self): h2o_hf = SCF(self.h2o,method='HF') h2o_hf.iterate() self.assertAlmostEqual(h2o_hf.energy,-76.011755864850628,4) def runsuite(verbose=True): # To use psyco, uncomment this line: #import psyco; psyco.full() if verbose: verbosity=2 else: verbosity=1 # If you want more output, uncomment this line: #logging.basicConfig(format="%(message)s",level=logging.DEBUG) suite = unittest.TestLoader().loadTestsFromTestCase(UnitTests) unittest.TextTestRunner(verbosity=verbosity).run(suite) # Running without verbosity is equivalent to replacing the above # two lines with the following: #unittest.main() return On May 1, 3:50 pm, Terry Reedy wrote: > Rick Muller wrote: > > I'm the main programmer for the PyQuante package, a quantum chemistry > > package in Python. I'm trying to speed up one of my rate determining > > steps. Essentially, I have to decide between two algorithms: > > > 1. Packed means that I compute N**4/8 integrals, and then do a bunch > > of indexing operations to unpack; > > 2. Unpacked means that I compute all N**4 integrals, but don't have to > > do any indexing. > > > Raw timing the two options show that packed is clearly faster (12.5 > > sec vs 20.6 sec). However, the profilings show very different results. > > I have the results below. Clearly I'm going to use the packed scheme. > > My question to the mailing list is what am I doing wrong with my > > profiling that it shows such poor predictions? > > That *might* be easier to answer if you were to show exactly what you > did to get the odd-looking results ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling gives very different predictions of best algorithm
On May 1, 7:38 pm, Terry Reedy wrote: > I presume in your overall time text, you ran the two versions of the > algorith 'naked'. But, for some reason, you are profiling them embedded > inside a test suite and runner. It does not seem that this should > affect relative timing, but I have seen some pretty strange behaviors. > At best, it will add noise. > > Let me expand my question: what did you do differently between the two > profile runs? When I compute the electron repulsion integrals, the two different methods are: if packed: ijkl = intindex(i,j,k,l) Ints[ijkl] = coulomb(bfs[i],bfs[j],bfs [k],bfs[l]) else: val = coulomb(bfs[i],bfs[j],bfs[k],bfs[l]) Ints[i,j,k,l] = val Ints[j,i,k,l] = val Ints[i,j,l,k] = val Ints[j,i,l,k] = val Ints[k,l,i,j] = val Ints[k,l,j,i] = val Ints[l,k,i,j] = val Ints[l,k,j,i] = val and when I access the integrals the differences are: if packed: index = intindex(i,j,k,l) temp[kl] = Ints[index] else: temp[kl] = Ints[i,j,k,l] If you look at the profiling, I'm making something like 11M calls to intindex, which is a routine I've written in C. I thought that by storing all N**4 integrals (rather than the N**4/8 that packed stores) would remove the need for the intindex calls and speed things up, but it's 50% slower. I can't really figure out why it's slower, though, since profiling makes it look like the slower version is faster. Something like 30% of the time for the full PyQuante test suite is taken up with calls to intindex, and I'd like to remove this if possible. I also wrote a version of the code where I stored all of the intindex values in a Python dictionary rather than calling a C function. That version appeared to be roughly the same speed when I profiled the code, although I didn't test it without profiling (stupidly) because at that point I didn't recognize the magnitude of the discrepancy between the profiling/nonprofiling timings. I was posting to the list mostly because I would like to know whether I can do something different when I profile my code so that it give results that correspond more closely to those that the nonprofiling results give. -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling gives very different predictions of best algorithm
On May 2, 9:10 am, Rick wrote: > I was posting to the list mostly because I would like to know whether > I can do something different when I profile my code so that it give > results that correspond more closely to those that the nonprofiling > results give. A good comment that was emailed to me rather than being posted to the list was to use cProfile rather than profile. Doing this gave much more realistic results. -- http://mail.python.org/mailman/listinfo/python-list
using time.gov to get the current time
Is there any way to get the current time from time.gov using urllib2 or something similar? Does anyone have any examples of doing this? Thanks! Rick King Southfield MI -- http://mail.python.org/mailman/listinfo/python-list
Sending ^C
Hi, I am to write script which is to read data from log file which resides on remote host. It's a simple text file but grows to couple of MBytes. I want to do ssh connection to remote, and run 'tail -f _some_file_' command to read only new coming data and process them in the loop. The problem is, I don't know how to deal with it when log file rotates and change name. I need then to break running 'tail -f _some_file_' and excecute 'tail -f _other_file'. Can you give me hints how to do this? Regards Rick -- http://mail.python.org/mailman/listinfo/python-list
Display file names in Tkinter Listbox
Hello, My first attenpt at a simple python Tkinter application. I wanted to see how to load file names into a listbox from a menu. This is what I got until the part of displaying the file names in a listbox, which I could not figfure out how to do? Any help would be appreciated. Trying to do this as simple as possible to understand. The "print fileNames" does work but how to display it in listbox? from Tkinter import * from tkFileDialog import askopenfilenames class MyCode: def __init__(self): root = Tk() menubar = Menu(root) filemenu = Menu(menubar) lbox = Listbox(root, width=50).pack() menubar.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New Project') filemenu.add_command(label='Load Files...', command=self.OnLoad) filemenu.add_command(label='Exit', command=root.quit) root.config(menu=menubar) root.mainloop() def OnLoad(self): fileNames = askopenfilenames(filetypes=[('Split Files', '*')]) print fileNames myApp = MyCode() -- http://mail.python.org/mailman/listinfo/python-list
Re: How clean/elegant is Python's syntax?
On Wednesday, May 29, 2013 7:24:48 PM UTC-5, Dan Stromberg wrote: > About the only thing I don't like is: > > var = 1, > > That binds var to a tuple (singleton) value, instead of 1. I don't understand why Python needs tuples anyway; at least not tuple literals!. I mean, i like the idea of a sequence type that is immutable as much as the next fella, however, i just hate the fact that we had to pay for this type with syntactical multiplicity only to be forever a slave to it's resulting quirkiness! Psst: Guido, i think you got screwed! (And they thought Jack was a fool for acquiring those beans!) With the demand for type literals growing all the larger as time goes on and the ASCII char set remaining static, there must be a better way! (And no folks, I'm not suggesting space cadet keyboards!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Short-circuit Logic
> On Fri, May 31, 2013 at 2:58 AM, rusi wrote: > > On May 30, 5:58 pm, Chris Angelico wrote: > > > The alternative would be an infinite number of iterations, which is far > > > far worse. > > > > There was one heavyweight among programming teachers -- E.W. Dijkstra > > -- who had some rather extreme views on this. > > > > He taught that when writing a loop of the form > > > > i = 0 > > while i < n: > > some code > > i += 1 > > > > one should write the loop test as i != n rather than i < > > n, precisely because if i got erroneously initialized to > > some value greater than n, (and thereby broke the loop > > invariant), it would loop infinitely rather than stop > > with a wrong result. > > > > And do you agree or disagree with him? :) I disagree with > Dijkstra on a number of points, and this might be one of > them. When you consider that the obvious Pythonic version > of that code: > > for i in range(n,m): > some code Maybe from your limited view point. What if you need to perform operations on a sequence (more than once) in a non-linear fashion? What if you need to modify the sequence whilst looping? In many cases your simplistic "for loop" will fail miserably. py> lst = range(5) py> for n in lst: ... print lst.pop() 4 3 2 Oops, can't do that with a for loop! py> lst = range(5) py> while len(lst): ... print lst.pop() 4 3 2 1 0 -- http://mail.python.org/mailman/listinfo/python-list
PyWart: The problem with "print"
Note to those of you who may be new to Python: I will refer to "print" as a function -- just be aware that "print" was a statement before Python3000 was introduced. Introduction: Many languages provide a function, method, or statement by which users can write easily to stdout, and Python is no exception with it's own "print" function. However, whilst writing to stdout via "print" is slightly less verbose than calling the "write" method of "sys.stdout", we don't really gain much from this function except a few keystrokes... is this ALL print should be? A mere syntactical sugar? For me, i think the "print" function CAN and SHOULD be so much more! Print's Role in Debugging: A print function can be helpful in many ways, and one very important role print plays is to inform the programmer of internal states of objects via debug messages written to stdout. Sure, there are fancy debuggers by which internal state and object identity can be inspected on the fly, however, "print" is always going to be there no matter what libraries or add-on you have available. And let's face it folks, print is the most simplistic and intuitive interface you'll ever find for debugging purposes. Sure, "print" may not be the most productive for large scale debugging, but for the majority of debugging tasks, it's a good fit. I know some of you will cringe at the idea of using print for debugging, however, i will argue that using a debugger can weaken your detective skills. If an exception message and trackback are not giving you enough information to find the bug, well then, the language OR the code you've written is not worth a monkey's toss! I've found that many subtle bugs are caused by not limiting the inputs to sane values (or types). And with Python's duct typing and implicit casting to Boolean, you end up with all sorts of misleading things happening! Maybe you're testing for truth values and get a string instead; which screws everything up!!! Anyhoo, i digress... Inadequacies of "print" Debugging. In it's current implementation, print is helpful, but in many ways, print is lacking it's true potential. Many of the problems that propagate up when using print as a debugger focus on the fact that you cannot easily switch the debug messages "on" or "off". Sure, you can comment-out all calls to print, but if you need to see the messages again you will be forced to uncomment all the lines again... hey that's no fun! A "wise programmer" may think he's solved the problem by writing a function called "debugprint" that looks like this: def debugprint(*args): if DEBUG == True: print(*args) However that solution is at best woefully inadequate and at worse a cycle burner! * Woefully inadequate because: Switching on or off the debug messages is only valid in the current module that the function was imported. What if you want to kill all debugprint messages EVERYWHERE? Do you really want to edit "debug = BOOLEAN" in every source file OR do something stupid like import debugprint and edit the DEBUG constant OR even dumber, edit the debugprint source code? GAWD NO! * But even if you are willing to cope with all the "switch- on-and-off" nonsense, are you willing to have you code slowed by numerous calls to a dead function containing a comparison that will always be false? ## START INTERACTIVE SESSION ## py> from __future__ import print_function py> DEBUG = True py> def debugprint(*args): ... if not DEBUG: ... return ... print(*args) py> debugprint("foo", "bar") foo bar py> DEBUG = False py> code = compile('debugprint("foo", "bar")', '', 'exec') py> import dis py> dis.disassemble(code) 1 0 LOAD_NAME0 (debugprint) 3 LOAD_CONST 0 ('foo') 6 LOAD_CONST 1 ('bar') 9 CALL_FUNCTION2 12 POP_TOP 13 LOAD_CONST 2 (None) 16 RETURN_VALUE ## END INTERACTIVE SESSION ## After a few million executions of this superfluous comparison your cpu is losing faith in your ability to write logical code! py> function.call() + false_comparison() == 'cycle burner' "YOU BET YOU A$$ IT DOES!!" Solution. This realization has brought me to the conclusion that Python (and other languages) need a "scoped print function". What i
Re: PyWart: The problem with "print"
On Jun 2, 12:20 pm, Chris Angelico wrote: > On Mon, Jun 3, 2013 at 3:04 AM, Rick Johnson > > * Woefully inadequate because: Switching on or off the debug > >messages is only valid in the current module that the > >function was imported. What if you want to kill all > >debugprint messages EVERYWHERE? Do you really want to edit > >"debug = BOOLEAN" in every source file OR do something > >stupid like import debugprint and edit the DEBUG constant > >OR even dumber, edit the debugprint source code? GAWD NO! > Easy fix to this one. Instead of copying and pasting debugprint into > everything, have it in a module and import it everywhere. Then the > debug flag will be common to them all. Ignoring the fact that you have "import everywhere", what if you want to stop ALL debug messages? If you "import everywhere" to get them, you then have to "edit everywhere" to stop them. > Oh, and you probably want to add **kwargs to debugprint, because the > print function does a lot more than sys.stdout.write does: The kwargs to print are not germane to the issue, however noobs may be watching so glad you pointed that one out. > [...] > py> timeit.timeit('debugprint("asdf") [...] > 0.5838018519113444 > > That's roughly half a second for a million calls to debugprint(). > That's a 580ns cost per call. Rather than fiddle with the language, > I'd rather just take this cost. I never purposely inject ANY superfluous cycles in my code except in the case of testing or development. To me it's about professionalism. Let's consider a thought exercise shall we? Imagine your an auto mechanic. You customer brings in his car and asks you to make some repairs. You make the repairs but you also adjust the air/fuel ratio to run "rich" (meaning the vehicle will get less MPG). Do you still pat yourself on the back and consider you've done a professional job? I would not! However, you're doing the same thing as the mechanic when your code executes superflouos calls and burns cycles for no other reason than pure laziness. CPU's are not immortal you know, they have a lifetime. Maybe you don't care about destroying someone's CPU, however, i do! I just wonder how many of your "creations" (aka: monstrosities!) are burning cycles this very minute! > [...] > So you can eliminate part of the cost there, if it matters to you. If > a half-microsecond cost is going to be significant to you, you > probably should be looking at improving other areas, maybe using > ctypes/cython, or possibly playing with the new preprocessor tricks > that have been being discussed recently. There's really no need to > change the language to solve one specific instance of this "problem". That's like suggesting to the poor fella who's MPG is suffering (because of your incompetent adjustments!) to buy fuel additives to compensate for the loss of MPG. Why should he incur costs because you are incompetent? -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with "print"
On Sunday, June 2, 2013 12:49:02 PM UTC-5, Dan Sommers wrote: > On Mon, 03 Jun 2013 03:20:52 +1000, Chris Angelico wrote: > > On Mon, Jun 3, 2013 at 3:04 AM, Rick Johnson > [...] > Or use the logging module. It's easy to get going quickly > (just call logging.basicConfig at startup time), and with > a little care and feeding, you can control the output in > more ways than can fit into the margin. Oh, yeah, I'm sure > it introduces some overhead. So does everything else. I hate log files, at least during development or testing. I prefer to debug on the command line or using my IDE. Log files are for release time, not development. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with "print"
On Sunday, June 2, 2013 1:58:30 PM UTC-5, Steven D'Aprano wrote: > On Sun, 02 Jun 2013 10:04:00 -0700, Rick Johnson wrote: Oh Steven, you've really outdone yourself this time with the theatrics. I hope you scored some "cool points" with your minions. Heck, you almost had me convinced until i slapped myself and realized your whole argument is just pure BS. For the sake of the lemmings, i must dissect your BS and expose it's methane emitting innards for all to smell. > > Many > > languages provide a function, method, or statement by which users can > > write easily to stdout, and Python is no exception with it's own "print" > > function. However, whilst writing to stdout via "print" is slightly less > > verbose than calling the "write" method of "sys.stdout", we don't really > > gain much from this function except a few keystrokes... is this ALL > > print should be? A mere syntactical sugar? > > Perhaps you should read the docs before asking rhetorical questions, > because the actual answer is, No, print is not mere syntactical sugar > saving a few keystrokes. > [...] And perhaps you should read a dictionary and obtain (at minimum) a primary school level education in English before making such foolish statements, because, OBVIOUSLY you don't know the definition of "syntactical sugar"... shall i educate you? # Wikipedia: "syntactic sugar" # # In computer science, syntactic sugar is syntax within a # # programming language that is designed to make things # # easier to read or to express. It makes the language # # "sweeter" for human use: things can be expressed more# # clearly, more concisely, or in an alternative style that # # some may prefer[...] # The print function is the very definition of a "syntactic sugar". For example: print("some sting") is much more readable than: sys.stdout.write("some string"+"\n") or: sys.stderr.write("some string"+"\n") or: streamFoo.write("blah") But wait, there's more! # Wikipedia: "syntactic sugar" (continued) # # [...]Specifically, a construct in a language is called # # syntactic sugar if it can be removed from the language # # without any effect on what the language can do: # # functionality and expressive power will remain the same. # Again, the removal of a print function (or print statement) will not prevent users from calling the write method on sys.stdout or sys.stderr (or ANY "stream object" for that matter!) The only mistake i made was to specify stdout.write specifically instead of generally referring to the print function as a sugar for "stream.write()". > > I've found that many subtle bugs are caused by not limiting the inputs > > to sane values (or types). And with Python's duct typing > [...] > > and implicit > > casting to Boolean, you end up with all sorts of misleading things > > happening! Maybe you're testing for truth values and get a string > > instead; which screws everything up!!! > Only if you're a lousy programmer who doesn't understand Python's truth > model. I understand the Python truth model quite well, i just don't happen to like it. Implicit conversion to Boolean breaks the law of "least astonishment". Many times you'll get a result (or an input) that you expect to be a Boolean, but instead is a string. A good example of poor coding is "dialog box return values". Take your standard yes/no/cancel dialog, i would expect it to return True|False|None respectively, HOWEVER, some *idiot* decided to return the strings 'yes'|'no'|'cancel'. If you tried to "bool test" a string (In a properly designed language that does NOT support implicit Boolean conversion) you would get an error if you tried this: py> string = " " py> if string: ... do_something() ERROR: Cannot convert string to Boolean! However, with Python's implicit conversion to Boolean, the same conditional will ALWAYS be True: because any string that is not the null string is True (as far as Python is concerned). This is an example of Python devs breaking TWO Zens at once:
Re: PyWart: The problem with "print"
On Monday, June 3, 2013 10:16:13 PM UTC-5, Vito De Tullio wrote: > Rick Johnson wrote: > > Take your > > standard yes/no/cancel dialog, i would expect it to return > > True|False|None respectively, > you clearly mean True / False / FileNotFound. No, i clearly meant what i said :-). FileDialogs only return one of two values; either a valid path or a value representing "failure". I suppose FileNotFound is a custom exception? That will work however i wonder if exception handling is overkill for this? try: path = filedialog.open("path") except FileNotFound: return do_something(path) As opposed to: path = filedialog.open("path") if path: do_something(path) Or, if Python was really cool! if filedialog.open("path") as path: do_something(path) However, i think True|False|None is the best return values for a yes|no|cancel choice. Consider: result = yesnocancel("save changes?") if result: # Try to save changes and close. if self.fileSave(): app.close() else: show_error() elif result is False: # Close without saving changes. app.close() else: # Canceled: Do nothing. return -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Tuesday, June 4, 2013 12:39:59 AM UTC-5, Steven D'Aprano wrote: > On Mon, 03 Jun 2013 18:37:24 -0700, Rick Johnson wrote: > Consider a simple thought experiment. Suppose we start with a sequence of > if statements that begin simple and get more complicated: > if a == 1: ... > if a == 1 and b > 2*c: ... > if a == 1 and b > 2*c or d%4 == 1: ... > if a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0: ... > I don't believe that any of these tests are improved by adding an > extraneous "== True" at the end: > if (a == 1) == True: ... > if (a == 1 and b > 2*c) == True: ... > if (a == 1 and b > 2*c or d%4 == 1) == True: ... > if (a == 1 and b > 2*c or d%4 == 1 and not (d**3//7)%3 == 0) == True: ... And i agree! You are misunderstanding my very valid point. Post-fixing a "== True" when truth testing a *real* Boolean (psst: that's a True or False object) is superfluous, I'm referring to truth testing non-Boolean values. So with that in mind, the following is acceptably "explicit enough" for me: a = True if a: do_something() However, since Python allows implicit conversion to Boolean for ALL types, unless we know for sure, beyond any reasonable doubt, that the variable we are truth testing is pointing to a True or False object, we are taking too many chances and will eventually create subtle bugs. a = " " if a: do_something() When if write code that "truth tests", i expect that the value i'm testing is a True or False object, not an empty list that *magically* converts to False when i place an "if" in front of it, or a list with more members that magically converts to True when i place an "if" in front of it. This implicit conversion seems like a good idea at first, and i was caught up in the hype myself for some time: "Hey, i can save a few keystrokes, AWESOME!". However, i can tell you with certainty that this implicit conversion is folly. It is my firm belief that truth testing a value that is not a Boolean should raise an exception. If you want to convert a type to Boolean then pass it to the bool function: lst = [1,2,3] if bool(lst): do_something This would be "explicit enough" > If you are unfamiliar with Python, then you have to learn what the > semantics of "if lst" means. Just as you would have to learn what > "if len(lst) > 0" means. Again, i understand the folly of "implicit Boolean conversion" just fine. > > I prefer to be explicit at the cost of a few keystrokes: > > if len(lst) > 0: > This line of code is problematic, for various reasons: > - you're making assumptions about the object which are unnecessary; > - which breaks duck-typing; > - and risks doing too much work, or failing altogether. > You're looking up the length of the lst object, but you don't really care > about the length. Yes i do care about the length or i would not have asked. I'm asking Python to tell me if the iterable has members, amd if it does, i want to execute a block of code, if it does not, i want to do nothing. But i'm also informing the reader of my source code that the symbol i am truth testing is expected to be an iterable with a __len__ method. "if lst" does not give me the same answer (or imply the same meaning to a reader), it merely tells me that the implict conversion has resulted in a True value, but what if the lst symbol is pointing to a string? Then i will falsely believe i have a list with members when i actually have a string with length greater than zero. > You only care about whether there is something there or > not, whether lst is empty or not. It makes no difference whether lst > contains one item or one hundred million items, and yet you're asking to > count them all. Only to throw that count away immediately! I agree. Summing the list members just to guarantee that the iterable has members is foolish, however, python gives me no other choice IF i want to be "explicit enough". In a properly designed language, the base iterable object would supply a "hasLength" or "hasMembers" method that would return a much faster check of: try: iterable[0] except IndexError: return False else: return True That check would guarantee the iterable contained at least one member without counting them all. > Looking at the length of a built-in list is cheap, but why assume it is a > built-in list? Perhaps it is a linked list where counting the items > requires a slow O(N) traversal of the entire list. Or some kind of lazy > sequence that has no way of counting the items remaining, but knows > whether it is exhausted or not. Yes, but the problem
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Jun 4, 10:44 am, Rick Johnson wrote: > What we need is a method by which we can validate a symbol > and simultaneously do the vaidation in a manner that will > cast light on the type that is expected. In order for this > to work, you would need validators with unique "type names" > > if var.is_validList(): > elif var.is_validString(): > elif var.is_vaildTuple(): > elif var.is_validInteger(): > elif var.is_validFloat(): > elif var.is_validDict(): > etc... Actually, instead of forcing all types to have many "specific" methods, one builtin could solve the entire issue. The function would be similar to isinstance() taking two arguments "object" and "type", however, it will not only guarantee type but also handle the conversion to Boolean: if is_valid(var, list): # if this block executes we know # the var is of and # var.length is greater than one. else: # if this block executes we know # that var is not of # or, var.length equals zero. The is_valid function would replace implicit Boolean conversion for all types in manner that is "explicit enough" whilst maintaining finger longevity. This is how you design a language for consistency and readability. Again. PUCKER UP WHO-VILLE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Jun 4, 11:00 am, Chris Angelico wrote: > You know, if you want a language with strict type declarations and > extreme run-time efficiency, there are some around. I don't like declaring types everywhere, i hate it. I prefer duck typed languages, HOWEVER, in order for duck typing to work consistently you must have checks and balances that the programmer can apply when he feels necessary. My "is_valid" built in will bridge the gap. We won't be forced to declare types, but we should ALWAYS add "type checks" to our "truth tests" unless we want to create subtle bugs. "is_valid" IS the answer! -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Jun 4, 12:42 pm, Ian Kelly wrote: > > By this manner, we can roll three common tests into one > > method: > > * Boolean conversion > > * member truthiness for iterables > > * type checking > How exactly does this is_valid method perform the first two? Are you > suggesting that an empty sequence should not be considered "valid"? I'm suggesting that the rules for Python's current "implicit conversion to Boolean" simply be moved into a "explicit function" named "isvalid", that also does a type check. Here is some Python code that might help you understand. py> def isvalid(object_, type_): ... if isinstance(object_, type_) and object_: ... return True ... return False py> isvalid([], list) False py> isvalid([1], list) True py> isvalid(0, int) False py> isvalid(1, int) True py> isvalid({}, dict) False py> isvalid("", str) False py> isvalid(" ", str) True Now, let's go back to my earlier example of where i was expecting a list but got a string instead. If i use Python's current implicit conversion to Boolean my code will do something i don't want it to do. py> lst = " " py> if lst: ... print("I'm a liar") ... else: ... print("I'm honest") I'm a liar But unlike this simple example (which failed quickly) in the real world, it may not fail for a long time. And when it does fail, you will be pulling your hair out tracking down the origin of the bug. If however i use my "isvalid" function, my conditional will not lie to me: py> lst = " " py> if isvalid(lst, list): ... print("I'm a liar") ... else: ... print("I'm honest") I'm honest Now. You're not always going to need to "isvalid" function. Sometimes you just need to test type, sometimes you just need convert to Boolean, and sometimes you can just fly by the seat of your pants. The point is, remove implicitly and inject explicitly. Furthermore: If the current "implicit conversion to Boolean" can be optimized by Python, then there is no reason why an explicit "isvalid" function cannot -- any talk to the contrary is just BS. If you still feel that this idea is garbage, then, keep on writing your sloppy code. My proposal is the best method to handle the problems that arise with duck typed languages in a manner that is not restrictive or laborious -- it's actually quite elegant. *school-bell-rings* -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Wednesday, June 5, 2013 11:59:07 AM UTC-5, Chris Angelico wrote: > Frankly, I don't think the language much matters. It's all > down to the skill of the programmers and testers. Ada > wasn't the source of the problem unless Ada has a bug in > it... which is going to be true of pretty much any > language. Maybe Python would be a better choice, maybe > not; but let me tell you this, if the choice of language > means the difference between testable in three months and > testable code in three years, I'm going for the former. Yes EVEN IF life or property hangs in the balance, the only important decision is how much work YOU will be required to do -- Chris, why i am not amazed by this bombastic display of selfishness? -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Wednesday, June 5, 2013 6:18:13 PM UTC-5, Michael Torrie wrote: > On 06/05/2013 12:11 AM, Russ P. wrote: > > But then, what would you expect of a language that allows you to > > write > > x = 1 > > x = "Hello" > > It's all loosey goosey -- which is fine for many applications but > > certainly not for critical ones. > This comment shows me that you don't understand the difference between > names, objects, and variables. May sound like a minor quibble, but > there're actually major differences between binding names to objects > (which is what python does) and variables (which is what languages like > C have). It's very clear Rick does not have an understanding of this > either. Just because someone does not "prefer" this or that aspect of Python, does not mean they don't understand it. I understand "implicit conversion to Boolean" just fine, however, i don't like it. Actually, i hate it! I think it's foolish. It was invented by people who rather save a few keystrokes at the cost writing cryptic code. There are many good reasons for saving keystrokes, implicit conversion to Boolean is NOT one of them. I make the same argument for "return". Some languages allow implicit return values from functions/methods. When writing a function with Ruby, the return statement is optional: ## START RUBY CODE ## def foo: "implicit return" end rb> puts foo "implicit return" ## END RUBY CODE ## This is one area where Python shines! In Python, if you fail to use the return statement, then Python will return None, NOT some some value that just happens to be the last line executed in the function -- Ruby breaks the law of least astonishment. The point is we must balance our selfish need to save keystrokes against the need of a reader to QUICKLY understand what he is reading. Python's "explicit return statement" satisfies both requirements, whereas, the optional return value of Ruby does not. We don't want to overly implicit, or overly explicit (as in the nightmare of "public static void foo", which is overkill (at least for a language as high level as Python)). -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Wednesday, June 5, 2013 2:15:57 AM UTC-5, Chris Angelico wrote: > [...] > I cannot name a single modern programming language that does NOT have > some kind of implicit boolification. Congrats: Again you join the ranks of most children who make excuses for their foolish actions along the lines of: "Hey, they did it first!" Well, the lemmings get what they deserve i suppose. -- http://mail.python.org/mailman/listinfo/python-list
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Wednesday, June 5, 2013 8:37:20 PM UTC-5, Steven D'Aprano wrote: > On Wed, 05 Jun 2013 09:15:01 -0700, Russ P. wrote: > > On Wednesday, June 5, 2013 1:59:01 AM UTC-7, Mark Lawrence wrote: > >> On 05/06/2013 07:11, Russ P. wrote: > What prevents bugs is the skill of the people writing the code, not the > compiler. Compile-time static type checking is merely a tool, which has > costs and benefits. It is ludicrous to think that any one single tool, or > the lack of that tool, will make all the difference between working code > and non-working code. Yes, just as ludicrous as thinking that dynamic languages have abolished the evil practice of "type checking". > Static type-checking is no better, or worse, for "critical code" than > dynamic type-checking. One language chooses to deal with some errors at > compile-time, others deal with them at run-time. Wow, talk about ignoring the elephant in the room! I don't feel i need static typed languages for EVERY problem, however, i'm not foolish enough to believe that "compile time type checking" and "run-time type checking" are even comparable. Oversimplification? > Either way, the > programmer has to deal with them in some way. > A static type system forces you to deal with a limited subset of errors, > "type errors", in one way only: by removing any execution paths in the > software which would assign data of type X to a variable of type Y. For > reasons of machine efficiency, that is often a good was to deal with such > errors. But a dynamic type system makes different trade-offs. > And of course, type errors are such a vanishingly small subset of all the > possible errors that might be made that, frankly, the difference in code > quality between those with static typing and those without is essentially > indistinguishable. There's no evidence that code written in static typed > languages is less buggy than code written in dynamic languages. WOW! Your skill with the implicit Ad hominem is approaching guru status. First you cleverly convert the base argument of this ongoing discussion from: "implicit conversion to boolean is bad", into the hot button topic of: "static vs dynamic typing". In this manner you can ratchet up the emotion of your supporters by employing the same political "slight of hand" used by countless political hacks: "Liberal vs Republican" ring a bell? When there is only two choices, the sheeple can be easily manipulated by the football game. Especially when the opposing sides have the same end-goal in mind. It's all a game of diversions you idiots! Then you go and make a blanket statement that "appears" to weigh the differences of the two styles fairly, when in fact, what you've done is to falsely invalidate the opposition's entire argument based on a complete overstatement (not to mention that you stopped short of explaining the "trade offs" in detail): > And of course, type errors are such a vanishingly > small subset of all the possible errors that might be > made that, frankly, the difference in code quality > between those with static typing and those without is > essentially indistinguishable. Nice! Well, then. You've slayed the enemy. If type errors are as rare as you claim, then by golly these crazy people who use static languages are really just fools. I mean, how could they not be? If they were as intelligent as YOU then they would see the truth! Your attempts at sleight of hand are rather amusing. The whole point of this "implicit conversion to Boolean" discussion hinges around the fact that dynamic languages are okay for small to medium problems ( or for prototyping larger problems). But they cannot be depended on for mission critical code. And mission critical does not only encompass manned flights to mars, it could be any code that places your reputation on the line. I don't want Python to be a static typed language. Neither do i believe that duck typing is wrong for Python. HOWEVER, what i DO believe is that dynamic languages can be unreliable if we do not: 1. Choose to be "explicit enough" I've explained this in detail Ad-nauseam. 2. Fail to type check where type checking is due. The second covers type checking objects that enter into new namespaces. That would cover all functions/methods arguments (at a minimum). We don't need to type check EVERY single object (but of course the programmer could IF he wanted to). If i declare a variable[1] that points to a list in a block of code, then i reference that variable[1] in the same block of code, i see no reason to type check that variable[1] first. That is overkill and that is why people are turned off by static languages. However, if i declare the same variable[1] and then pass that variable[1] into a function, the function should do a type check on all the arguments to guarantee that these arguments are in fact what they should be. This is how you strike a balance between explicit and
Re: Bools and explicitness [was Re: PyWart: The problem with "print"]
On Thursday, June 6, 2013 1:03:24 PM UTC-5, Rick Johnson wrote: > The second covers type checking objects that enter into new > namespaces. That would cover all functions/methods arguments > (at a minimum). Yeah, before anyone starts complaining about this, i meant to say "scope". Now you can focus on the *real* argument instead of spending all your time pointing out minutiae. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On Sunday, June 9, 2013 8:21:43 AM UTC-5, Malte Forkel wrote: > I have asked the PSF for help regarding the implications of the license > status of code from sre_parse.py and the missing license statement in > sre.py. I'll happily report their answer to the list I they don't reply > in this thread. HaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHa (deep breath...) HaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHaHa I can't say much with great certainty about the leadership of this community, but what i can say for sure is they are NOT going to waste one second of their so-called "precious" time responding to legitimate questions (like yours). The Secret Labs license is very explicit: "All rights reserved". That line means you can't touch it under pain of lawsuit. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On Sunday, June 9, 2013 4:08:54 PM UTC-5, zipher wrote: > >> That's not entirely correct. If he *publishes* his code (I'm using > > >> this term "publish" technically to mean "put forth in a way where > > >> anyone of the general public can or is encouraged to view"), then he > > >> is *tacitly* giving up protections that secrecy (or *not* disclosing > > >> it) would *automatically* grant. The only preserved right is > > >> authorship after that. So it can be re-distributed freely, if > > >> authorship is preserved. The only issue after that is "fair use" and > > >> that includes running the program (not merely copying the source). > > > > > > No, the original author retains all rights except those explicitly > > > granted. The same way that obtaining the "source" to a song does not > > > give you the right to redistribute the song all you want. > > > > No, you are right only by the *word* of the law, but you have not > > included the authors *actions*. A court has to include both. > > > > He explicitly did not *retain* his rights when he *published* his > > code. There is not word of law that is necessary when his actions > > have already done the deed (unless under coercion, of course). > > > > > Fair use has nothing to do with money. It depends on how the work is > > > used and how you've changed it. Weird Al's song parodies are fair use, > > > even though he sells them. > > > > That can't really be claimed without a case being brought against him. > > Michael Jackson, for example, probably could have made a case against > > WierdAl, but did not -- that does not automatically mean that > > WierdAl's use was fair-use in the slightest. In fact, it probably was > > not, but MJ made enough money that he probably also didn't want to the > > PR loss. > > > > > You distributing copies of a commercial > > > software to everyone is not fair use, even though you aren't making > > > money. > > > > It *is* absolutely fair use, if that commercial software *published* > > their code (in the definition I gave earlier). If you stole the code > > off their protected servers, it is not fair use. > > > > >> Well this is where one must make a distinction with fair-use -- if I > > >> re-publish my modifications then the code is still subject to the > > >> terms by the original author. If I make a copy for myself and run the > > >> problem for personal, non-commercial use, then I am in the domain of > > >> fair use and have no other obligations. > > > > > > Again, no. The GPL does not restrict your rights when running on > > > machines you control, but that's just because of the terms of the > > > license. Most commercial licenses include terms like "no reverse > > > engineering the software" that have nothing to do with distribution. > > > > Close-source software could automatically be considered "protected", > > but that is only out of kindness. Publishing software, even > > closed-source software opens a company to some level > > reverse-engineering by the nature of computers and by the fact that > > the techniques of turning machine code into assembly are well known. > > So they explicitly state that they do not give permission to do so, > > yet this is not worth much of anything except for the fact that most > > people are intimidated to go against a large software company to argue > > their rights. > > > > Apparently these companies have already seen this loophole and have > > made things like DRM to put a legalistic container around what would > > otherwise be de facto published (machine) code. But this is not a > > legit workaround either and companies have essentially stealing from > > the intellectual and creative communities. > > > > There is no legitimate argument against a personal user figuring out > > how software works for personal use. If they don't want people to > > "figure it out", they'll have to open stores where people can run > > their special software on machines that are under their control. > > > > I'm sorry, this is just the way it is -- everyone's just gone along > > with the program tacitly because they get intimidated by the legal > > system. But the law is for people, not for lawyers. Preach on my brother, Preach on! It's amazing how much control you can leverage on the populace of lemmings from a few well placed tv ads and some OP-ED propaganda. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On Sunday, June 9, 2013 7:26:43 PM UTC-5, Steven D'Aprano wrote: > When you listen to a song on the radio, do you know how they have a > copyright announcer read out the copyright and explicitly list all the > rights they keep after each and every song and advertisment? > No, me neither. It doesn't happen. Because it's nonsense that you give up > copyright by publishing. The fact that media distributors think they can control source files in this day and age is just wishful thinking and even more foolish than the ongoing (and fruitless) two decade long "war on drugs". I can't decide which is worse: circumventing evolution for the sake of greed OR for the sake of blind altruism. [Tangential Meandering Ahead] What these "pseudo moral" fools fail to realize is that a certain segment of any group is doomed to failure. This is not my law, this is the law of the universe in which we live. """ But Rick you're heartless. What of the children? If we legalize drugs then kids will be addicts, some will even die!""" How many are dying now in the streets from gangland shootouts? How many lives are being ruined and minds are being brainwashed by the highly repetitive music spewing hateful lyrics, indoctrinating another generation into the dead-end thug lifestyle? By fighting a losing war to "protect" degenerates from themselves, we actually elevate the thug and destroy the collective well-being of all humanity. Let the drug addicts and alcoholics self-destruct! Put the thugs out of business by legalizing drugs and you take away their easy source of profit. Take away the profit and you reduce the influence of these punks over the minds of children. Take away the influence, and you break the cycle of a thug lifestyle. Only logic can only undo what decades of bleeding heart policies have utterly destroyed. Instead of wasting time saving people who are lost, you should focus your time (and money) on people who have a future, people who can be productive members of society, people who have a true moral compass. How many innocent people have to die before you idiot " pseudo moralist" realize that restricting personal choices is a lost cause? But more importantly, when are you going to realize that the blood of all the innocent lives lost is on your hands! But i digress... [Back on topic of Copyright/license Issues] Maintaining an ownership of "Yes, that was my idea" and "i should benefit from my idea for a limited amount of time" is great, but thinking you can squeeze every penny out of an idea to very detriment of our collective evolution is nothing less than a crime against humanity! (<-- that was NOT an exaggeration!) In the 80's huge record companies bilked consumers and artists for hundreds of millions of dollars. They had their day in the sun. But every good ponzie scheme comes to an end. Maybe i'll go cry in the corner for the corporate suits, or maybe not! The real losers where the artist who forfeited an egregious percentage of their potential earnings so the corporate suits could buy another jet or another summer home to impress their shallow friends. But this whole idea of "i was first so you're not allowed" is just nonsense. If someone can reproduce your work, then it must not have been much of a leap in the first place. Instead of squalling over who owns an idea (like two children fighting over a toy)try to inject uniqueness into your interpretation of the idea to make it your "very own". If you're an inventor, artist, musician, programmer, scientist, etc... your focus should be on creating the best idea you possibly can. If the thought of someone imitating or copying your idea keeps you awake at night, then don't release your idea to the public. In this day and age of the information revolution, any attempt to stop the propagation of your idea is foolish. Just as foolish as thinking that outlawing guns will end murder, or that some illogical "war on drugs" will ever be won, or that seat-belt laws exist because your government "cares" about your well-being -- Oh gawd your a bunch of idiots! "Authoritarian policies create side effects that are far worse than the miniscule problems the policies attempted to solve." -- http://mail.python.org/mailman/listinfo/python-list
Re: "Don't rebind built-in names*" - it confuses readers
On Monday, June 10, 2013 9:56:43 PM UTC-5, Steven D'Aprano wrote: > On Mon, 10 Jun 2013 20:14:55 -0400, Terry Jan Reedy wrote: > > For instance, open Lib/idlelib/GrepDialog.py in an editor that colorizes > > Python syntax, such as Idle's editor, jump down to the bottom and read > > up, and (until it is patched) find > > list.append(fn) > > with 'list' colored as a builtin. Stop. That looks wrong. List.append > > needs two arguments: a list instance and an object to append to the > > list. The 'solution' is in a previous line > > list = [] > > Reading further, one sees that the function works with two lists, a list > > of file names, unfortunately called 'list', and a list of > > subdirectories, more sensibly call 'subdirs'. > Yes, that is a poor choice of names. But sometimes you are > dealing with a generic list, and calling it "filenames" > would be equally inappropriate :-) I agree, however hopefully you're joking, because in the past you've argued that programmers should never use variables as generic as "list", "string", "integer", "float", etc... even though there are instances when all you need to know is what type your working with. > > I was initially confused > > and reading the code still takes a small bit of extra mental energy. > > Idle stays confused and will wrongly color the list instance name until > > it is changed. Calling the file list 'fnames' or 'filenames' would have > > been clearer to both me and Idle. > Correct. The downside of editors that colourise text is > that sometimes they colourise it wrong. One of the most important side-effects of using an editor with colorizing capabilities is to show you that you're using a built-in or keyword as a variable! I love when people comment on subjects they have no direct experience with, like for instance, you commenting on colonizers or GUI's -- LOL! > In this case, how is the editor supposed to know that list > no longer refers to the built-in list? Colonizers should ALWAYS colorize built-in (as built-in symbols) symbols EXCEPT when that symbol is part of a string or comment. > This is yet another good argument for being cautious about > shadowing built- ins. In a language designed like Python, yes. Unfortunately Python not only decided to expose built-in functions for constructing types instead of class identifiers, they also stole the best generic names! Sometimes all you need to know is the type of an object, not what it contains. I remember someone *cough-steven* talking about duck typing and how great it was to just treat a duck like a duck. Well, here we find ourselves treating a list like a list and your taking the opposite argument... why am i not surprised? PS: Is that "D" in last name short for "DevilsAdvocate"? Steven "DevilsAdvocate" Prano. -- http://mail.python.org/mailman/listinfo/python-list
Re: "Don't rebind built-in names*" - it confuses readers
On Tuesday, June 11, 2013 8:34:55 AM UTC-5, Steven D'Aprano wrote: > GvR is saying that it's okay to use the names of built-in functions or > types as the names of local variables, even if that causes the built-in > to be inaccessible within that function. Looks like we've finally found the traitor! Code smells propagating down from the apex of the pyramid... well thanks for the wonderful advice Guido, and with it you've cursed Python's stdlib to another decade of unprofessional code! PS: Excuse me whilst i brew myself a nice cup of HEMLOCK TEA!!! ಠ_ಠ -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
Umm, "Niko". (Superfluous Unicode Removed) The code you have written is very difficult to read because you are doing too much inside the conditional and you're repeating things!. For starters you could compile those regexps and re-use them: ## BEGIN SESSION ## py> import re py> s = """\ ... hello. ... I'm a little ... multiline ... string""" ... py> repr(s) "hello.\nI'm a little \nmultiline\nstring" py> prog = re.compile(r'e\s*\n') py> prog.findall(s) ['e \n', 'e\n'] ## END SESSSION ## Secondly you could wield the power of the built in function "all" to make your first "run-on-condition" a bit nicer: ## BEGIN SESSION ## py> lst = [True, True, False] py> all(lst) False py> if all([True, True, False, True]): ... print('Doing something') ... else: ... print("Shucks. I suppose i'll just twiddle my thumbs!") ... Shucks. I suppose i'll just twiddle my thumbs! ## END SESSION ## Lastly, you should write some helper functions to format the command (OUTSIDE OF THE CONDITIONAL) so you can shorten those atrociously long lines! -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: question regarding references and class relationships
On Monday, June 10, 2013 8:18:52 AM UTC-5, Rui Maciel wrote: > [...] > > > class Point: > position = [] > def __init__(self, x, y, z = 0): > self.position = [x, y, z] Firstly. Why would you define a Point object that holds it's x,y,z values in a list attribute? Why not store them as self.x, self.y and self.z? But if you are going to store them as a list, then why not extend a python list? I hate to see a "listy" object that only holds a list. It begs the question: Why not make it a *real* list? (Although i believe the former approach is more desirable for this problem) Secondly, why would store the position of the Point as a class attribute? Do you realize that EVERY instance of the Point object will share the same x,y, and z values if you do it that way? (considering you query the correct variable *evil grin*) Actually, you have a legitimate excuse: you were fooled because in your "object definition" you declared a "class level variable" named "position". THEN in your "__init__" method you declared an "instance level variable" named "position". Then, when you assigned the x,y,z values to "self.position" you thought you where assigning them to the "class level variable" named "position", HaHa, but then again you had NO idea that "class level variables" and "instance level variables" even existed! (or, at least, how to properly declare them) Q: Yes Rick but how do i solve this issue? By changing the names we can inspect the Point object and understand how class level and instance level variables work in Python. Observe: ## START SESSION ## py> class Foo(object): ... classVar = [] ... def __init__(self, arg): ... self.instanceVar = arg ... py> Foo.classVar [] py> Foo.classVar = "apple" py> Foo.classVar apple py> foo1 = Foo("pear") py> foo1.classVar apple py> foo1.instanceVar pear py> foo2 = Foo("peach") py> foo2.classVar apple py> foo2.instanceVar peach ## END SESSION ## As you can see the "class level variable" is known to all instances of the object, and a change in one is equal to a change in all. Whereas the "instance level variables" are unique to each instance. > class Line: > points = () > def __init__(self, p_i, p_f): > self.points = (p_i, p_f) Same problem here with the class level/instance level thing. > It would be nice if, whenever a Point object was updated, > the Line objects which are associated with it could > reflect those updates directly in Line.p_i and Line.p_f. > What's the Python way of achieving the same effect? Thanks > in advance, Rui Maciel > If you construct your code properly this can be achieved. If each point is an object, and lines are merely holding references to two point objects that define the start and end position of an imaginary "line", then updates on the points will be reflected in the Line object. Observe: ## START SESSION ## py> class Point3d(object): ... def __init__(self, x, y, z): ... self.x = x ... self.y = y ... self.z = z ... def __str__(self): ... _ = 'Point3d({}, {}, {})' ... return _.format(self.x, self.y, self.z) ... py> p1 = Point3d(1,2,3) py> str(p1) Point3d(1, 2, 3) py> p2 = Point3d(3,4,5) py> str(p2) Point3d(3, 4, 5) py> class Line3d(object): ... def __init__(self, p1, p2): ... self.p1 = p1 ... self.p2 = p2 ... def __str__(self): ... _ = 'Line3d({}, {})' ... return _.format(self.p1, self.p2) ... py> line1 = Line3d(p1, p2) py> str(line1) Line3d(Point3d(1, 2, 3), Point3d(3, 4, 5)) py> p1.x = 100 py> str(p1) Point3d(100, 2, 3) py> str(line1) Line3d(Point3d(100, 2, 3), Point3d(3, 4, 5)) ## END SESSION ## Easy peasy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: question regarding references and class relationships
On Monday, June 10, 2013 2:56:15 PM UTC-5, Ian wrote: > [...] > There are a couple of ways you might get this to work the way you > want. One is by adding as an extra layer a proxy object, which could > be as simple as: > class Proxy(object): > def __init__(self, ref): > self.ref = ref > Instead of adding points to the model, add instances of Proxy that > contain the points. When adding points to the lines, add the same > Proxy objects instead. Oh gawd just stop here! Are you joking? Are you playing coy? Are you attempting to confuse the lad? This type of complexity you suggest is what renders code bases unreadable and gives sloppy programmers "job security". > Later, when you want to replace a point in the > model, leave the Proxy in place but change the Point it contains by > modifying the "ref" attribute. Since the Line only directly > references the Proxy, it must follow the same ref attribute to access > the Point, and so in that way it will "see" the change. The downsides > to this approach are that you have to then use the Proxy objects all > over the place and explicitly "dereference" them by using the ref > attribute all over the place. Teacher: "What is the worse thing since memory management?" Jimmy Says: "ooh! ohh! i know! Teacher: "Yes jimmy?" Jimmy: "Superfluous memory management?" Teacher: "Oh no, I'm sorry Jimmy, you're so close but i was looking for: `Superfluous memory management by proxy`!" -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tuesday, June 11, 2013 8:25:30 PM UTC-5, nagia@gmail.com wrote: > is there a shorter and more clear way to write this? > i didnt understood what Rick trie to told me. My example included verbatim copies of interactive sessions within the Python command line. You might understand them better if you open the Python command line and type each command in one-by-one. Here is an algoritm that explains the process: open_command_window() whilst learning or debugging: type_command() press_enter() observe_output() if self.badder.is_full: take_potty_break() close_command_window() Utilizing the power of interactive sessions, for learning and debugging, should be a cornerstone fundamental of your programming "work-flow" when writing code in an interpreted language like Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tuesday, June 11, 2013 9:14:38 PM UTC-5, alex23 wrote: > On Jun 12, 12:05 pm, Chris Angelico wrote: > > > You have to include the coding phase. > > How else would he get into an error state? > > Via copy & paste. Now that's more like it Alex! If you move to my side the Python world could experience a cataclysmic polar shift. Which may not necessarily be a bad thing, however, I've noticed that these folks stress easily -- hmm, maybe their undergarments are just too tight??? -- http://mail.python.org/mailman/listinfo/python-list
Re: A certainl part of an if() structure never gets executed.
On Tuesday, June 11, 2013 10:37:39 PM UTC-5, Rick Johnson wrote: > Now that's more like it Alex! Opps, it seems i falsely interpreted Chris's post as directed towards me, and then with that false assumption in mind i went on to falsely interpreted reply to Chris. Folks if your not already ignoring me this might be a good time to start <|:o). At this time i think we should just forget about my mistake and and return to the request for internship in his new "open sore"sss project. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pywart: The problem with "Rick Johnson"
On Wednesday, June 12, 2013 2:17:49 PM UTC-5, Terry Reedy wrote: > On 6/4/2013 11:45 PM, Mike Hansen wrote: > > Is "Rick Johnson" the alter ego of Xah Lee, or is he the result of a > > cross breeding experiement with a troll by Saruman at Isengard? > He is a Python programmer competent enough with tkinter to have given > useful answers to me and others. Well thanks Terry. You've always been a knowledgeable and kind force on this list and the Python community could definitely use a few more like you. Hey, i would trade one-hundred Ricks for five or six more Terrys. :-) > He occasionally enjoys verbal jousting, > as in a bar, but pollutes his rants with ad hominem slurs. Urm, well i will admit my methods can be a bit "confrontational", however my intentions are always virtuous. "Ad hominem slurs" may be a bit too harsh, or, maybe my definition of "ad hominem" is different than others. I'll admit, I've never been the type that "works well with others". I'm more of a "one man army" than a "team player". But then again, some of the greatest intellects in history share my awkward social skills! And even if my "PyWarts" are troubling to some, i believe they are needed simply because they serve a greater purpose -- greater than even Rick himself! Because you cannot repair a problem if you are unaware that the problem exists. You see Terry, i'm just a soldier sacrificing myself on the alter of selflessness for the greater cause of this community. And whilst my vulgar display of bravado, and occasional diversions into hyperbole, can be upsetting to some, on the flip-side, my focused application of pure logical reasoning and my *unshakable* adherence to the fine principals of consistency can enlighten so many more! PS: Was this a private email sent to you or a thread started on the list? Because i don't see this thread anywhere -- unless I've gone blind??? -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Wednesday, June 12, 2013 2:46:13 PM UTC-5, John Ladasky wrote: > [...] > He's a smart kid, but prefers to be shown, to be tutored, > rather than having the patience to sit down and RTFM. > Have any of you been down this road before? I would > appreciate it if you would share your experiences, or > provide resource material. Hello John. I'm going to suggest a completely different path to enlightenment for the lad. A path that has the potential for semi-instant gratification whilst also humbling the boy to the grim realities of computer graphics and application development. *evil grin* Since your son has zero experience with both graphical and application based programming i would suggest starting at (near) the very bottom of the GUI spectrum, which, in the Python world would be the Tkinter Canvas. Some people would suggest starting with "turtle.py", and yes this is a good suggestion, however, i highly suggest that he begin by coding a python turtle program HIMSELF. But first i would let him use the existing turtle program, play around with it, understand some of the commands, etc... but whatever you do: DON'T LET HIM SEE THE SOURCE CODE! Then i would ask him to think about how this program works in a general manner (psst: remember, he's not a programmer "yet"!). For starters we know we need to create a "window" (this is where you would explain what a GUI library is. And to satisfy the instant gratification, we should create a window very soon. After we can create a blank window, we should take this opportunity to quickly cover some of the common subwidgets that can be placed into a window, such as:: "Text", "Entry", "Label", "Button", etc.., and maybe some simple code to display each of them will be fun. Now that we know "generally" what a GUI is, and we know about windows and sub-widgets, it's time to refocus on the turtle program. We will need to create a drawing area within the window for which to draw the turtle -- enter the Tk::Canvas! Next we can take a slight tangential meandering and learn about common Canvas primitives (like rectangles and lines and whatever!) Then we should decide which primitive would best suit a turtle, and draw that primitive. Once we have drawn the turtle, we quickly realize that it needs to sprout some legs and move around. This is where the fun really starts to begin... I think you can figure out where to go from there. Math functions, event processing... fun times! After he gets a simple turtle program running i would point out that even though he went to quite bit of work to solve this fairly simple problem, most of the really difficult code, like turning pixels on and off, drawing and ordering GUI windows, event loops, etc, etc... has been abstracted away into multiple layers of low level code. Even though the starting point of our project could be considered "slightly low level" relative to Python, there are vast libraries of millions of lines of code, layered one atop the other, making all this possible. The point of this exercise would be to get him thinking about solving problems instead of just reaching for a prepackaged library, and then not fully appreciating (or furthermore, truly *understanding*) the vast scope of *real* software design. Anybody can grab PyGame and start making simple games, but do they understand what is going on under the hood? I don't think they need to understand the science behind the internal combustion engine, however, if they cannot explain the basics of how the major components like: electrical, fuel, suspension, drive-train, braking, etc... work, then they lack a fundamental insight into solving complex problems that can arise later. For instance, if you hear a knocking sound whilst driving but the sound is absent whist idling, you can deduce that the problem most likely exists in the drive-train. From there you'd need to focus in at an even smaller level of detail -- but you could not come to that conclusion if you did not possess (at minimum) a basic understanding of the underlying component systems. Of course some might say: "Rick, why go to all that trouble when you could traumatize him with openGL instead". And to that i would reply: "Save OpenGL for lesson number two!" *wink* -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Wednesday, June 12, 2013 11:08:44 PM UTC-5, Chris Angelico wrote: > No. Definitely not. Programming does NOT begin with a GUI. It begins > with something *simple*, so you're not stuck fiddling around with the > unnecessary. On today's computers, that usually means console I/O > (actually console output, with console input coming along much later). Chris, you're a dinosaur, only thing is, somebody forgot to tell you. *Everything* these days revolves around graphical interfaces. The console, which was once the dark and mystical battlefield where knighted geeks would slay the plagues of exception demons, has been reduced to a mere: "little black box of nostalgia". 1. Rock is dead... 2. The console is dead... 3. Welcome to the 21st century Chris! PS: Although i'll bet you think the "rock is dead" mantra is relatively recent, nope! Jim Morrison was singing about it waaay back in 1969! -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Thursday, June 13, 2013 3:18:57 PM UTC-5, Joshua Landau wrote: > [...] > GUI is boring. I don't give a damn about that. If I had it > my way, I'd never write any interfaces again (although > designing them is fine). Console interaction is faster to > do and it lets me do the stuff I *want* to do quicker. And are you willing to provide *proof* that the console is faster? Or is this merely just your "opinion"? I would be ready and willing to compete in a "Pepsi challenge" to disprove your claim if needed. For instance, if i want to open a text file on my machine, i merely navigate to the file via my file browser interface, using clicks along the way, and then the final double click will open the text file using it's default program. Are you telling me you can type the address faster (much less remember the full path) than i can point and click? And if you think you're going to cheat by creating an "environment variable", well i can still win by doing the same thing with a "shortcut". > Also - Python is pretty much the only language that > *isn't* overkill; once you take more than the first few > steps a language that's *consistent* will help more with > learning, a mon avis, than these "quicker" languages ever > will. Python is consistent and simple. Your statement is an oft cited misconception of the Python neophyte. I'm sorry to burst your bubble whilst also raining on your parade, but Python is NOT consistent. And the more i learn about Python the more i realize just how inconsistent the language is. Guido has the correct "base idea", however he allowed the evolution to become a train wreck. > [...] > Basically, "kid" is a *very* generic term and there are > people who like GUIs and there are people who like > internals Your statement is true however it ignores the elephant in the room. You can "prefer" console over GUI all day long but that does not negate the fact that GUI's outperform the console for many tasks. With the exception of text based games, the console is as useful for game programming as a cheese grater is for masturbation -- slightly amusing, but mostly just painful! -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Thursday, June 13, 2013 11:05:00 PM UTC-5, Chris Angelico wrote: Chris, a GUI interface can be created for *ANY* command line functionality. By utilizing the GUI you can be more productive because a "point" and a "click" are always faster than "peck-peck-peck" * INFINITY. For instance, if i want to start a certain program (or func) on the commandline, first i will need to know what commands are available. To see these commands i must *FIRST* type a command. On the windows box that command would be "help". Now hopefully the command list will fit within the console's buffer capacity, or else i need to enter a page buffer mode (SOMEBODY KILL ME NOW!!!). This is where the GUI shines! When i choose to open my "system tools gui" (instead of the antiquated text only console), a list of commands will be displayed in a nice list box with scroll-bars that have near unlimited capacity to scroll. All i need to do is "point" and "click" and this "magical" piece of software runs another GUI program for that specific task or tool. > Also - Show me an efficient way, with a GUI, to invoke any > file with any program with any parameters, without > cheating and using something like Alt-F2 to enter a > command line. Your solution must be utterly generic. I > need to be able to tail -F and tail -f a file. Just because you lack the graphical tools on your machine, or the skill to create those graphical tools on your machine, does not mean the rest of us are as incapable. Note: The following solution requires you to have a windows OS, if you are using anything else, then you should be geeky enough to roll your own solution! ## BEGIN SCRIPT ## # Python Version < 3.0 only! import sys, os import Tkinter as tk import tkSimpleDialog, tkMessageBox msg1 = 'Greetings master, by what method shall i execute "{0}"?' msg2 = """\ And the master sayeth: "{0}" So it is written, so shall it be done""" ivalue = "some/path/to/nowhere.txt -opt1=foo -opt2=bar" def prompt_master(): argv = sys.argv path = argv[1] fname = os.path.basename(path) msg = msg1.format(fname) argstr = tkSimpleDialog.askstring('', msg, initialvalue=ivalue, parent=root ) if argstr: tkMessageBox.showinfo('', msg2.format(argstr),parent=root) os.system('{0} {1}'.format(path, argstr)) root.destroy() if __name__ == '__main__': root = tk.Tk() root.withdraw() prompt_master() root.mainloop() ## END SCRIPT ## Save that code in a file named "PepsiChallenge.py", then throw that script in your "Send To" folder and it "magically" becomes accessible from the "SendTo" command of the windows context menu. If you don't know where to find your windows "send to" folder then ask my good friend Google. To use, simply open your windows file browser, navigate to a file icon, right click the file, and send it to the PepsiChallenge script. By doing this we've harnessed the power of an existing GUI without actually writing all the GUI code. But more importantly we've won the challenge :-P" *school-bell* -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On Sunday, June 16, 2013 4:52:16 PM UTC-5, Chris Angelico wrote: > Okay... I'm trying to get my head around what you've done > here. Isn't it simply that you've made a way to, with what > looks like a point-and-click interface, let the user type > in a command line? > [...] > That's no more using a GUI than bringing up a terminal is. Yes, a Graphical Interface will need the occasional "peck-peck" input from the user, the only difference from a text based interface is the INFINITY multiplier. The Graphical Interface prefers the point and click, but NOT exclusively! The Graphical Interface allows you apply the most efficient method by which to solve a problem -- again, that might be "peck-peck" or "point-click", OR, a combination of both. Depends on the situation really. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is regex so slow?
On Tuesday, June 18, 2013 11:45:29 AM UTC-5, Roy Smith wrote: > I've got a 170 MB file I want to search for lines that look like: > [2010-10-20 16:47:50.339229 -04:00] INFO (6): songza.amie.history - > ENQUEUEING: /listen/the-station-one > This code runs in 1.3 seconds: > -- > import re > pattern = re.compile(r'ENQUEUEING: /listen/(.*)') > count = 0 > for line in open('error.log'): > m = pattern.search(line) > if m: > count += 1 > print count Is the power of regexps required to solve such a simplistic problem? I believe string methods should suffice. py> line = "[2010-10-20 16:47:50.339229 -04:00] INFO (6): songza.amie.history - ENQUEUEING: /listen/the-station-one" py> idx = line.find('ENQ') py> if idx > 0: match = line[idx:] py> match 'ENQUEUEING: /listen/the-station-one' -- http://mail.python.org/mailman/listinfo/python-list
Re: Beginner Question: 3D Models
On Tuesday, June 18, 2013 9:47:34 PM UTC-5, andrew...@gmail.com wrote: > I'm looking at developing a program for work that can be > distributed to others (i.e. and exe file). The > application would open various dialogue boxes and ask the > user for input and eventually perform mathematical > calculations on the input. Tkinter sucks for GUI (at least as it stands today) however it IS part of the stdlib and you can get going fairly quickly with it -- although Tkinter does not supply a native 3dcanvas widget so you'll have to use "togl", which is very old and poorly written, but it works! ;-) Alternatively, WxPython is a full featured GUI library which has a glCanvas waiting for you. But like anything there is a trade-off -- will take a bit more time to understand Wx than Tkinter. > From what I've read Python would have no trouble with > this. However, for one part of the program I'd like to be > able to create a 3D model based on the user input. The > model would be very basic consisting of a number of lines > and objects. > [...] > Are there any capabilities to import existing > CAD geometry, arrange the components in particular 3D > coordinates in space and then view the results in some > sort of 3D viewer? Ideally the user would then be able to > zoom in and orbit around looking at the model. Is this > possible? Is Python the right language? Sounds like "OpenGL" is what you need. Others have mentioned Blender, however i would say that is a bad idea. Sure, all the zoom and orbit code is written for you but then your users are going to be overwhelmed by the Blender interface. Blender is overkill for what you want! Suggesting Blender for this problem is like suggesting you rent a semi-truck to ship a toaster one block. Adding lines and faces (or even geometric primitives) in OpenGL is so easy you'd have to be a complete moron not to understand it. There's a little bit of complication when handling concave faces (or faces containing holes), but nothing impossible about it. Importing data from outside programs is pure Python (easy stuff). PS: Be aware that you'll most likely want to use the latest version of Python 2.x if you go the OpenGL route. You need the following. Python2.x + (Tkinter & Togl or WxPython) + OpenGL -- http://mail.python.org/mailman/listinfo/python-list
Re: A Beginner's Doubt
On Wednesday, June 19, 2013 8:58:19 AM UTC-5, augus...@gmail.com wrote: > This is my first post in this group and the reason why I > came across here is that, despite my complete lack of > knowledge in the programming area, I received an order > from my teacher to develop a visually interactive program, Ah teachers, you gotta love them! High on a power trip. Drunk on tenure. Most of which are overpaid and under-worked. Can't work with them, can't fire them! "HAY, TEACH-AH! Leave them kids alone!" > until 20th July, so we can participate in a kind of > contest. My goal is to learn and program it by myself, as > good as the time allows me. That said, what I seek here is > advice from people who definitively have more experience > than me on topics like: is it possible to develop this > kind of program in such a short amount of time? Develop what kind of program exactly? You see, usually you want to explain the details of your problem *before* you ask a question in relation to that problem, *ESPECIALLY* in the case of a generic question! How do you expect us to provide an answer? I mean, heck, even when faced with a post more riddled with more expletives than a prostitute has STD's, we can usually deduce the context of "it", however, in this case your just plain obfuscating! "What's the frequency Kenneth?" > What kinds of aspects of Python should I focus on > learning? What tutorials and websites are out there that > can help me? What kind of already done packages are out > there that I can freely use, so I do not need to create > all the aspects of the program froms scratch? It would be > wise to give an abstract of the program. Yes, and wiser if you had given it at post.index[0]! "Somethings happin' here" (at c.l.py) "What it is ain't exactly clear" "There's a post without context there!" "Tellin' me, i got to beware!" > Full screen window -> Title and brief introductory text -> 3 Buttons > (Credits) (Instructions) and (Start) > (Credits) -> Just plain text and a return button > (Instructions) -> Just plain text and a return button > (Start) -> Changes the screen so it displays a side-menu and a Canvas. > Side menu -> X number of buttons (maybe 4 or 5) > Buttons -> Clicked -> Submenu opens -> List of images > -> Return button -> Back to side menu > Image in List of images -> When clicked AND hold mouse button -> Make copy > -> if: dragged to canvas -> paste the copy in place > -> if: dragged anywhere else -> delete copy and > nothing happens > On canvas: > Image -> On click and drag can be moved > -> Double click -> Opens menu -> Resize, Deform, Rotate, Color, > Brigthness, Contrast, Color Curve, Saturation > Then, somewhere in cavas: > Save option -> Prompt for file and user's name > -> Prompt if users want printed copy or not -> Print > -> After saved, display random slideshow in other monitor, device > or screen with the users' creations. Easy. Pick up Tkinter and learn how to: 1. Display a window. 2. Display a button and associate a block of code to be called when the button is pressed. 3. Learn how to create a menu and attach it to a topwindow. Then add command and associate actions with those commands. 4. Display a canvas, then insert images in the canvas, then manipulate them. Manipulation will require input from the user, which involves either dialogs(easy) or interactive modifications(difficult) PS: What the hell is a "side menu"? PPS: Good luck ;^) -- http://mail.python.org/mailman/listinfo/python-list
Re: A Beginner's Doubt
On Wednesday, June 19, 2013 12:57:06 PM UTC-5, Terry Reedy wrote: > > Terry (speaking to OP) said: > > Do you literally mean a full screen *window*, like a > browser maximized, with frame and title bar with Minimize, > Restore/Maximize, and Close buttons? or a full-screen app > without the frame, like full-screen games? Tkinter, Wx, > etc, are meant for the former, Pygame, etc, for the > latter. Actually Terry, a GUI window is a GUI window -- whether or not the window displays "user window management controls" is irrelevant. Consider this example using Tkinter: ## BEGIN SCRIPT ## import Tkinter as tk MSG = """\ Your Screwed: Muhahahaha! Well, not really, you can destroy the window since i provided a secret exit. But you cannot maximize or minimize!!! Muhahahahaha! ...Oh just get out of here already!""" class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self._createWidgets() def _createWidgets(self): _ = 'Create User Controllable Window' w = tk.Button(self, text=_, command=self._cb1) w.pack(padx=5, pady=5) _ = 'Create User Pwned Window' w = tk.Button(self, text=_, command=self._cb2) w.pack(padx=5, pady=5) def _cb1(self): win = tk.Toplevel(self) win.title('User Controllable') win.geometry('500x500+20+20') self.wait_window(win) def _cb2(self): win = tk.Toplevel(self) win.overrideredirect(True) win.geometry('500x500+20+20') tk.Label(win, text=MSG).pack(fill=tk.X) tk.Button(win, text='X', command=win.destroy).pack() if __name__ == '__main__': app = App() app.mainloop() ## END SCRIPT ## > If you open Idle and click Help / About IDLE, you will see > a dialog box with title, text, and two groups of 3 buttons > that open plain text, including Credits, in a separate > window with a close (return) button. I guess that depends on which version of Python you are using. I don't have that dialog in my 2.7 version, although i did confirm your advice is True for v3.2.2 > It you decide to use tkinter, this would give you a start. > The code is in Lib/idlelib/aboutDialog.py. I do not know > how to make the 'dialog' be a main window instead, nor how > to replace a main window with a new set of widgets (as > opposed to opening a new window), but I presume its > possible. If so, I am sure Rick could tell us how. Oh yes, Senior Rick has a virtual cornucopia of knowledge locked away in his huge cranium just waiting for the opportunity to propagate out into this dark and illogical world. And Rick CAN tell you many things, the only question is: will you listen? > > When clicked AND hold mouse button -> Make copy > I am not sure what you mean by 'copy'. Make an internal > image object from the disk file? Sounds like he wants to allow the user to make some "interactive manipulations" on canvas image objects. In this particular case a "copy" operation. > > On canvas: > > Image -> On click and drag can be moved > This could be a problem if images overlap. Not necessarily. You can "pick" the image that is currently under the mouse pointer by querying certain tags, reguardless of any "overlap". > Image operations are what are usually placed on a size > menu or floating menu box. Unfortunately Tkinter does not provide interactive sizers for canvas items. You can create one yourself fairly easily however this is probably out of the range of a one month project for a complete Python noob. But you don't even need them really. Granted interactive manipulations are more powerful in some situations, you could simply prompt the user for values. For sizing operations a percentage of width and height or an absolute width and height values are all you need. For Rotations a degree of rotation, and possibly a rotational point(could default to centroid!) is all you need. For color you could wield the tkColorChooser. For Brightness you could either prompt for a value in range MIN to MAX or use a Tkinter::Slider. Simplistic deformations could also use a dialog. My recommendation would be to forget about interactive manipulations. First, get acquainted with the Tkinter widgets, then start drawing things on canvas, then figure out how to manipulate canvas items programically, then prompt the user for manipulations values, and only then, and only IF you still have time, try your hand at interactive manipulations. This is the path of a wise problem solver... THIS, is the path of the Rick neophytes. Go forth my young d
Re: Default Value
On Wednesday, June 19, 2013 2:17:35 PM UTC-5, Ahmed Abdulshafy wrote: > I'm reading the Python.org tutorial right now, and I found > this part rather strange and incomprehensible to me> > > Important warning: The default value is evaluated only > once. This makes a difference when the default is a > mutable object such as a list, dictionary, or instances of > most classes > > def f(a, L=[]): > L.append(a) > return L > > print(f(1)) > print(f(2)) > print(f(3)) > > This will print > > [1] > [1, 2] > [1, 2, 3] > > How the list is retained between successive calls? And > why? By the evil hands of an illogical consistency. Have you ever heard the old adage: "The road to hell is paved in good intentions"? Well, apparently the original designers of the language called in sick the day that class was taught. It's unfortunate because the same functionality that this "intention" claims to solve can be reproduced easily, and in a less astonishing manner, by the programmer himself. http://en.wikipedia.org/wiki/Principle_of_least_astonishment -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On Thursday, June 13, 2013 2:11:08 AM UTC-5, Steven D'Aprano wrote: > Gah! That's twice I've screwed that up. > Sorry about that! Yeah, and your difficulty explaining the Unicode implementation reminds me of a passage from the Python zen: "If the implementation is hard to explain, it's a bad idea." -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On Thursday, June 20, 2013 1:26:17 AM UTC-5, Steven D'Aprano wrote: > The *implementation* is easy to explain. It's the names of > the encodings which I get tangled up in. Well, ignoring the fact that you're last explanation is still buggy, you have not actually described an "implementation", no, you've merely generalized ( and quite vaguely i might add) the technical specification of a few encoding. Let's ask Wikipedia to enlighten us on the subject of "implementation": # Define: Implementation # # In computer science, an implementation is a realization # # of a technical specification or algorithm as a program, # # software component, or other computer system through # # computer programming and deployment. Many# # implementations may exist for a given specification or # # standard. For example, web browsers contain # # implementations of World Wide Web Consortium-recommended # # specifications, and software development tools contain # # implementations of programming languages.# Do you think someone could reliably implement the alphabet of a new language in Unicode by using the general outline you provided? -- again, ignoring your continual fumbling when explaining that simple generalization :-) Your generalization is analogous to explaining web browsers as: "software that allows a user to view web pages in the range www.*" Do you think someone could implement a web browser from such limited specification? (if that was all they knew?). Since we're on the subject of Unicode: One the most humorous aspects of Unicode is that it has encodings for Braille characters. Hmm, this presents a conundrum of sorts. RIDDLE ME THIS?! Since Braille is a type of "reading" for the blind by utilizing the sense of touch (therefore DEMANDING 3 dimensions) and glyphs derived from Unicode are restrictively two dimensional, because let's face it people, Unicode exists in your computer, and computer screens are two dimensional... but you already knew that -- i think?, then what is the purpose of a Unicode Braille character set? That should haunt your nightmares for some time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thursday, June 20, 2013 7:57:06 AM UTC-5, rusi wrote: > Every language has gotchas. This is one of python's. So are we purposely injecting illogic into our language just to be part of some "cool crowd" of programming languages with gotchas. "You thought intuitiveness was a virtue? Haha, we gotcha!" Or maybe this is reminiscent of the fraternity hazing rituals of days gone by: *POP* "Thank you Sir, may i have another?" > If you are a beginning python programmer, really the best > answer is: Just dont do it! Dont do what? Dont use > mutable arguments as function defaults. Once you cross the > noob stage you can check that its a standard gotcha: Just > run a search for 'python gotcha default []' > > And when you feel that you need to, use Steven's trick: > use a immutable indicator 'None' for the mutable []. Once > you cross the noob stage you can check that its a standard > gotcha: Just run a search for 'python gotcha default []' > Its even been discussed repeatedly on the python-ideas > list Your attempting to excuse an inexcusable language flaw by pointing out that the effects of the flaw can be avoided by using a workaround. And, to add insult to injury, you provide no good reason for the flaw to exist: "Just do x, y, and z and shut up. Yes we made a mistake but we are not about to admit our mistake and the onerous will be on all the noobs to re-invent the workaround each time" To me that is unacceptable. > Heres a correction suggestion: [...] Here's Terry Reedy's > nicely explaining the 'why-of-the-how' : [...] FWIW here > is a conceptual/philosophical explanation of your > confusion: There are 2 fundamental ways for approaching > the programming task -- functional and imperative. All these "explanations" ignore a fundamental fact about subroutines[1]. A call to a subroutine should exists as a unique transaction within the entire program. It is expected to optionally take inputs, and optionally return an output (depending on the definition). When the subroutine is completed, all inputs and local variables are expected to be destroyed. If the programmer wants a return value, he need simply ask. Data persistence is not a function of subroutines! Finally, a subroutine should never have side effects UNLESS the programmer explicitly ask for a side effect. However, the Python flaw of allowing mutable sequence arguments to persist between successive calls of a subroutine is breaking the entire definition of a subroutine, and for what noble purpose i ask? What purpose is SO important that you change a well established interface in a totally unintuitive manner? If your answer is that recursion is easier, then i say that is foolish because a programmer can keep a reference to a mutable sequence OUTSIDE the subroutine and you can save the "gotchas" for Guido's next birthday party. [1]: http://en.wikipedia.org/wiki/Subroutine -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On Thursday, June 20, 2013 9:04:50 AM UTC-5, Andrew Berg wrote: > On 2013.06.20 08:40, Rick Johnson wrote: > > then what is the purpose of a Unicode Braille character set? > Two dimensional characters can be made into 3 dimensional shapes. Yes in the real world. But what about on your computer screen? How do you plan on creating tactile representations of braille glyphs on my monitor? Hey, if you can already do this, please share, as it sure would make internet porn more interesting! > Building numbers are a good example of this. Either the matrix is reality or you must live inside your computer as a virtual being. Is your name Tron? Are you a pawn of Master Control? He's such a tyrant! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thursday, June 20, 2013 10:38:34 AM UTC-5, Chris Angelico wrote: > Function defaults in Python, being implemented as > attributes on the function object, are very similar in > nature to static variables in C. Oh wait a minute. i think it's becoming clear to me now! Python functions are objects that take arguments, of which (the arguments) are then converted to attributes of the function object. Ah-Ha! Urm, but wait! We already have a method to define Objects. Heck, I can even create my own callable objects if i want! Observe: py> class FuncAdd(object): ... def __init__(self, ivalue): ... self.ivalue = ivalue ... def __call__(self, numeric): ... return self.ivalue + numeric ... py> fa = FuncAdd(10) py> fa(10) 20 py> fa(20) 30 I can even emulate (quite easily) this idea of "persistence of function arguments" with mutables too, Yippee! py> class ArgPersist(object): ... def __init__(self, lst): ... self.lst = lst ... def __call__(self, arg): ... self.lst.append(arg) ... return self.lst ... py> fp = ArgPersist([1,2,3]) py> fp(4) [1, 2, 3, 4] py> fp([5,6,7]) [1, 2, 3, 4, [5, 6, 7]] But then, i can even do it WITHOUT creating an object definition: py> mutable = [] py> def expandMutable(arg): ... mutable.append(arg) ... py> expandMutable(1) py> mutable [1] py> expandMutable([2,3,4]) py> mutable [1, [2, 3, 4]] ANY of those approaches are much less confusing than the current flaw and do not violate the least astonishment law.. I'm quite Okay with Python functions being first class objects, however, i am not okay with violating the fundamental nature of subroutines, especially when that violation can offer no clear and arguable benefits and is in fact unreasonably esoteric in nature. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thursday, June 20, 2013 12:12:01 PM UTC-5, rusi wrote: > Python (and all the other 'cool' languages) dont have > gotchas because someone malevolently put them there. In > most cases, the problem is seen too late and the cost of > changing entrenched code too great. Okay. So now you are admitting the problem. That is a good start. Thanks for being honest. > Or the problem is clear, the solution is not etc etc. Both the problem and solution are clear, however, the will to execute the solution remains to be seem. Are you telling me we can justify breaking backwards compatibility for the sake of "print"[1] but we cannot justify breaking it for this monstrosity? Come on Rusi, you've gone too far with the comedy now. [1]: FYI I personally think print as function is the correct implementation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thursday, June 20, 2013 7:57:28 PM UTC-5, Steven D'Aprano wrote: > On Thu, 20 Jun 2013 11:05:32 -0700, Rick Johnson wrote: > > Python functions are objects that take arguments, of > > which (the arguments) are then converted to attributes > > of the function object. > Arguments in general are *not* converted to attributes. If > you call a function func(x=1, y=2), arguments 1 and 2 are > not stored as attributes anywhere. That would be silly, > since 1 and 2 become local variables and there is no point > in storing them for later use since they don't get used > later. Only default values for parameters are stored for > later use. Obviously you've lost the ability to recognize sarcasm. :( > They have to be stored *somewhere*, and Python chooses to > store them as an attribute of the function object, where > they can be easily inspected, rather than by storing them > inside some undocumented and hidden location locked up in > a binary blob. I like how that last sentence implicitly argues against an argument i never made, whilst explicitly supporting your argument. But, by all means Steven, proceed. > Even if Python chose late binding instead of early binding > for function defaults, the default would *still* need to > be stored somewhere. No, if your passing in a symbol, then the object it points to must exist *somewhere*. OTOH if your passing in a literal, or an expression, then the subroutine will need to "store" the resulting object. Yes. > The only difference is that with early binding, the > default value is calculated once, and the object stored, > while with late binding the default value is re-calculated > over and over again, every time it is needed, and a piece > of code that calculates the default value is stored. And that is *ONLY* the case using the currently broken system. You're arguing that the status-quo is better because the only alternative would be to re-evaluate the argument every time, when in fact, i provided three code examples that will not require re-evaluation of the mutable and i did so without sacrificing readability. Your argument is weak. > > Ah-Ha! Urm, but wait! We already have a method to define > > Objects. Heck, I can even create my own callable objects > > if i want! > > > [snip] > Yes, you can create callable objects by defining a > __call__ method. That's okay. It is pure slander, invented > by Perl programmers, that Python gives you "only one way > to do it". Python has functions for 99% of your subroutine > needs, and for more complex cases where your subroutine > needs to store permanent data and make them available to > the caller, you have class-based callables. But really, > using a class-based callable is a PITA. You have to define > a class, write an __init__ method, write a __call__ > method, instantiate the class, store the instance, and > call it. Mother of GOD call the authorities because a little girly man has been violated! That mean old Rick and his insistence on readability is causing a pandemic of carpal tunnel and PTSD syndrome. Haul him away, lock him up, and throw away the keys! Psst: That was sarcasm. > > But then, i can even do it WITHOUT creating an object > > definition: > > py> mutable = [] > > py> def expandMutable(arg): > > ... mutable.append(arg) > > ... > [...] > The biggest, most obvious problem with the expandMutable > approach is that it relies on a global variable. I find it > implausible that you, an experienced programmer, is > unaware of the dangers of global variables. I am quite aware of the dangers of globals, and i abhor their use in 99 percent of the cases. But we're talking about Python here *giggle*. The limits of a Python "global" are the module for which it is declared. Plus, this is quite amusing that you are now seemingly preferring the OOP style; how many times have you made snide remarks about my penchant for OOP? I dunno because i stopped counting after i ran out of fingers! Yes i can only count to ten, there, i beat you to the joke. Now we can focus again. > > ANY of those approaches are much less confusing than the > > current flaw > Confusing for whom? Beginners, who don't know the first > thing about Python? Of course programming noobs are going to be confused by this. > Programmers who are experienced with > some other language but have no clue about what these > weird __init__ and __call__ methods do? So now your going to argue that experienced programmers are going to intuit an IMPLICIT and unconventional subroutine data persistence, but they cannot intuit EXPLICIT words like "init" and "call"? Oh Please! > Programmers with > 40 years experience who don't kno
Re: Default Value
On Friday, June 21, 2013 2:10:49 AM UTC-5, Chris Angelico wrote: > Why should that be? Why is a subroutine not allowed to > retain any state? I refuse to repeat myself for lazy readers! > You're free to write code in a purely functional style if > you like I don't want to write code in a purely functional style, i find that style too restricting. > all objects must be immutable, That would suck! > all functions must have no side effects and simply return > a value. No thanks! > One of Python's strengths is that it permits many styles > of programming, without shoehorning every programmer and > every task into one model. Yes, and i consider that aspect of Python a virtue. But this "persistence of mutable arguments" is not a virtue, it's an abomination! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Thursday, June 20, 2013 5:28:06 PM UTC-5, Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC] wrote: > > [snip example showing dummy coder doing something dumb] > > +1. This is what convinces me that keeping references to > keyword arguments is actually the right thing to do. > > Perhaps I'm biased because I'm used to the mutable- > argument behavior by now, but the gotcha described above > seems to be much harder to track down and understand than > any bugs caused by mutable arguments. With mutable > arguments, at least you know the cause is in the function > definition. If you initialized variables each time, you'd > have to track the problem down across the entire > namespace. That's because you and many other folks, who keep supporting this BS idea, have become SO accustomed to writing code in a sloppy manner, that you need this flaw to save yourself, FROM YOURSELF! " Hello, allow myself to introduce myself" Apparently you don't understand the value of writing rock solid code. Instead of passing your mutables in as arguments, all you have to do is reference them properly in the BODY of the subroutine and everything will work just fine. If you fear global level variables then write up a simple Object definition to encapsulate the mutable and make it callable. Thought Exercise: Let's imagine for a second if Python allowed mutable keys in a dictionary, would you be surprised if you used a mutable for a key, then you mutated the mutable key, then you could not access the value from the original key? ## Imaginary code ## py> lst = [3] py> d = {1:2, lst:4} py> lst.append(10) py> d[lst] opps, KeyError! Would you REALLY be so surprised? I would not. But more importantly, does Python need to protect you from being such an idiot? I don't think so! Any "intelligent" programmer would NEVER use mutable keys for a hash table -- unless he had a very good reason and was willing to take the risks -- EVEN IF the language allowed such foolishness! But you people will sit here all day arguing that "early binding" is warranted on the grounds that people need to be protected from doing stupid things -- like passing mutables as arguments to subroutines. This is a weak argument. Tell me you have something better, tell me the fate of this language does not revolve around benevolent idiocy! If you really want to save the poor idiot from writing code that could fail, a leader ruled by benevolence, but who has a modicum of intelligence remaining, would simply throw up a warning. Warning: Argument "lst" to function "poopoo" has been mutated, which could cause a subtle bug on successive calls. YOU HAVE BEEN WARNED! What you never, EVER, want to do is to use idiots for an excuse to create some esoteric abomination of persistent mutables between successive calls of subroutines. > I, for one, would much rather follow the rule "don't use > mutable arguments in function definitions" Yes, that's the exact point i'm making! A little self discipline can go a long way > than "don't ever re-use the name of your variables." Well, we're not even talking about that, but i understand the value of your statement. Although, i think your comparing Apples and Oranges. PS: First you support the opposition. now you go an do a 180? You're confusing the hell out of me Matthew! @_@ -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 10:57:17 AM UTC-5, Steven D'Aprano wrote: > On Thu, 20 Jun 2013 11:05:32 -0700, Rick Johnson wrote: > > py> class FuncAdd(object): > > ... def __init__(self, ivalue): > > ... self.ivalue = ivalue > Notice how you are storing state here? I thought you said, > and I quote: "When the subroutine is completed, ALL INPUTS > and local variables are expected to be destroyed. If the > programmer wants a return value, he need simply ask. Data > persistence is NOT a function of subroutines!" > [emphasis added] > > And yet here you are defining persistent input ("ivalue") > to the callable subroutine, which is stored as external > state and not destroyed at the end of the subroutine call: Because Steven, my dear lad, what i created is NOT a subroutine, no, it's an object that stores state and is callable. Each call to the object is merely a request to mutate and then return it's current state. A subroutine, at least REAL subroutines (not the snake oil that Python is selling) do not have state. Real subroutines merely: 1. Optionally take inputs 2. Execute a body of code (which could have side effects, but which is NOT persistent!) 3. Optionally return output That's it. If your problem requires state persistence, then you need to move up to an Object definition. Use the correct tool for the job dammit! > > ... def __call__(self, numeric): > > ... return self.ivalue + numeric > > ... > All you have done here is define a subroutine with state, > precisely the thing that you say subroutines must never > have. It's Okay to carry state EXPLICITLY, it's NOT okay to carry state IMPLICITLY. My implementation is correct, Python's is not. Besides, encapsulated state is one of the fundamental principles of OOP programming, along with interfaces; and i've satisfied both! The mutable is protected from the world by an object, and the object allows manipulation of the mutable via an interface. But unlike Python's limited implementation, my approach is scalable. I can change the interface, i can add more functionality, i can do anything i want. "I am the Lizard King, and i can do, well ANYTHING!" However, with Python's limited approach, i'm just a slave to the implementation. I'm forced to follow estoeric rules with no chance of scalability. # Moral of the Day # # You should only use SUBROUTINES for executing# # subprograms requiring stateless transactions.# # Alternativly, subprograms requiring persistant state # # transactions should wield the power of a custom # # object defintion -- or you can use the # # global+subroutine method if encapsulation is not # # warrented. # But in any case, following this advice will ensure less bugs and more maintainable code than Python's current implementation of lunacy. > What you haven't done is define a function which takes a > default value that can be overridden when called. Oh, you mean like this? py> class Func(object): ... def __call__(self, arg=0): ... print(arg) ... py> f = Func() py> f("pwned") pwned > Your argument is invalid. My argument is not invalid, i just figured i did not need wipe your bum for you, "Homer". ~(_8^(I) -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 12:47:56 PM UTC-5, Rotwang wrote: > It isn't clear to me from your posts what exactly you're > proposing as an alternative to the way Python's default > argument binding works. In your version of Python, what > exactly would happen when I passed a mutable argument as a > default value in a def statement? E.g. this: > > >>> a = [1, 2, 3] > >>> a.append(a) > >>> b = object() > >>> def f(x = [None, b, [a, [4]]]): > ... pass # do something > > What would you like to see the interpreter do in this case? Ignoring that this is a completely contrived example that has no use in the real world, here are one of three methods by which i can handle this: The Benevolent Approach: I could cast a "virtual net" over my poor lemmings before they jump off the cliff by throwing an exception: Traceback (most recent screw-up last): Line BLAH in SCRIPT def f(x = [None, b, [a, [4]]]): ArgumentError: No mutable default arguments allowed! The Apathetic Approach: I could just assume that a programmer is responsible for the code he writes. If he passes mutables into a function as default arguments, and then mutates the mutable later, too bad, he'll understand the value of writing solid code after a few trips to exception Hell. The Malevolent Approach (disguised as beneva-loon-icy): I could use early binding to confuse the hell out of him and enjoy the laughs with all my ivory tower buddies as he falls into fits of confusion and rage. Then enjoy again when he reads the docs. Ahh, the gift that just keeps on giving! Conclusion: As you can probably guess the malevolent approach has some nice fringe benefits. You know, out of all these post, not one of you guys has presented a valid use-case that will give validity to the existence of this PyWart -- at least not one that CANNOT be reproduced by using my fine examples. All you can muster is some weak argument about protecting the lemmings. Is anyone up the challenge? Does anyone here have any real chops? PS: I won't be holding my breath. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 1:37:13 PM UTC-5, Steven D'Aprano wrote: > Okay, you're trolling. Time for another month in the kill-file. > *plonk* That's so typical of you. You start losing an argument, and when you have no remaining counter arguments, you resort to name calling. Why am i not surprised? You wanna see some trolling? Is this all you can conjure Steven "Sauron" D'Aprano? ... A FEW MINDLESS ORCS? I have defeated your orcs, and your cave trolls. I have defeated you in my darkest hour in the keep. I have thrown out that despot from the white city, i have even slain your Nazgul. Heck, my little sister killed your witch king. ...AND STILL YOU THINK YOU CAN DEFEAT ME! And now, here i stand, at the foot of the mountain of doom, with the ring of *POWER* in my hand, and i shall cast it into the fires from whence it came! ...WHO WILL STOP ME? All you have remaining is your beloved "gollom van rossum" and he has already defeated himself with his blind devotion to this despicable ring. A ring that represents illogical and inconsistent design philosophies. A philosophy that he himself cannot defend. Free my people from this plague of darkness, and cast light on these atrocities so that the sun may bleach this language and this community clean, and maybe we'll let you visit the shire. ...MAYBE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 2:18:27 PM UTC-5, Rick Johnson wrote: > On Friday, June 21, 2013 1:37:13 PM UTC-5, Steven D'Aprano wrote: > > > Okay, you're trolling. Steven, you wouldn't know "trolling" even if you were an honorary salad tosser at a troll face-sitting contest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 2:20:22 PM UTC-5, Neil Cerutti wrote: > Rick, it's not a wart, It's a gotcha. The reason it's a > gotcha is this: In order to predict what will happen > correctly, you have to have mastered three separate Python > concepts. > > 1. How name-binding works. > 2. How argument passing works, i.e., via name-binding. > 3. When default arguments are evaluated. > 4. The Python object model. I understand all these concepts in a Python context quite well, but understanding a PyWart is no validation for it's continued existence. You probably understand the common cold quite well. If you do you'll wash your hands before eating, and avoid exposure to sick people. THAT'S CALLED A WORKAROUND! But disease is not yet fully under human control, we are forced to used the workaround. Whereas, languages are. So designing a language poorly and then getting upset because people don't praise your clunky work-around is ludicrous. Psst: THE PROBLEM IS SELF-INDUCED! Mankind, the only creature dumb enough to self-induce his own hardships -- somewhere a higher intelligence must be laughing... or crying, who knows. *sigh* -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 2:25:49 PM UTC-5, MRAB wrote: > On 21/06/2013 19:26, Rick Johnson wrote: > > > > The Apathetic Approach: > > > > I could just assume that a programmer is responsible for the > > code he writes. If he passes mutables into a function as > > default arguments, and then mutates the mutable later, too > > bad, he'll understand the value of writing solid code after > > a few trips to exception Hell. > > > > The Malevolent Approach (disguised as beneva-loon-icy): > > > > I could use early binding to confuse the hell out of him and > > enjoy the laughs with all my ivory tower buddies as he falls > > into fits of confusion and rage. Then enjoy again when he > > reads the docs. Ahh, the gift that just keeps on giving! > > How does the "Apathetic Approach" differ from the > "Malevolent Approach"? In the apathetic approach i allow the programmer to be the sole proprietor of his own misfortunes. He lives by the sword, and thus, he can die by the sword. Alternatively the malevolent approach injects misfortunes for the programmer on the behalf of esoteric rules. In this case he will live by sword, and he could die by the sword, or he could be unexpectedly blown to pieces by a supersonic Howitzer shell. It's an Explicit death versus an Implicit death; and Explicit should ALWAYS win! The only way to strike a reasonable balance between the explicit death and implicit death is to throw up a warning: "INCOMING" Which in Python would be the "MutableArgumentWarning". *school-bell* -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 5:49:51 PM UTC-5, MRAB wrote: > I notice that you've omitted any mention of how you'd know that the > argument was mutable. My argument has always been that mutables should not be passed into subroutines as default arguments because bad things can happen. And Python's excuse of saving the poor dummies is no excuse. It does not matter if we are passing the arguments into the current implementation of "python functions which maintain state of default mutables arguments between successive calls" or in a more desirable system of truly "stateless subroutines". I also believe that a programmer should not be prevented from passing mutable default arguments, but if he does, I'm not going to provide any sort of protection -- other than possibly throwing up a warning message. Now, YOU, and everyone else, cannot destroy the main points of my argument because the points are in fact rock solid, however, what you will do is to focus in one small detail, one little tiny (perceived) weakness in the armor, and you will proceed to destroy that small detail (in this case how i will determine mutability), and hope that the destruction of this insignificant detail will start a chain-reaction that will propagate out and bring down my entire position. So you want me to tell you how to query the mutability of an object... Ha Ha Ha! Sorry, but that's not going to happen! Why should i help the developers of this language. What have they done for me? Hmm, let's see. They called me names. Trolled up my posts. Written me off. Refused to answer my questions. Been absolutely rude. etc, etc... Banned me from lists i've never posted on and then proclaim the list is free and open to all... BS! WOULD YOU OFFER ASSISTANCE TO PEOPLE THAT HAVE TREATED YOU THIS WAY? And let's just be honest. You don't want my assistance. You just want me to fumble the ball. Then you can use that fumble as an excuse to write me off. Nice try! You want to gain my respect? Then start engaging in honest debates. Start admitting that yes, somethings about Python are not only undesirable, they're just plain wrong. Stop calling me a troll when i am not. And not just me, stop calling other people trolls too! Stop using the personal attacks and straw man arguments. Finally, get the core devs to realize that this list matters and they need to participate (including you know who!) -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 6:40:51 PM UTC-5, Rotwang wrote: > On 21/06/2013 19:26, Rick Johnson wrote: > [...] > I didn't ask what alternative methods of handling default > argument binding exist (I can think of several, but none > of them strikes me as preferable to how Python currently > does it). I asked what would happen in /your/ version of > Python. Which of the alternatives that you present would > have been implemented, if you had designed the language? The apathetic approach. However, you fail to understand that whilst Python's current implementation is partly apathetic, is is also benevolent, and malevolent simultaneously. My approach is purely apathetic. I'll explain later. Stay tuned. > [...] > So how does the interpreter know whether an arbitrary > object passed as a default value is mutable or not? Not > that it really matters. Well i'm glad it does not matter to you because it does not matter to me either. *shrugs* > > Let's imagine for a second if Python allowed mutable keys in > > a dictionary, > which it does Am i just to take your word for this? You cannot provide an example? Here, allow me to "break the ice": # Literal py> d = {[1]:2} Traceback (most recent call last): File "", line 1, in d = {[1]:2} TypeError: unhashable type: 'list' # Symbol py> lst = [1] py> d = {lst:2} Traceback (most recent call last): File "", line 1, in d = {lst:2} TypeError: unhashable type: 'list' Hmm, maybe only certain mutables work? Great, more esoteric rules! Feel free to enlighten me since i'm not going to waste one second of my time pursuing the docs just to learn about ANOTHER unintuitive PyWart i have no use for. > Now, I don't really believe that you think that the user > shouldn't be protected from doing one idiotic thing with > mutable dict keys but should be protected from doing > another idiotic thing with mutable default arguments, > especially as you've already been given a use case for the > latter. So I assume that The Benevolent Approach is not > the approach you would have gone for if you had designed > the language, right? If so then let's ignore it. You are correct. Finally, we can agree on something. > > > > The Apathetic Approach: > > > > I could just assume that a programmer is responsible for the > > code he writes. If he passes mutables into a function as > > default arguments, and then mutates the mutable later, too > > bad, he'll understand the value of writing solid code after > > a few trips to exception Hell. > > It seems to me that this is exactly what currently happens. (is this lazy readers day? I swear i explained this earlier) And here is where you are wrong. In the current implementation python functions carry the state of mutable default arguments between successive calls. That's a flaw. Observe: py> def foo(arg=[]): ... arg.append(1) ... print(arg) ... py> foo() [1] py> foo() [1, 1] py> foo() [1, 1, 1] No, no, NO! That's wrong! Subroutines should be stateless. That means that an empty mutable default argument will ALWAYS be empty at each call of the subroutine. This is what should happen: py> def foo(arg=[]): ... arg.append(1) ... print(arg) ... py> foo() [1] py> foo() [1] py> foo() [1] Yes, Yes, YES! That is intuitive! That is sane! Now, what if we pass a reference to a mutable object? What then. Well, let's see: py> lst = range(5) py> lst [0, 1, 2, 3, 4] py> def foo(arg=lst): ... arg.append(1) ... print(arg) ... py> foo() [0, 1, 2, 3, 4, 1] py> foo() [0, 1, 2, 3, 4, 1, 1] That's fine. Because the object was already created OUTSIDE the subroutine. So therefore, modifications to the mutable are not breaking the fundamental of statelessness INSIDE subroutines. The modification is merely a side effect, and the subroutine is unconcerned with anything that exists beyond it's own scope. IS ALL THIS REGISTERING YET? DO YOU UNDERSTAND? > > > > The Malevolent Approach (disguised as beneva-loon-icy): > > > > I could use early binding to confuse the hell out of him and > > enjoy the laughs with all my ivory tower buddies as he falls > > into fits of confusion and rage. Then enjoy again when he > > reads the docs. Ahh, the gift that just keeps on giving! > My quest
Re: Default Value
On Friday, June 21, 2013 8:31:35 PM UTC-5, Steven D'Aprano wrote: > Tuples have to go into the "Bad List" because, although > they themselves are immutable, their contents may not be. > Imagine the confusion and horror that poor developers will > experience when they do something like this: > > def func(arg, extra=(23, 'foo', [])): > [code goes here...] > extra[2].append("something") > [more code...] > > and they've now mutated the immutable default! Thinking > about this, I think that the only safe thing to do in > Rickython 4000 is to prohibit putting mutable objects > inside tuples. Putting a list or a dict inside a tuple is > just a bug waiting to happen! Geezsus, the warts in this language are innumerable! So what your saying is that Python Tuples are "immutable" like automobiles passengers are "immutable". Sure you can design the car for a maximum number of passengers, but as soon as the circus clowns show up, all bets are off! This whole language is a joke! It just some sick joke! ROTF -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 8:54:50 PM UTC-5, MRAB wrote: > On 22/06/2013 00:51, Rick Johnson wrote: > > On Friday, June 21, 2013 5:49:51 PM UTC-5, MRAB wrote: > > My argument has always been that mutables should not be > > passed into subroutines as default arguments because bad > > things can happen. [...] I also believe that a programmer > > should not be prevented from passing mutable default > > arguments [...] > So, having mutables as default arguments is a bad idea, > but a programmer should not be prevented from doing that, > and a warning message should be printed on such occasions. Well i'll admit that does sound like a contradiction. Basically i meant, programmers should be *discouraged* from passing mutables as default arguments but not *prevented*. Of course, utilizing a stateless subroutine like i suggest, argument mutability would not matter. Sometimes when you're passionate about something your explanations become so verbose as to render your idea lost in the noise. Obviously i made that mistake here :) In my last reply to Rotwang i explained the functionality i seek to achieve in a set of three interactive examples. Take a look at those and let me know what you think. > > Why should i help the developers of this language. What have > > they done for me? > > They've developed this language, and provided it for free. > They've even released the source code. You perceive flaws > that you say must be fixed, but you're not going to help > to fix them. Agreed. And i am thankful for everyone's contributions. I can be a bit harsh sometimes but my intention has always been to improve Python. > I _do_ want you to help to improve the language, and I > don't care if you don't get it right first time. I didn't > get it right first time when I worked on the regex module > (I think that what I have on PyPI is my _third_ attempt!). Well thanks for admitting you are not perfect. I know i am not. We all had to start somewhere and anyone who believes he knows everything is most assuredly a fool. Learning is a perpetual process, same for software evolution. > > You want to gain my respect? Then start engaging in honest > > debates. Start admitting that yes, somethings about Python > > are not only undesirable, they're just plain wrong. > Python isn't perfect, but then no language is perfect. > There will always be compromises, and the need to maintain > backwards compatibility means that we're stuck with some > "mis-features", but I think it's still worth using; I > still much prefer it to other languages. I understand. We can't break backwards compatibility for everything, even breaking it for some large flaws could cause a fatal abandonment of the language by long time users. I just don't understand why i get so much hostility when i present the flaws for discussion. Part of my intention is to air the flaw, both for new users and old users, but a larger intention is to discover the validity of my, or others, possible solutions. And even if that solution involves a fork, that is not a bad thing. Creating a new fork and then garnering an acceptance of the new spinoff would lead to at worse, a waste of time and a huge learning experience, or at best, an evolution of the language. > > Stop calling me a troll when i am not. And not just me, stop > > calling other people trolls too! Stop using the personal > > attacks and straw man arguments. Sorry. I failed to explain that this statement was meant not directly for you but as a general statement to all members. Sometimes i feel like my back is against the wall and i'm fighting several foes at once. That can lead to me getting defensive. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 8:38:21 PM UTC-5, Ian wrote: > The answer to this conundrum is staring you in the face. Thanks for posting a solution for this. Not sure if i'll ever need it, but nice to know. > Note that the TypeError complains that you passed it an > "unhashable" type, and not that you passed it a "mutable" > type. If you want to take a mutable type and make it > hashable, just add a __hash__ method. > > class HashableList(list): > def __hash__(self): > return 42 > >>> d = dict() > >>> hl = HashableList(range(5)) > >>> hl2 = HashableList(range(6, 10)) > >>> d[hl] = 10 > >>> d[hl2] = 20 > >>> d > {[0, 1, 2, 3, 4]: 10, [6, 7, 8, 9]: 20} > > Additionally, instances of user-defined classes are, by > default, both mutable and hashable. This is safe because > equality and hashing for such objects are by default based > on identity. If you override the __eq__ method though, > then you lose hashability unless you explicitly override > __hash__ as well. Hey, you went above and beyond to provide that last bit of info. Thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Friday, June 21, 2013 9:32:43 PM UTC-5, rusi wrote: > So Rick... I agree with you... all these theoreticians > should be burnt at the stake! On a more serious note: many > people make similar mistakes eg Haskellers who think > Haskell is safe. Safer (than something or other) -- Ok > Safe -- NO So now you're going to attempt to defeat my idea by suggesting that it chalks up to nothing more than a safety measure? How many times must i explain the simple concept of stateless subroutines and hazards of the current incarnation Python FUNCtions (You smell the func!) Yes you gain safety by utilizing such an implementation over the current implementation, however you also trim a negative attribute of the language. Not to mention the intuitive and readability gains. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
> See my blog [...] > for a history of wishes akin to yours and lessons not > learnt. In short the problems accruing from unconstrained > imperative programming are severe and the solutions are > hard. In the meanwhile, goals such as your 'keep- > procedures-stateless' can and should certainly be > practised in the human sphere even if not implemented in > the programming language sphere. The aggregation of such > 'best-practices' is what I call FP as an ideology rather > than as technology. > > I have a collection here [...] > And I would welcome suggestions/discussions on the same. Here are some statements from your blog, i have made a few tweaks to the text (mainly structure) so as to render it more readable. > Unfortunately these are the exceptions. In the vast > majority of cases, the quest for generalities only > produces rubbish. So lets see how the... The Philosophy of > OO fares in this regard. > > OO starts off its philosophical sojourn with the dogma: > Everything is an object I will start with a variation that > is slightly less nonsensical but easier to debunk; > Everything can be modeled as a class > > Now if we start looking at the justifications of this > statement we would find certain methodological directives > such as Identify the nouns in the use-case and make them > classes In itself this is - as a methodology - not > objectionable. > > So for example if we are presented with the standard > example of a customer coming to an ATM and making a > transaction, this methodology tells us that it may be a > good idea to make customer and ATM into classes - so far > so good. > > And what about transaction? Yes we could make it into a > class also, but as we shall see, blanket- adding the set > of abstract nouns into the set of common nouns as class- > ifiable objects gets us into trouble. No, the transaction itself need NOT be a custom object. > So for example, if the use-case contained a statement > like: In order to safeguard customer-satisfaction, the > ATM's performance shall not degrade beyond 3 seconds > response time. > So now - according to our methodology - we need to > make performance, response-time and even customer- > satisfaction(!!) into classes. LOL! Only a fool, or a religious OOP extremist, would create custom objects for such things. Although, if he were forced to use Java, he wouldn't have any choice would he? Poor basterd! >:D But my point is, OOP is not a cure-all for every problem, in fact, it can overly complicate many problems. For instance, being forced to write an object definition for a simple hello world program in Java is nothing less than pure sadism -- but that's why i don't use Java unless i'm forced! OTOH, from skimming a few other threads in your blog, you seem to long for some salvation of FP to save all our souls from the eternal damnation of IP, like a Christian longing for the second coming of Christ! "Take us away to streets paved in gold!" I sorry, but FP is not going to wash our sins clean. In fact, if taken too seriously, FP leads to preaching professors, intellectually unstimulated students, and semesters of wasted time that could have been better spent honing practical *real world* skill sets. #Tip of the Day# # Remember, whilst the professor's tenure will # # guarantee he gets a paycheck even for producing # # rubbish, you won't be afforded such luxuries in the # # real world. # "If it IS to be, then it's up to ME" The point is, no one paradigm is going to save us from the devil. We must take from each style it's positive attributes, and reject it's negative attributes. The art of intelligently applying multiple paradigms to solve complex problems should be held up as the pinnacle of greatness. If your going to worship something, worship achievement. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On Saturday, June 22, 2013 8:36:43 AM UTC-5, Joshua Landau wrote: > message = "Item wrote to MongoDB database " > message += "{0[MONGODB_DB]}/{0[MONGODB_COLLECTION]}".format(settings) > log.msg(message, level=log.DEBUG, spider=spider) If you're going to whore out parts of the string to variables i would suggest going for the gold and actually make it readable. Plus, your use of the format syntax is incorrect. _arg1 = settings['MONGODB_DB'] _arg2 = settings['MONGODB_COLLECTION'] _fmtstr = "Item wrote to MongoDB database {0}, {1}" msg = _fmtstr.format(_arg1, _arg2) log.msg(msg, level=log.DEBUG, spider=spider) If you want readability, now you got it. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On Saturday, June 22, 2013 10:40:24 AM UTC-5, Joshua Landau wrote: > > Plus, your use of the format syntax is incorrect. > Wut? Well what i mean exactly is not that it's illegal, i just find the use of the "getattr sugar", from WITHIN the format string, to be excessively noisy. In short, i don't care to know WHAT is being injected into the format string, i simply need to know WHERE it is being injected. It's about abstractions. It's about not violating the fundamentals of "templates". -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
On Saturday, June 22, 2013 12:19:31 PM UTC-5, Rotwang wrote: > > On 22/06/2013 02:15, Rick Johnson wrote: > > IS ALL THIS REGISTERING YET? DO YOU UNDERSTAND? > > No, I don't. These two special cases are not sufficient > for me to determine what semantics you are proposing for > the general case. QUESTION 1: > For example, what happens in the second > example if lst is rebound? Well nothing could happen, or something significant could happen. How do you expect me to determine an answer for such a general question when i have no context, or any algorithms to work from. Maybe you are trying to set a situation that results in chaos, okay, then chaos will happen. But who's fault is the chaos when a programmer is rebinding names? The programmer is ultimately responsible for his action. Remember my "Apathetic Approach"? QUESTION 2: > Does the default stay the same or does it change to the > new value of lst? Here you go again, you cannot seem to comprehend very simple concepts. My second example clearly explains what will happen >> py> lst = range(5) >> py> lst >> [0, 1, 2, 3, 4] >> py> def foo(arg=lst): >> ... arg.append(1) >> ... print(arg) >> ... >> py> foo() >> [0, 1, 2, 3, 4, 1] >> py> foo() >> [0, 1, 2, 3, 4, 1, 1] Do you see how the name 'lst' is bound to a list object living in global module scope? Do you see how the default argument (named `arg`) is a reference to a global list named `lst`? ARE YOU FOLLOWING ALONG SO FAR? Since the mutable arg exists OUTSIDE the subroutine, the subroutine merely need to provide access to the global *name* `lst` from within the body of the subroutine, and the subroutine merely do this ONCE at compile time! ARE YOU FAMILIAR WITH THE CONCEPT OF POINTERS? QUESTION 3-A: > What about if you pass a call as a default argument, and > then subsequently change the behaviour of the callable? Hmm, let's have a thought experiment. What if i give you a digital birthday card. And when you open the card you see a friendly note from me: "Rotwang is my best friend in the whole wide world". But unbeknownst to you, i have actually hacked the card and installed a secret wifi device. I've made the message mutable -- hmm, surely nothing "bad" could arise from mutability correct? *evil-grin* A few hours later when you open the card to show to some friends, you are alarmed to see a new message: "Rotwang is a degenerative penis condition" Now, besides being embarrassed, and probably angry as hell, do you understand the dangers of mutable objects? I'm not suggesting you don't ever want to use the power of mutability, no, but you do need to have a healthy respect for mutability -- because it can really ruin your day! QUESTION 3-B: > Does the argument get re-evaluated every time foo() is > called, or is the argument guaranteed to be the same every > time? If the argument is an expression, like a literal, it will be reset to the literal each time the subroutine is called. If the argument is a non-local object, the argument will NOT be reset each time. See "ANSWER 2" for more context. QUESTION 3-C: > If the latter, what happens if the arguments type is > modified (e.g. by changing one of its class attributes)? > What about defining functions dynamically, with default > arguments that are only known at runtime? Is there any way > to avoid the second type of behaviour in this case? If so, > how? If not, isn't that likely to prove at least as big a > gotcha to people who don't know the rules of RickPy as the > problem you're trying to solve? What if X? What if Y? What i pass in a pony but i sell it to a glue factory before the subroutine gets called??? I'm sorry but have no more patience for these ridiculous questions. If you want me to answer *specific* questions, then be sure to ask them one at a time and provide relevant code examples. -- http://mail.python.org/mailman/listinfo/python-list
Re: n00b question on spacing
On Saturday, June 22, 2013 6:12:50 PM UTC-5, Chris Angelico wrote: > As a general rule, I don't like separating format strings and their > arguments. Huh? Format strings don't take arguments because Python's built-in string type is not callable. py> callable("") False "Format string" is just a generic term we apply to normal string literals that include special markers (called "placeholders") that define the final location and specify the specifics of an Object(s) translation into string type. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question
On Saturday, June 22, 2013 9:39:30 PM UTC-5, christ...@gmail.com wrote: > Writing simple program asking a question with the answer being > "yes"...how do I allow the correct answer if user types Yes, > yes, or YES? Here is a clue. py> 'e' == 'e' True py> 'E' == 'E' True -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sunday, June 23, 2013 11:15:38 AM UTC-5, Ian wrote: > If you're worried about efficiency, you can also > explicitly name the superclass in order to call the method > directly, like: I'm NOT worried about efficiency, i worried about readability, and using super (when super is NOT absolutely required) is folly. > A.__init__(self, arg) What you've done here is correct, the only flaw is that you choose to do this for all the wrong reasons. ...GET YOUR PRIORITIES IN ORDER! -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the semantics meaning of 'object'?
On Sunday, June 23, 2013 11:49:42 AM UTC-5, Roy Smith wrote: > For what it's worth, I never bother to inherit from object > unless I know there's something I need from new style > classes. Undoubtedly, this creates a disturbance in The > Force, but such is life. Well, in Python 3000, if you don't explicitly inherit from "object", Python (aka: Guido's Master Control Program) is going to implicitly do it for you; so i would suggest you be explicit for the sake of the reader. PS: I love how people say so confidently: "In Python 3, inheriting from object is optional!" Obviously they don't understand the definition of optional. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
On Sunday, June 30, 2013 1:06:35 AM UTC-5, Chris Angelico wrote: > So, here's a challenge: Come up with something really simple, and > write an insanely complicated - yet perfectly valid - way to achieve > the same thing. Bonus points for horribly abusing Python's clean > syntax in the process. Chris, i'm sorry, but your challenge is decades too late. If you seek amusement you need look no further than the Python stdlib. If you REALLY want to be amused, peruse the "idlelib" -- not only is the code obfuscated, it also breaks PEP8 and the PYTHON ZEN many times over. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question:Programming a game grid ...
On Jun 27, 5:21 pm, iconoclast011 wrote: > Fairly new to Python ... Is there a way to efficiently (different from my > brute > force code shown below) to set up a game grid of buttons (ie with pygame) > responding to mouse clicks ? I would want to vary the size of the grid ... > > Thanks > > Brute force code: > from Tkinter import * > > root = Tk() > > f = Frame(root, bg = "blue", width = 500, height = 500) > f.pack(side=LEFT, expand = 1) > > f3 = Frame(f, bg = "white", width = 500) > f3.pack(side=LEFT, expand = 1, pady = 50, padx = 50) > > #f2 = Frame(root, bg = "black", height=100, width = 100) > #f2.pack(side=LEFT, fill = Y) > > #b = Button(f2, text = "test") > #b.pack() > > var = 'b00' > vars()[var] = Button(f3, text = "00", bg = "white") > b00.grid(row=0, column=0) > b00.bind('', leftclick) # bind left mouse click > b00.bind('', rightclick) # bind left mouse click > > var = 'b01' > vars()[var] = Button(f3, text = "01", bg = "white") > b01.grid(row=0, column=1) > b01.bind('', leftclick) # bind left mouse click > b01.bind('', rightclick) # bind left mouse click > > b02 = Button(f3, text = "02", bg = "white") > b02.grid(row=0, column=2) > b02.bind('', leftclick) # bind left mouse click > b02.bind('', rightclick) # bind left mouse click > > b03 = Button(f3, text = "03", bg = "white") > b03.grid(row=0, column=3) > b03.bind('', leftclick) # bind left mouse click > b03.bind('', rightclick) # bind left mouse click > > b04 = Button(f3, text = "04", bg = "white") > b04.grid(row=0, column=4) > b04.bind('', leftclick) # bind left mouse click > b04.bind('', rightclick) # bind left mouse click > > b05 = Button(f3, text = "05", bg = "white") > b05.grid(row=0, column=5) > b05.bind('', leftclick) # bind left mouse click > b05.bind('', rightclick) # bind left mouse click > > b06 = Button(f3, text = "06", bg = "white") > b06.grid(row=0, column=6) > b07 = Button(f3, text = "07", bg = "white") > b07.grid(row=0, column=7) > b08 = Button(f3, text = "08", bg = "white") > b08.grid(row=0, column=8) > > b10 = Button(f3, text = "10", bg = "white") > b10.grid(row=1, column=0) > b11 = Button(f3, text = "11", bg = "white") > b11.grid(row=1, column=1) > b12 = Button(f3, text = "12", bg = "white") > b12.grid(row=1, column=2) > > b13 = Button(f3, text = "13", bg = "white") > b13.grid(row=1, column=3) > b14 = Button(f3, text = "14", bg = "white") > b14.grid(row=1, column=4) > b15 = Button(f3, text = "15", bg = "white") > b15.grid(row=1, column=5) > > b16 = Button(f3, text = "16", bg = "white") > b16.grid(row=1, column=6) > b17 = Button(f3, text = "17", bg = "white") > b17.grid(row=1, column=7) > b18 = Button(f3, text = "18", bg = "white") > b18.grid(row=1, column=8) > > b20 = Button(f3, text = "20", bg = "white") > b20.grid(row=2, column=0) > b21 = Button(f3, text = "21", bg = "white") > b21.grid(row=2, column=1) > b22 = Button(f3, text = "22", bg = "white") > b22.grid(row=2, column=2) > > b23 = Button(f3, text = "23", bg = "white") > b23.grid(row=2, column=3) > b24 = Button(f3, text = "24", bg = "white") > b24.grid(row=2, column=4) > b25 = Button(f3, text = "25", bg = "white") > b25.grid(row=2, column=5) > > b26 = Button(f3, text = "26", bg = "white") > b26.grid(row=2, column=6) > b27 = Button(f3, text = "27", bg = "white") > b27.grid(row=2, column=7) > b28 = Button(f3, text = "28", bg = "white") > b28.grid(row=2, column=8) > > b30 = Button(f3, text = "30", bg = "white") > b30.grid(row=3, column=0) > b31 = Button(f3, text = "31", bg = "white") > b31.grid(row=3, column=1) > b32 = Button(f3, text = "32", bg = "white") > b32.grid(row=3, column=2) > > b36 = Button(f3, text = "36", bg = "white") > b36.grid(row=3, column=6) > b37 = Button(f3, text = "37", bg = "white") > b37.grid(row=3, column=7) > b38 = Button(f3, text = "38", bg = "white") > b38.grid(row=3, column=8) > > b33 = Button(f3, text = "33", bg = "white") > b33.grid(row=3, column=3) > b34 = Button(f3, text = "34", bg = "white") > b34.grid(row=3, column=4) > b35 = Button(f3, text = "35", bg = "white") > b35.grid(row=3, column=5) > > b40 = Button(f3, text = "40", bg = "white") > b40.grid(row=4, column=0) > b41 = Button(f3, text = "41", bg = "white") > b41.grid(row=4, column=1) > b42 = Button(f3, text = "42", bg = "white") > b42.grid(row=4, column=2) > > b43 = Button(f3, text = "43", bg = "white") > b43.grid(row=4, column=3) > b44 = Button(f3, text = "44", bg = "white") > b44.grid(row=4, column=4) > b45 = Button(f3, text = "45", bg = "white") > b45.grid(row=4, column=5) > > b46 = Button(f3, text = "46", bg = "white") > b46.grid(row=4, column=6) > b47 = Button(f3, text = "47", bg = "white") > b47.grid(row=4, column=7) > b48 = Button(f3, text = "48", bg = "white") > b48.grid(row=4, column=8) > > b50 = Button(f3, text = "50", bg = "white") > b50.grid(row=5, column=0) > b51 = Button(f3, text = "51", bg = "white") > b51.grid(row=5, column=1) > b52 = Button(f3, text = "52", bg = "white") > b52.grid(row=5, column=2) > > b53 = Button(f3, text = "53", bg = "white"
Re: code review
On Jul 2, 3:20 am, Chris Angelico wrote: > On Mon, Jul 2, 2012 at 6:11 PM, Steven D'Aprano > > wrote: > > "c" < first_word < second_word == third_word < "x" > > > I'm sure I don't have to explain what that means -- that standard chained > > notation for comparisons is obvious and simple. > > > In Python, you write it the normal way, as above. But some other > > languages force you into verbosity: > > > ("c" < first_word) and (first_word < second_word) and (second_word == > > third_word) and (third_word < "x") > > Uhh, actually you DO have to explain that, because I interpreted it > quite differently: > > (("c" < first_word) and (first_word < second_word)) == (third_word < "x") Poor Chris. That's because you've been brainwashed into believing you must spoon feed your interpreter to get your code working correctly. Stop applying these naive assumptions to Python code. Python knows when you reach the end of a statement, no need for redundant semicolons! Python knows when its reached the end of block and needs to drop back one level, no need for redundant road signs. Python knows Chris; Python KNOWS! -- http://mail.python.org/mailman/listinfo/python-list
Re: code review
On Jun 30, 9:06 pm, Steven D'Aprano wrote: > On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote: > > Yes. My sole point, really, is that "normally", one would expect these > > two expressions to be equivalent: > > > a < b < c > > (a < b) < c > > Good grief. Why would you expect that? > > You can't just arbitrarily stick parentheses around parts of expressions > and expect the result to remain unchanged. Order of evaluation matters: > > 2**3**4 != (2**3)**4 Yes but as Chris points out in the next message, you can inject the following parenthesis without changing a thing!: py> 1 + 3 * 4 13 py> 1 + (3 * 4) 13 Of course i understand the rules of operator precedence, however i have never liked them AND i continue to believe that such functionality breeds bugs and is in fact bad language design. I believe all evaluations should be cumulative: py> 1 + 3 * 4 should ALWAYS equal 16! With parenthesis only used for grouping: py> a + (b*c) + d Which seems like the most consistent approach to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: code review
On Jul 2, 11:42 am, Chris Angelico wrote: > Rick, do you realize that you have > to spoon-feed the interpreter with spaces/tabs when other interpreters > just KNOW to drop back an indentation level when you close a brace? Yes. And significant white space is my favorite attribute of Python source code. But the difference here is like night and day. While your getting bogged down playing "match-the-brackets", i'm writing code and being productive. I don't need to put any mental effort into pressing the Enter+Tab keys. On the contrary, you must constantly break your mental focus to "corral" the braces, and the sad part is, you're still formatting your code like mine (with tabs and newlines!) however your simultaneously juggling superfluously archaic syntax! Why Chris? WHY? > I simply need to make sure that the interpreter and I have the same > understanding of the code. It will then work correctly. There's > nothing special about one syntax or another, I agree in the sense of: "to each his own". However. There are methods of writing code that are more productive, and methods that are less productive, and your emotive agenda of defending such nostalgic pedantry is quite self-defeating. > they're all just > communication from my brain to a CPU, and different syntaxes are > suited to different tasks. There's nothing inherently wrong with: > > right_length = len(x) > 5, < 20 Agreed. I wish we had one language. One which had syntactical directives for scoping, blocks, assignments, etc, etc... BLOCK_INDENT_MARKER -> \t BLOCK_DEDENT_MARKER -> \n STATEMENT_TERMINATOR -> \n ASSIGNMENT_OPERATOR -> := CONDITIONAL_IF_SPELLING -> IF CONDITIONAL_ELSE_SPELLING -> EL ... > (I quite like braces, myself, [...] and only a relatively small > amount of actual logic. So you have a penchant for confinement and an aversion to logic? Hmm, interesting! -- http://mail.python.org/mailman/listinfo/python-list
Re: code review
On Jul 2, 2:06 pm, Thomas Jollans wrote: > On 07/02/2012 08:22 PM, Rick Johnson wrote: > > > Agreed. I wish we had one language. One which had syntactical > > directives for scoping, blocks, assignments, etc, etc... > > > BLOCK_INDENT_MARKER -> \t > > BLOCK_DEDENT_MARKER -> \n > > STATEMENT_TERMINATOR -> \n > > ASSIGNMENT_OPERATOR -> := > > CONDITIONAL_IF_SPELLING -> IF > > CONDITIONAL_ELSE_SPELLING -> EL > > ... > > You must be joking. Well i was slightly serious, but mostly sarcastic. Whist customizable syntax would be a great benefit to the individual, it would be a nightmare to the community -- the real solution lies in assimilation! I am reminded of a story: A few years back a very nice old woman offered to give me her typewriter. She said: "i might need to type a letter one day and it would good to have around". It was a nice typewriter for 1956, but she had no idea her little "machine" was reduced to no less than a paper weight thanks to something called the PC. Her machine had been extinct for decades. Effectually, SHE had been extinct for decades. When i hear people like Chris evangelizing about slavish syntax, i am reminded of the nice old lady. Her intentions where virtuous, however her logic was flawed. She is still clinging to old technology. Like the Luddites she refuses to see the importance technological advancements. And by harboring this nostalgia she is actually undermining the future evolution of an entire species. Lifespans are limited for a very important evolutionary reason! -- http://mail.python.org/mailman/listinfo/python-list
Re: WxSlider Mouse Wheel Resolution
On Jul 2, 10:45 am, Wanderer wrote: > Is there a way to set the mouse wheel resolution for the wxPython > wx.Slider? I would like to use the graphic slider for coarse control > and the mouse wheel for fine control. Right now the mouse wheel makes > the slider jump ten counts and I would like it to be a single count. > > Thanks I have always found GUI mouse wheel events (and others) to be lacking in the "user tuned control" category. NOTE: Instead of forcing your lib users to configure specifics or re-bind events like(course, medium, fine) simply pre-bind the following events and empower the end user: MouseWheel -> cb(MEDIUM) MouseWheel+ControlKey -> cb(FINE) MouseWheel+ShiftKey -> cb(COURSE) What a novel FREAKING idea! *school-bell-rings* -- http://mail.python.org/mailman/listinfo/python-list
Re: WxSlider Mouse Wheel Resolution
On Jul 2, 3:45 pm, Rick Johnson wrote: > [...] > MouseWheel -> cb(MEDIUM) > MouseWheel+ControlKey -> cb(FINE) > MouseWheel+ShiftKey -> cb(COURSE) Of course some could even argue that three levels of control are not good enough; for which i wholeheartedly agree! A REAL pro would provide a configurable method to the user for which a slider (or numerical range) would pop up to micro-adjust the increment. However! I think all widgets should expose every configurable option to the end user. All configure options would be available by default and the developer can restrict ANY configure option(s) which would have disastrous side-effects for that particular GUI. -- http://mail.python.org/mailman/listinfo/python-list
Re: Discussion on some Code Issues
On Jul 4, 6:21 pm, subhabangal...@gmail.com wrote: > [...] > To detect the document boundaries, I am splitting them into a bag > of words and using a simple for loop as, > > for i in range(len(bag_words)): > if bag_words[i]=="$": > print (bag_words[i],i) Ignoring that you are attacking the problem incorrectly: that is very poor method of splitting a string since especially the Python gods have given you *power* over string objects. But you are going to have an even greater problem if the string contains a "$" char that you DID NOT insert :-O. You'd be wise to use a sep that is not likely to be in the file data. For example: "" or "". But even that approach is naive! Why not streamline the entire process and pass a list of file paths to a custom parser object instead? -- http://mail.python.org/mailman/listinfo/python-list
Re: simpler increment of time values?
On Jul 5, 10:19 am, Steven D'Aprano wrote: > The number of seconds in a day (true solar day) varies by between 13 and > 30 seconds depending on the time of the year and the position of the sun. Indeed. Which proves that a time keeping system based on the haphazard movements of celestial bodies is antiquated technology. Talk about job security! -- http://mail.python.org/mailman/listinfo/python-list