Re: [Fwd: Re: hex string to hex value]
tim wrote: > > I end up with 66 again, back where I started, a decimal, right? > I want to end up with 0x42 as being a hex value, not a string, so i can > pas it as an argument to a function that needs a hex value. > (i am trying to replace the 0x42 in the line midi.note_off(channel=0, > note=0x42) with a variable) As far as Python is concerned, 66 decimal and 42 hex are exactly the same thing. There's absolutely no difference in calling note_off(0x42) and note_off(66) See: >>> def f(c): ...print c ... >>> f(66) 66 >>> f(0x42) 66 >>> -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Repetition is a form of change // Brett g Porter * [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutability of function arguments?
ex_ottoyuhr wrote: > I'm trying to create a function that can take arguments, say, foo and > bar, and modify the original copies of foo and bar as well as its local > versions -- the equivalent of C++ funct(&foo, &bar). > > I've looked around on this newsgroup and elsewhere, and I gather that > this is a very common concern in Python, but one which is ordinarily > answered with "No, you can't. Neat, huh?" A few websites, newsgroup > posts, etc. have recommended that one ask for a more "Pythonic" way of > doing things; so, is there one, or at least one that doesn't involve > using objects as wrappers for mutable arguments? > > And, indeed, would that approach work? Would declaring: > > class FooWrapper : > __init__(fooToLoad) : > self.foo = fooToLoad > > mean that I could now declare a FooWrapper holding a foo, pass the > FooWrapper to a function, and have the function conclude with the foo > within the FooWrapper now modified? Well, you can test it yourself: >>> class wrapper(object): ...def __init__(self, val): ... self.val = val ... >>> w = wrapper(42) >>> w.val 42 >>> def foo(w): ...w.val = 11 ... >>> foo(w) >>> w.val 11 >>> > > Thanks in advance for everyone's time; I hope I'm comprehensible. You're comprehensible, but I think that you're also thinking in C++. The object model that Python follows is very different -- instead of thinking of assignment meaning "Stick this value into this named location", you need to switch to thinking of assignment as meaning "stick this name onto that object until I tell you otherwise". If you're trying to return multiple values from a function, Python lets you do that >>> def multiFoo(x, y, z): ... return x*2, y*2, z*2 ... >>> x = 1 >>> y = 2 >>> z = 3 >>> x, y, z = multiFoo(x, y, z) >>> x 2 >>> y 4 >>> z 6 >>> -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Repetition is a form of change // Brett g Porter * [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to compare files
Lad wrote: > Hi, > What is the best method for comparing two files by words? > I was thinking about reading files by words and compare them but a word > in one file can be linked with a new line character ( \n) > and this '\n' will cause that the words will considered to be > different( eventhough without '\n' are the same) > > Thanks for help. > LAd. > Have you looked at the difflib module that comes with Python? http://docs.python.org/lib/module-difflib.html -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Defending Python
Jorey Bump wrote: > > Monty Python's Flying Circus used to begin with "It's..." I had read at one > time that "It's" was one of the original names proposed for the > troupe/show, although I can't seem to find verification. "In fact, one of the titles of the show was 'It's', so he must have been in there fairly early on. On a list of titles I've got scribbled in a notebook was 'It's' and just 'It,' so that's probably where he came from." -- Michael Palin (referring to the "It's" man) in _The First 20 Years of Monty Python_ by Kim "Howard" Johnson (St. Martin's Press, 1989), p.20 -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * [EMAIL PROTECTED] // http://bgporter.inknoise.com/JerseyPorkStore -- http://mail.python.org/mailman/listinfo/python-list
Re: First Script Problem
Ed Hotchkiss wrote: > This script should just be writing every possibly IP (yea, there are > billions i know blah blah) to a txt file. Instead of just writing the > IP, it continues and the number goes past 4 groups. IE: The possible IP > keeps getting 3 characters longer every time. And at the end of the last > loops do I somehow have to set my mySet to NULL? Any ideas here? > > -- > edward hotchkiss > > > > > > # Script to Evaluate every possible IP Address Combo, then write it to a > text file > # 9/15/05 > > # ipFileLocation = r"G:\Python\myCode\IPList.txt" > > ipFileLocation = "IPList.txt" > ipFile = open(ipFileLocation, 'w') > > def findIPs(): > for num in range(256): > mySet = "%03.d" % num okay -- at this point, on the first iteration of this outer loop, mySet is '000' > for num in range(256): >mySet = mySet + "." + "%03.d" % num and on the first iteration of this first inner loop, mySet is '000.000' >for num in range(256): > mySet = mySet + "." + "%03.d" % num second inner loop, first iteration, mySet is '000.000.000' > for num in range(256): > mySet = mySet + "." + "%03.d" % num > ipFile.write(mySet+"\n") Okay -- this innermost loop will now be executed 256 times (values ranging from 0 to 255, and mySet just keeps getting appended to, creating the ever-growing output string that you see. A better way to write this would be something like: for octet1 in range(256): for octet2 in range(256): for octet3 in range(256): for octet4 in range(256): ipAddress = '%03.d.%03.d.%03.d.%03.d\n' % (octet1, octet2, octet3, octet4) ipFile.write(ipAddress) ...which will generate output like you're looking for: 000.000.000.000 000.000.000.001 000.000.000.002 000.000.000.003 000.000.000.004 000.000.000.005 000.000.000.006 000.000.000.007 000.000.000.008 000.000.000.009 000.000.000.010 000.000.000.011 000.000.000.012 000.000.000.013 000.000.000.014 Also note that growing strings by concatenating with '+' is going to create code that runs very slowly as the strings continue to grow -- much better to either use string formatting or the idiom of using the join method of list objects to create a string in a single pop once a list of substrings is all populated. -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Destroy -nothing -the most important thing // Brett g Porter * [EMAIL PROTECTED] // http://bgporter.inknoise.com/JerseyPorkStore -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern matching with string and list
BartlebyScrivener wrote: > Even without the marker, can't you do: > > sentence = "the fabric is red" > colors = ["red", "white", "blue"] > > for color in colors: > if (sentence.find(color) > 0): > print color, sentence.find(color) > That depends on whether you're only looking for whole words: >>> colors = ['red', 'green', 'blue'] >>> def findIt(sentence): ...for color in colors: ... if sentence.find(color) > 0: ... print color, sentence.find(color) ... >>> findIt("This is red") red 8 >>> findIt("Fredrik Lundh") red 1 >>> It's easy to see all the cases that this approach will fail for... -- http://mail.python.org/mailman/listinfo/python-list
Re: URL 'special character' replacements
Claude Henchoz wrote: > Hi guys > > I have a huge list of URLs. These URLs all have ASCII codes for special > characters, like "%20" for a space or "%21" for an exclamation mark. > > I've already googled quite some time, but I have not been able to find > any elegant way on how to replace these with their 'real' counterparts > (" " and "!"). > > Of course, I could just replace(), but that seems to be a lot of work. > > Thanks for any help. > > Cheers, Claude > The standard library module 'urllib' gies you two choices, depending on the exact behavior you'd like: http://www.python.org/doc/2.3.2/lib/module-urllib.html unquote(string) Replace "%xx" escapes by their single-character equivalent. Example: unquote('/%7Econnolly/') yields '/~connolly/'. unquote_plus(string) Like unquote(), but also replaces plus signs by spaces, as required for unquoting HTML form values. -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Accretion // Brett g Porter * [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: String handling and the percent operator
Justin Azoff wrote: > Tom Plunket wrote: >> boilerplate = \ >> """ > [big string] >> """ >> >> return boilerplate % ((module,) * 3) >> [deletia...] > Of course.. > stuff = {'lang': 'python', 'page': 'typesseq-strings.html'} print """I should read the %(lang)s documentation at > ... http://docs.%(lang)s.org/lib/%(page)s""" % stuff > I should read the python documentation at > http://docs.python.org/lib/typesseq-strings.html ...or perhaps cooler: http://docs.python.org/lib/node109.html something like: from string import Template def GetPyContents(module): boilerplate = Template( \ """ class $moduleName: pass if __name__ == '__main__': import unittest unittest.main('${moduleName}_t') """) return boilerplate.substitute(moduleName=module) -- http://mail.python.org/mailman/listinfo/python-list
Re: xmlrpclib and methods declared at runtime
squid wrote: > > Based on having read the python tutorial and remembering the list of > built-in functions, my guess would have been calling setattr in the > constructor or after doing a listMethods operation against the XML-RPC > server.. That is, assuming the XML-RPC service supports this api.. > something like that.. But that does not seem to be the case here, as a > search of xmlrpclib.py does not show ANY instances of setattr being > used. I did, however, notice some cases of classes implementing a > __getattr__ method, which leads me to the question of how the > interpreter performs lookup of methods when they are called. Does it > use getattr itself? Is it possible to, say, effectively override > getattr for a specific class, thereby returning a pointer to a generic > function that could be used to handle... well.. everything? > You seem to have gotten it. When Python can't find an attribute in an object's dict, it then looks for the magic __getattr__ method. If it's present, it passes that method the name that you're looking for. This lets you synthesize attributes and methods at runtime. >>> class Foo(object): ...def __getattr__(self, name): ... return name.upper() ... >>> f = Foo() >>> f.test 'TEST' With xml-rpc, a method call on your side of the connection is implemented by building up an XML message and sending it to the server -- rather than statically try to figure out what oprations the server supports, xmlrpclib will happily attempt to call any method name that you can think of, and let the server tell you if there's an error. It's probably not a good idea to let __getattr__ handle EVERYTHING your class needs to do, but in cases like this where you don't know in advance what the class will need to handle, it lets your code hide the magic in a way that lets the users of your code forget that there's anything magic going on at all. It just looks like code. -- // Brett g Porter * [EMAIL PROTECTED] // http://www.bgporter.net/blog -- http://mail.python.org/mailman/listinfo/python-list
Re: do people really complain about significant whitespace?
[EMAIL PROTECTED] wrote: > Its not the typing, its the fact that when you say the same thing > twice, there is the potential for them to get out of sync. If the > method the compiler uses (braces) and the method the human uses > (indentation) to determine what the code does don't agree, then a > reader will be likely to misunderstand what it will actually do. One > of the driving principles behind Python is that, because code will be > read more often than written, readability is more important. Not to mention the errors that creep in when code is maintained, like when C code starting out as if (i < SOME_CONSTANT) doSomething(); gets "maintained" to if (i < SOME_CONSTANT) doSomething(); doSomethingDangerous(); without the programmer adding the surrounding braces. The programmer's intent is clear to me as a human, but the C compiler will disagree with me, and in this case, the compiler will be right and I'm wrong. You can (and we do, at my company) have coding standards that mandate braces around single line if()s in C/C++, but that's really just patching around the problem (and it counts on humans being consistent). Pushing the scutwork down onto tools is not as good a solution as eliminating the scutwork, especially when it shouldn't be necessary at all... -- // Brett g Porter * [EMAIL PROTECTED] // http://www.bgporter.net/blog -- http://mail.python.org/mailman/listinfo/python-list
Re: How to *Search* with google from inside my programme and get the search result?
I V wrote: > Frank Potter wrote: >> Does google supply some webservice to programmers? I did see > > Googling for "google api" gets you to: > > http://www.google.com/apis/ > > It appears to be a SOAP API, which you can access with python, but I > think you'll need a third-party library. Googling for "python soap" > gets you: > > http://www-128.ibm.com/developerworks/library/ws-pyth5/ > > which might be a place to start. > Or even easier: http://pygoogle.sourceforge.net/ SUMMARY --- This module allows you to access Google's web APIs through SOAP, to do things like search Google and get the results programmatically. This API is described here: http://www.google.com/apis/ SYSTEM REQUIREMENTS --- Requires Python 2.0 or later Requires the SOAPpy library from the Python Web Services project (http://pywebsvcs.sourceforge.net). We include an older version, but its use is now deprecated (and will go away completely in future releases). Unfortunately, versions of SOAPpy prior to 0.11.3 will not work correctly, and thus PyGoogle will fall back on the included SOAP.py library if an earlier version is found. // BgP -- http://mail.python.org/mailman/listinfo/python-list
Re: Python forum
Jonas Melian wrote: > Hi, > > I'm going to say a suggestion, why don't you create a forum like the one > of Ruby (http://www.rubyforums.com/)? for the novices this is a great > help, better than a mail list > > It's also worth noting that rubyforums.com has nearly no posts (six > total) because it takes very just a short time working. > > I know that you have python-list, it's both an email and a usenet list. > But I think that a forum is great for the learning. The test is in > gentoo's forums. They are a lot of experienced people answering > questions without any problem and it goes very well > > Thanks Don't forget that there's also the Tutor list (see http://www.python.org/mailman/listinfo/tutor ), targeted to people looking to learn the language... -- // Today's Oblique Strategy (© Brian Eno/Peter Schmidt): // Change instrument roles // Brett g Porter * [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteration over strings
Robert Dailey wrote: > Hi, > > I have the following code: > > str = "C:/somepath/folder/file.txt" > > for char in str: > if char == "\\": > char = "/" > > The above doesn't modify the variable 'str' directly. I'm still pretty > new to Python so if someone could explain to me why this isn't working > and what I can do to achieve the same effect I would greatly appreciate it. > The thing that you need to remember is that strings in Python never change (and nothing ever changes that). Any time that you start out thinking "I need to change this string' you need to immediately translate that thought into "I need to create a new string with some changes made to this string". String objects can already do what you're trying to do here: >>> str = "C:\\somepath\\folder\\file.txt" >>> str 'C:\\somepath\\folder\\file.txt' >>> str2 = str.replace('\\', '/') >>> str2 'C:/somepath/folder/file.txt' >>> str 'C:\\somepath\\folder\\file.txt' replace() returns a new string with all instances of the 1st subsstring replaced with the second substring -- note that the original string 'str' is unmodified. Also note that if this is your actual use case, the standard lib also contains a function os.path.normpath() that does all the correct manipulations to correctly normalize file paths on the current platform. -- http://mail.python.org/mailman/listinfo/python-list
Re: Eureka moments in Python
Steven D'Aprano wrote: > I'd be interested in hearing people's stories of Eureka moments in Python, > moments where you suddenly realise that some task which seemed like it > would be hard work was easy with Python. Mine was definitely when I was first working with the xmlrpc module, and I was puzzled to no end how it was that I was able to make a call to a method of an object when that method didn't exist. All the talk about Python being a dynamic language had bounced off of me until that moment, when I walked through the __getattr__ method in the debugger and was enlightened. Not surprisingly, that was also the moment when C++ started feeling like a straightjacket to me... -- http://mail.python.org/mailman/listinfo/python-list
Re: Eureka moments in Python
Dustan wrote: > On Mar 13, 10:05 am, Brett g Porter <[EMAIL PROTECTED]> wrote: >> Steven D'Aprano wrote: >>> I'd be interested in hearing people's stories of Eureka moments in Python, >>> moments where you suddenly realise that some task which seemed like it >>> would be hard work was easy with Python. >> Mine was definitely when I was first working with the xmlrpc module, and >> I was puzzled to no end how it was that I was able to make a call to a >> method of an object when that method didn't exist. All the talk about >> Python being a dynamic language had bounced off of me until that moment, >> when I walked through the __getattr__ method in the debugger and was >> enlightened. >> >> Not surprisingly, that was also the moment when C++ started feeling like >> a straightjacket to me... > > Started? Meaning there was a time when it DIDN'T feel like a > straightjacket? If I were a journalist, this would be all over the > news... > If you're born wearing a straightjacket, I'm sure that it feels natural and fine until the first time someone unties it... -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-web-based templating system
Diez B. Roggisch wrote: > [EMAIL PROTECTED] wrote: > > Maybe the built-in string interpolation is sufficient? > > print "Hello %(name)s" % dict(name="Peter Pan") Or in recent pythons, the built-in string templating system (see http://docs.python.org/lib/node109.html) >>> from string import Template >>> d = dict(name="Barney") >>> s = Template("Hello $name") >>> s.substitute(d) 'Hello Barney' -- http://mail.python.org/mailman/listinfo/python-list
Re: Python program as daemon?
Johny wrote: Is it possible to run a Python program as daemon? Sure -- see http://code.activestate.com/recipes/66012/ for an example (and some useful stuff in the comments.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Reasoning behind 'self' parameter in classes?
Robert Dailey wrote: This is an example of a response I'm looking for: "The self parameter is required because the parser is a bit old and needs to know the exact object you're referencing" This is _not_ an example of what I'm looking for: "Specifying self is a great mysterious thing that we should never question. Do not question the language! The language is mighty! Don't bring C++ to Python!" Fredrik Lundh has written a very clear explanation of this at http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm (or http://bit.ly/3EUiCf if you don't feel like stitching that URL back together...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python MIDI in 2008
Maciej Bliziński wrote: For the last couple of days, I've been looking for a Python midi library. I'm generally interested in sending MIDI events via ALSA. It seems like everything out there is pretty old; packages are from 2003 or 2005. Some packages don't seem to be really used, for instance portmidi doesn't even support installing it system-wide; you can compile it and... no make install for you. I haven't used the PortMidi bindings that are in the Cheeseshop at http://pypi.python.org/pypi/pyPortMidi/0.0.3 but I've used PortMidi extensively from C++ code and have had excellent results with it. -- http://mail.python.org/mailman/listinfo/python-list