Re: Updating path.py
Robert Kern wrote: On 7/26/10 5:16 PM, Michael Hoffman wrote: I have been using Jason Orendorff's path.py module for a long time. It is very useful. The only problem is that Python 2.6 deprecates the md5 module it imports, so I (and others using my software) now get this warning whenever they start, which is a little annoying. /homes/hoffman/arch/Linux-x86_64/lib/python2.6/path-2.2-py2.6.egg/path.py:32: DeprecationWarning: the md5 module is deprecated; use hashlib instead The original web page is gone, and e-mails to the author have gone unanswered. It has a "public domain" license so I could easily fork it and make this small change. The question is what is the best way to do that and ensure continuity with the previous versions. Can I (or someone else) take over the PyPI entry in question? Other suggestions? You cannot "take over" a project on PyPI. You can only fork the project with a new name. In fact, this has already been done: http://pypi.python.org/pypi/forked-path/0.1 Great, I'll start by trying that, I was hoping someone already had a solution. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Updating path.py
I have been using Jason Orendorff's path.py module for a long time. It is very useful. The only problem is that Python 2.6 deprecates the md5 module it imports, so I (and others using my software) now get this warning whenever they start, which is a little annoying. /homes/hoffman/arch/Linux-x86_64/lib/python2.6/path-2.2-py2.6.egg/path.py:32: DeprecationWarning: the md5 module is deprecated; use hashlib instead The original web page is gone, and e-mails to the author have gone unanswered. It has a "public domain" license so I could easily fork it and make this small change. The question is what is the best way to do that and ensure continuity with the previous versions. Can I (or someone else) take over the PyPI entry in question? Other suggestions? Many thanks, Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Presentation software for Python code
Sebastian Wiesner wrote: I'm willing to consider TeX- and HTML-based approaches. I can recommend latex with the beamer package. It doesn't directly support formatting of code snippets, but the pygments syntax highlighter comes with a Latex formatter. This is what I have been doing so far, and it works pretty well. Thanks! Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Presentation software for Python code
alex23 wrote: How do you feel about reStructuredText? If you're open to it, I highly recommend Bruce: http://pypi.python.org/pypi/bruce That looks like it would be perfect. Unfortunately it doesn't seem to work on my Windows laptop: C:\Documents and Settings\Michael\Desktop\bruce-3.2.1>C:\Python25\python.exe bru ce.pyw ..\bruce-3.2.1-examples\test_bullet_mode.rst Traceback (most recent call last): File "bruce.pyw", line 6, in run.main() File "bruce-library.zip\bruce\run.py", line 25, in main File "bruce-library.zip\bruce\run.py", line 217, in cmd_line File "bruce-library.zip\bruce\run.py", line 313, in run File "bruce-library.zip\bruce\presentation.py", line 31, in start_presentation File "bruce-library.zip\bruce\page.py", line 29, in create File "bruce-library.zip\bruce\layout.py", line 143, in create File "bruce-library.zip\pyglet\graphics\__init__.py", line 348, in add File "bruce-library.zip\pyglet\graphics\__init__.py", line 436, in _get_domain File "bruce-library.zip\pyglet\graphics\vertexdomain.py", line 135, in create_ domain File "bruce-library.zip\pyglet\graphics\vertexdomain.py", line 174, in __init_ _ File "bruce-library.zip\pyglet\graphics\vertexbuffer.py", line 117, in create_ mappable_buffer File "bruce-library.zip\pyglet\graphics\vertexbuffer.py", line 383, in __init_ _ File "bruce-library.zip\pyglet\graphics\vertexbuffer.py", line 301, in __init_ _ File "bruce-library.zip\pyglet\gl\lib_wgl.py", line 94, in __call__ File "bruce-library.zip\pyglet\gl\lib.py", line 63, in MissingFunction pyglet.gl.lib.MissingFunctionException: glGenBuffers is not exported by the avai lable OpenGL driver. VERSION_1_5 is required for this functionality. Exception exceptions.AttributeError: "'VertexDomain' object has no attribute 'at tributes'" in =[]>> ignored I don't understand this. OpenGL Extensions Viewer says I have OpenGL 1.5 and the glGenBuffers function. -- http://mail.python.org/mailman/listinfo/python-list
Re: Presentation software for Python code
Thanks for the suggestions. And if you do use Crunchy for a presentation, you might be interested in the html style used for Crunchy's own talk at the latest Pycon: http://us.pycon.org/media/2009/talkdata/PyCon2009/012/crunchy_.html H, I have to click on the next link every time? The best option might be to use an existing HTML presentation style with keyboard shortcuts. -- http://mail.python.org/mailman/listinfo/python-list
Presentation software for Python code
I mean to give a presentation next week to my workgroup on good Python programming practice. Last time I did a Python presentation I used PowerPoint which was not totally well-suited for the task. In particular, formatting code snippets was a pain, and they weren't even prettyprinted. Does anyone here have software they would suggest for making a presentation that includes Python code? Other than that it would probably be mainly bullet points. I'm willing to consider TeX- and HTML-based approaches. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the full path of an executable
Unknown wrote: On 2009-01-16, Michael Hoffman <9qobl2...@sneakemail.com> wrote: Is there a portable way to find the full path of a filename that would be called by os.execvp()? Yes. Use os.path.abspath() on the name before you call it with os.execvp() That doesn't work: Python 2.5.2 (r252:60911, Sep 23 2008, 19:04:15) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.path.abspath("echo") '/net/noble/vol2/home/mmh1/echo' >>> os.execvp(os.path.abspath("echo"), ["echo", "spam"]) Traceback (most recent call last): File "", line 1, in File "/net/noble/vol2/home/mmh1/arch/Linux-i386/opt/python-2.5.2/lib/python2.5/os.py", line 353, in execvp _execvpe(file, args) File "/net/noble/vol2/home/mmh1/arch/Linux-i386/opt/python-2.5.2/lib/python2.5/os.py", line 377, in _execvpe func(file, *argrest) OSError: [Errno 2] No such file or directory >>> os.execvp("echo", ["echo", "spam"]) spam The correct answer would be "/bin/echo" but abspath("echo") is just going to give me /echo. I need something that will search through the PATH like execvp() would. I can do it myself, but I'm surprised that such a feature is not already readily available somewhere. Michael -- http://mail.python.org/mailman/listinfo/python-list
Finding the full path of an executable
Is there a portable way to find the full path of a filename that would be called by os.execvp()? Thanks, Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
Michael Hoffman wrote: unlink = os.unlink Actually, I need to use shutil.rmtree instead, but you get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
Please accept my apologies if this message was posted several times. My newsreader claimed that a timeout error kept the message from being posted, but I think it got through. -- http://mail.python.org/mailman/listinfo/python-list
Using NamedTemporaryDir instead of multiple NamedTemporaryFiles
I am writing a library that creates temporary files and calls a series of external programs to process these files. Sometimes these external programs create files in the same directory as the input files, so to make sure they are all deleted, one must create them in a temporary directory, then delete it. I've written a NamedTemporaryDir class which is derived somewhat from tempfile.NamedTemporaryFile in the standard library. Right now I am using NamedTemporaryFile to create individual files, but since I am putting them in a directory that will be deleted anyway, I'm wondering if I can simplify things (and not have to keep track of all fo the NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my temporary directory, and relying on the directory deletion when exiting its with block. Is there any reason I should keep track of each temporary files myself instead of deleting the whole directory? I am using Linux, but I would also be interested in cross-platform considerations. Also, the code is below. Is this worth submitting as a patch? # NamedTemporaryFile is based somewhat on Python 2.5.2 # tempfile._TemporaryFileWrapper # # Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python # Software Foundation; All Rights Reserved # # License at http://www.python.org/download/releases/2.5.2/license/ from tempfile import mkdtemp class NamedTemporaryDir(object): def __init__(self, *args, **kwargs): self.name = mkdtemp(*args, **kwargs) self.close_called = False def __enter__(self): return self unlink = os.unlink def close(self): if not self.close_called: self.close_called = True self.unlink(self.name) def __del__(self): self.close() def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result -- http://mail.python.org/mailman/listinfo/python-list
Re: pylint style convention
Mick Charles Beaver wrote: > Hello, > > I've been looking into using PyLint on some of my programs, just as a > best practices kind of thing. > > Here's a snippet: > #== > if __name__ == '__main__': > parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]') > parser.add_option('-c', '--config', > action='store', > type='string', > dest='configFilename', > help='config file containing defaults') > (options, args) = parser.parse_args() > #== > > Now, PyLint reports the following convention warnings: > C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > > Which style convention is it referring to? Should these really be all > caps? There's a style convention that global constants at file scope are defined in all caps. Personally, I do all my optparsing in a special function rather than in the __name__ == '__main__' block. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting values out of a CSV
Daniel wrote: > On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina > <[EMAIL PROTECTED]> wrote: > >> Note that every time you see [x for x in ...] with no condition, you >> can write list(...) instead - more clear, and faster. > > Faster? No. List Comprehensions are faster. Why do you think that? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Alan Isaac wrote: > Is there any discussion of having real booleans > in Python 3000? I'm not sure how the bools we have now are not "real." > Say something along the line of the numpy implementation for arrays of > type 'bool'? What aspect of this do you want? A bool typecode for the stdlib array module? I can guess a number of things that you might mean, but it would be best if you explained with an example of what current behavior is and what you would like it to be. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Eduardo "EdCrypt" O. Padoan wrote: > On 6/30/07, Bruno Desthuilliers > <[EMAIL PROTECTED]> wrote: >> Eduardo "EdCrypt" O. Padoan a écrit : >> > Remember that pure CPython has no different "compile time" and >> > runtiime. >> >> Oh yes ? So what's the compiler doing, and what are those .pyc files ? >> (hint: read the doc) > > Sorry, I surely know that Python has a compile time, I wanted to say > somthing like "compile time checks except from syntax". Well, if you try to reassign __debug__ or None you get a SyntaxError, but I don't think it is truly checking syntax. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python compilation ??
Steve Holden wrote: > Evan Klitzke wrote: >> On 7/2/07, Cathy Murphy <[EMAIL PROTECTED]> wrote: >>> Is python a compiler language or interpreted language. If it is >>> interpreter >>> , then why do we have to compile it? >> >> It's an interpreted language. It is compiled into bytecode (not >> machine code) the first time a script is run to speed up subsequent >> executions of a script. >> > While the flavor of this answer is correct, in strict point of fact > Python *doesn't* compile the scripts it executes, only the modules that > are imported. I think you mean that CPython doesn't save the results of the compilation of a script. The scripts are compiled every time they are run, as you go on to say. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python changing keywords name
Gabriel Genellina wrote: > "except" is hard to translate, and > even in English I don't see what is the intended meaning (is it a noun? > a verb? an adverb? all look wrong). It's a preposition. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Excuse me!!
[EMAIL PROTECTED] wrote: > Haven't you thought about what is the right religion?! Sure, why do you think I use Python? > Here you will get the answer Agreed. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: socket on cygwin python
[EMAIL PROTECTED] wrote: > I've installed cygwin with latest python 2.5.1, but it seems that the > socket lib file do NOT support IPv6(cygwin\lib\python2.5\lib-dynload > \_socket.dll), what can I do if I want to use IPv6? I don't think Cygwin supports IPv6. Use the native Windows Python. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: dealing with emf/wmf files
Jackie Wang wrote: > I'd like to put some emf/wmf pictures into a pdf file > using 'reportlab', but the Python Imaging Library > cannot recognize emf files. The wmf files are said to > be 'identified only'. libwmf (not for Python) can convert WMF (not EMF) to SVG or EPS. http://wvware.sourceforge.net/libwmf.html -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing variable from a function within a function
Nathan Harmston wrote: > Hi, > > I m playing around with extended euclids algorithm from Knuth. I m > trying to build a function with a function inside it. > > def exteuclid(m,n): > a,a1,b,b1,c,d = 0,1,1,0,m,n > def euclid(c,d): >q = c /d >r = c % d >if r == 0: >print a,b >return d >else: >print a1,a,b1,b,c,d,q,r >t = b1 >b = t - q * b >a = t - q * a >c,d,a1,b1 = d,r,a,b >return euclid(c,d) >return euclid(c,d) > > Unfortunately this doesnt work since a,a1,b,b1 arent declared in the > function. Is there a way to make these variables accessible to the > euclid function. Or is there a better way to design this function? Well, it would be simpler to pass through all the variables rather than relying on variables in a wider scope. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python changing keywords name
[EMAIL PROTECTED] wrote: > Hello AGAIN, > > I on working on windows and Python 2.4. Where can I find and CHANGE > python > grammar. ( I just want to change the keywords ) > > PLEASE HELP ME > SOMEBODY!! > > THANKS! This is the third time you have posted this today. Please stop. Also, you might want to moderate the tone of your messages. Some people might find a string of all caps and exclamation marks obnoxious. I think it is less likely to get you help. You may find this guide helpful <http://www.catb.org/~esr/faqs/smart-questions.html>. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Eduardo "EdCrypt" O. Padoan wrote: > On 6/22/07, John Nagle <[EMAIL PROTECTED]> wrote: >> Paul Boddie wrote: >> > P.S. I agree with the sentiment that the annotations feature of Python >> > 3000 seems like a lot of baggage. Aside from some benefits around >> > writing C/C++/Java wrappers, it's the lowest common denominator type >> > annotation dialect that dare not be known as such, resulting from a >> > lack of consensus about what such a dialect should really do, haunted >> > by a justified fear of restrictive side-effects imposed by a more >> > ambitious dialect (eg. stuff you get in functional languages) on >> > dynamically-typed code. I don't think the language should be modified >> > in ways that only provide partial, speculative answers to certain >> > problems when there's plenty of related activity going on elsewhere >> > that's likely to provide more complete, proven answers to those >> > problems. >> >> I agree. It's a wierd addition to the language. It looks like >> a compromise between the "no declarations" position and the "make >> the language strongly typed" position. But it's so ill-defined that >> it's not helpful, and worse than either extreme. The whole >> approach is antithetical to the "only one way to do it" concept. >> This could lead to misery when different libraries use >> incompatible type annotation systems, which is not going to be fun. >> >> Python made it this far without declarations, and programmers >> seem to like that. We need to get Python performance up, and >> the ShedSkin/Psyco restrictions seem to be enough to allow that. >> Type annotations don't seem to solve any problem that really needs >> to be solved. >> >> The main advantage of strongly typed systems is that more errors >> are detected at compile time. You pay for this in additional language >> baggage. PEP 3107 adds the excess baggage without providing the benefit >> of compile time checks. > > Remember that pure CPython has no different "compile time" and > runtiime. Yes, it does. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: What was that web interaction library called again?
Harald Korneliussen wrote: > Hi, > > I remember I came across a python library that made it radically > simple to interact with web sites, connecting to gmail and logging in > with four or five lines, for example. I thought, "that's interesting, > I must look into it sometime". Now there's this child I know who asked > me about programming, especially programs that could do things like > this, how difficult it was, and so on. I mentioned how I though Python > was a good intro to programming, and there was a library which was > perfect for what he wanted. > > Only now I've forgotten the name of the library! And try as I might, I > can't find it with google. I know there are modules for it in the > standard libraries, but this thing was brilliantly simple in > comparison. It might have been some sort of research project, I can't > remember... but perhaps someone here can remind me what it was? If so, > there may be yet another young python programmer in training :-) BeautifulSoup? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Indenting in Emacs
John J. Lee wrote: > Eugene Morozov <[EMAIL PROTECTED]> writes: > >> Steven W. Orr пишет: >> > Ok. I'm not stupid but I do not see a 4.78 anywhere even though I >> see refs >>> from google. I have 4.75 The SVN tree doesn't seem to even have >>> that. >>> >>> I checked the latest copy out from sourceforge and that was 4.75 too. >>> >>> Can someone please tell me where to find the latest? >>> >> It's from Emacs 22. > > Note that's a different python-mode to the old one that lives on SF. > Yes, there are now two of them. Which one is better? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Can python access windows clipboard
MaHL wrote: > Can I use python to copy something(like a string) to the clipboard, so > that I can paste it somewhere else. Is there a way to do this? If you're using Cygwin Python you can just open /dev/clipboard and work on that. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Indenting in Emacs
[EMAIL PROTECTED] wrote: > Hello, > Does anyone know how to make python-mode correctly indent nested lists > and dictionaries. I hate indenting Django url patterns and Zope > Archetypes schemas by hand, because python-mode indents them in > incorrect and ugly way. > > Here's how it should be: > StringField('reference', > widget=StringWidget( >description='Position reference' > )), > > Here's how python-mode indents this code: > schema = BaseSchema.copy() + Schema(( > StringField('reference', > widget=StringWidget( > description='Position reference' > )), I get: schema = BaseSchema.copy() + Schema(( StringField('reference', widget=StringWidget( description='Position reference' )), I'm using py-version "$Revision$." Oops! Anyway, try to install the latest python-mode, whatever that is, if it isn't 4.78. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Stephen R Laniel wrote: > On Wed, Jun 20, 2007 at 12:59:28PM -0700, [EMAIL PROTECTED] wrote: >> Then you should use another language. > > This is what I meant about knowing how Internet discussions > go. You originally said "Before I ask anything, let me note that this is surely an old question that has inspired its share of flame wars; I'm new to Python, but not new to how Internet discussions work." In that context, there is no way that this response was a flame. I find that Pythoneers want to use the right tool for the job. This isn't always Python. It might be Perl, or OCaml, or Java, or C, or JCL. If you want static type checking, Python definitely isn't the right tool for you. If you asked Java programmers why you couldn't turn *off* Java's static type checking if you wanted to, you'd probably get a similar response. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: DFW Pythoneers Meeting THIS Saturday
peter wrote: >> It says right in the subject line! DFW. If you don't know what DFW >> means, then it's probably not your local area. > > Precisely Precisely what? You complained that the OP didn't provide the location of the event, which he did. You also resorted to needless name-calling as a result of your mistake, which I don't think enhances the usefulness of this forum. What exactly are you trying to achieve? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: DFW Pythoneers Meeting THIS Saturday
peter wrote: > Just a tad arrogant, don't you think, to put a notice of some local > event on an international forum without saying where it is? It says right in the subject line! DFW. If you don't know what DFW means, then it's probably not your local area. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Questions about mathematical and statistical functionality in Python
Talbot Katz wrote: > I hope you'll indulge an ignorant outsider. I work at a financial > software firm, and the tool I currently use for my research is R, a > software environment for statistical computing and graphics. R is > designed with matrix manipulation in mind, and it's very easy to do > regression and time series modeling, and to plot the results and test > hypotheses. The kinds of functionality we rely on the most are standard > and robust versions of regression and principal component / factor > analysis, bayesian methods such as Gibbs sampling and shrinkage, and > optimization by linear, quadratic, newtonian / nonlinear, and genetic > programming; frequently used graphics include QQ plots and histograms. > In R, these procedures are all available as functions (some of them are > in auxiliary libraries that don't come with the standard distribution, > but are easily downloaded from a central repository). I use both R and Python for my work. I think R is probably better for most of the stuff you are mentioning. I do any sort of heavy lifting--database queries/tabulation/aggregation in Python and load the resulting data frames into R for analysis and graphics. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.normpath bug?
billiejoex wrote: > Hi there, > I've noticed that os.path.normpath does not collapse redundant > separators if they're located at the beginning of the string: > >>>> print os.path.normpath('/a//b//c') > \a\b\c >>>> print os.path.normpath('//a//b//c') > \\a\b\c > > Is it intentional or is it a bug? Intentional. http://en.wikipedia.org/wiki/Path_(computing)#Universal_Naming_Convention -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I capture all exceptions especially when os.system() fail? Thanks
Gabriel Genellina wrote: > En Wed, 13 Jun 2007 21:47:16 -0300, mike <[EMAIL PROTECTED]> escribió: > >> Following piece of code can capture IOError when the file doesn't >> exist, also, other unknown exceptions can be captured when I press >> Ctrl-C while the program is sleeping(time.sleep). Now the question is: >> when I run the non-exist command, the exception cannot be captured. > >> So far so good, then I changed the code to run a non-exist command >> "wrong_command_test"(commented the open and sleep lines), then the >> script printed: >> sh: wrong_command_test: command not found >> well Done > > That's because it is not an exception, it is an error message coming > from your shell, not from Python. Of course if you use subprocess.check_call() instead of os.system(), it will become an exception (CalledProcessError). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Optimizing constants in loops
Thomas Heller wrote: > Just use the builtin __debug__ variable for that purpose. > __debug__ is 'True' if Python is run normally, and 'False' > if run with the '-O' or '-OO' command line flag. > The optimizer works in the way you describe above (which > it will not if you use a custom variable). Thanks, I didn't know that __debug__ was optimized like this. But that was really just a specific example of the general case. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Optimizing constants in loops
The peephole optimizer now takes things like if 0: do_stuff() and optimizes them away, and optimizes away the conditional in "if 1:". What if I had a function like this? def func(debug=False): for index in xrange(100): if debug: print index do_stuff(index) Could the "if debug" be optimized away on function invocation if debug is immutable and never reassigned in the function? When performance really matters in some inner loop, I usually move the conditional outside like this: def func(debug=False): if debug: for index in xrange(100): print index do_stuff(index) else: for index in xrange(100): do_stuff(index) It would be nice if this sort of thing could be done automatically, either by the interpreter or a function decorator. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: load data infile problem
[EMAIL PROTECTED] wrote: > does any one know why when I execute this mysql statement with python > api > > LOAD DATA INFILE 'data.txt' INTO TABLE merchandise; > > I get this error and how can I fix it > > #1045 - Access denied for user: '[EMAIL PROTECTED]' (Using password: YES) This has nothing to do with Python. It is obvious from the error that the user "papermen" doesn't have the privileges to load data into that table. Ask your database administrator to give you the appropriate privileges. Followups set. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyrex problem with cdef'd attribute
[EMAIL PROTECTED] wrote: > I'll play around a bit > more and if I continue to confuse myself will subscribe to the pyrex mailing > list (or at least use the somewhat clunky gmane.org interface). I find that using a newsreader for gmane stuff is far more convenient. I use Thunderbird to access various infrequently-used mailing lists via NNTP and Gmane. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: *Naming Conventions*
Neil Cerutti wrote: > I find i and j preferable to overly generic terms like "item." Well, I probably wouldn't use "item" in a real example, unless it were for a truly generic function designed to act on all sequences. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: *Naming Conventions*
Wildemar Wildenburger wrote: > [EMAIL PROTECTED] wrote: >> On Jun 4, 12:20 am, Ninereeds <[EMAIL PROTECTED]> wrote: >> >>> First, for small loops with loop variables whose meaning is obvious >>> from context, the most readable name is usually something like 'i' or >>> 'j'. >>> >> >> 'i' and 'j' are the canonical names for for loops indices in languages >> that don't support proper iteration over a sequence. Using them for >> the iteration variable of a Python for loop (which is really a >> 'foreach' loop) would be at best confusing. >> >> > > While that is true, I guess it is commonplace to use i, j, k and n > (maybe others) in constructs like > > for i in range(len(data)): >do_stuff(data[i]) > > Or should the good python hacker do that differently? Hope not ;). Well, yes, I would do: for item in data: do_stuff(item) or, if using enumerate: for item_index, item in enumerate(data): do_stuff(item_index, item) I agree with Bruno that i and j should be used only for indices, but I'm usually less terse than that. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyrex: problem with blanks in string
Hans Terlouw wrote: > When trying to wrap C code using Pyrex, I encountered a strange problem > with a piece of pure Python code. I tried to isolate the problem. The > following code causes Pyrex to generate C code which gcc cannot compile: It works for me. Try posting your error messages and versions of Pyrex/Python/GCC. Better yet, do this in the Pyrex mailing list rather than here. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: *Naming Conventions*
Michael Hoffman wrote: > Thorsten Kampe wrote: > >> for validanswer in validanswers: >> if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: >> MyOptions['style'] = validanswer > > I usually try to avoid using "my" because I find it obscures a better > understanding of what is really going ...on. Whoops, sorry about missing the last word of that message. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: *Naming Conventions*
Thorsten Kampe wrote: > for validanswer in validanswers: > if myAnswers.myanswer in myAnswers.validAnswers[validanswer]: > MyOptions['style'] = validanswer I usually try to avoid using "my" because I find it obscures a better understanding of what is really going -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: __getslice__ depreciation
[EMAIL PROTECTED] wrote: > On Jun 1, 7:50 pm, [EMAIL PROTECTED] wrote: >> If __getslice__ is depreciated (since version 2.0) why are neither >> __setslice__ or __delslice__ >> depreciated?http://docs.python.org/ref/sequence-methods.html > > Sorry disregard that, I should have RTFA A request to have the docs changed so that "Deprecated since release 2.0." in bold appears next to all three would not go amiss. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Good Python style?
Steven D'Aprano wrote: > It would probably be easier to read with more readable names and a few > comments: [...] > Splitting it into multiple lines is self-documenting: > > blankless_lines = filter(None, [line.strip() for line in input_lines]) > first_words = [line.split()[0] for line in blankless_words] > some_set = frozenset(first_words) Re-writing code so that it is self-documenting is almost always a better approach. Premature optimization is the root of all evil. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Inverse of id()?
Gabriel Genellina wrote: > En Sat, 19 May 2007 20:42:53 -0300, Paul McGuire <[EMAIL PROTECTED]> > escribió: > >>>>> z = id(results) >>>>> for x in globals().values(): >> ... if id(x)==z: break >> ... >> >> This gives me a variable x that is indeed another ref to the results >> variable: >>>>> x is results >> True >>>>> x.x >> 123 >> >> Now is there anything better than this search technique to get back a >> variable, given its id? > > py> class A:pass > ... > py> class B:pass > ... > py> a=A() > py> id(a) > 10781400 > py> del a > py> b=B() > py> id(b) > 10781400 > > Now if you look for id=10781400 you'll find b, which is another, > absolutely unrelated, object. That's not what I get: Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class A: pass ... >>> class B: pass ... >>> a = A() >>> id(a) 2146651820 >>> b = B() >>> id(b) 2146651948 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't embed python in C++(Mingw[3.*] compiler)
Arjun Narayanan wrote: > That AND I didn't use the american spelling Py_Initiali >>> Z <<< e(); Like many words ending in -ize/-ise, initialize is listed with what you call the "American" spelling in the Oxford English Dictionary. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: questions about programming styles
[EMAIL PROTECTED] wrote: > (1) > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) >def cal_attr(self, args): >#do some calculations >self.attr = calculated_value > and then if the vlue of attribute is needed, >self.cal_attr(args) >some_var = self.attr > or I can define cal_attr() as follows: > (B) >def cal_attr(self, args): >#do some calculations >return calculated_value > and then, if the value of attribute is needed, >self.attr = self.cal_attr(args) >some_var = self.attr In many cases (I would really have to see the context to be sure) would prefer something like: def get_attr(self, args): # calculations here return calculated_value Don't have a self.attr, just return the results of get_attr(). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing Arrays in this way
John Machin wrote: > On May 3, 10:21 am, Michael Hoffman <[EMAIL PROTECTED]> wrote: >> Tobiah wrote: >> >>> >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) >>> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >> That's not an array, it's a list. See the array module for arrays >> (fixed-length, unlike variable-length lists). > > You must have your very own definitions of "fixed-length" and > "unlike". Sorry, too much time spent with numarray arrays which are documented to have immutable size. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Slicing Arrays in this way
Tobiah wrote: > > >>> elegant_solution([1,2,3,4,5,6,7,8,9,10]) > [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] That's not an array, it's a list. See the array module for arrays (fixed-length, unlike variable-length lists). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: open("output/mainwindow.h",'w') doesn't create a folder for me
[EMAIL PROTECTED] wrote: > Hello > I have done python for some time now. I'm forgetting things. > > This is the faulty line : outfile = open("output/mainwindow.h",'w') > > I thought it would have created the folder ouput and the file > mainwindow.h for me but it's throwing an error No, you have to create the folder first. Try os.makedirs() -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: While we're talking about annoyances
Steven D'Aprano wrote: > On Wed, 02 May 2007 06:10:54 +, Tim Roberts wrote: >> I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate) >> because of that. > > That's what the key= argument does. cmp= is slow because the comparison > function is called for EVERY comparison. The key= function is only called > once per element. Right. Using sort(key=keyfunc) is supposed to be faster than decorate-sort-undecorate. And I think it is clearer too. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I parse a string to a tuple??
Steven D'Aprano wrote: > On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote: >> "text1 \n text2 \n text3 \n text4" --> (text1, text2, text3, text4) > > the_string = "text1 \n text2 \n text3 \n text4" > tuple(the_string.split('\n')) > > If you don't need a tuple, and a list will do: > > the_string.split('\n') or the_string.splitlines() > If you want to get rid of the white space after each chunk of text: > > [s.strip() for s in the_string.split('\n')] -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: While we're talking about annoyances
Alex Martelli wrote: > Michael Hoffman <[EMAIL PROTECTED]> wrote: > >> Alex Martelli wrote: >>> Arnaud Delobelle <[EMAIL PROTECTED]> wrote: >>>... >>>>>>> decorated.sort() >>>... >>>>> def index(sequence): >>>>> return sorted(range(len(sequence)), key=sequence.__getitem__) >>>... >>>> But really these two versions of rank are slower than the original one >>>> (as sorting a list is O(nlogn) whereas filling a table with >>>> precomputed values is O(n) ). >>> Wrong, because the original one also had a sort step, of course, so it >>> was also, inevitably, O(N log N) -- I've quoted the .sort step above. >> Well, counting the index() function that is called in both cases, the >> original rank() had one sort, but my version has two sorts. > > That doesn't affet the big-O behavior -- O(N log N) holds whether you > have one sort, or three, or twentyseven. I've taught programming classes before, and I would have had to fail anybody who misunderstood speed badly enough to claim that something repeating an O(N log N) algorithm 27 times was no faster than doing it once. ;-) As Arnaud points out, asymptotic behavior is not the same as speed. His original statement that the more recently proposed definitions of rank() are slower than the OP's may be correct. And if it's not, it's not because they're all O(N log N). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: While we're talking about annoyances
Alex Martelli wrote: > Arnaud Delobelle <[EMAIL PROTECTED]> wrote: >... >>>>> decorated.sort() >... >>> def index(sequence): >>> return sorted(range(len(sequence)), key=sequence.__getitem__) >... >> But really these two versions of rank are slower than the original one >> (as sorting a list is O(nlogn) whereas filling a table with >> precomputed values is O(n) ). > > Wrong, because the original one also had a sort step, of course, so it > was also, inevitably, O(N log N) -- I've quoted the .sort step above. Well, counting the index() function that is called in both cases, the original rank() had one sort, but my version has two sorts. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: While we're talking about annoyances
GHUM wrote: > Steven, > >> def index(sequence): >> decorated = zip(sequence, xrange(len(sequence))) >> decorated.sort() >> return [idx for (value, idx) in decorated] > > would'nt that be equivalent code? > > def index(sequence): > return [c for _,c in sorted((b,a) for a, b in > enumerate(sequence))] Or even these: def index(sequence): return sorted(range(len(sequence)), key=sequence.__getitem__) def rank(sequence): return sorted(range(len(sequence)), key=index(sequence).__getitem__) Hint: if you find yourself using a decorate-sort-undecorate pattern, sorted(key=func) or sequence.sort(key=func) might be a better idea. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Numbers and truth values
Szabolcs wrote: > Why is 1 == True and 2 == True (even though 1 != 2), Not what I get. Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> 2 == True False -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: getting rid of EOL character ?
John Machin wrote: > On 27/04/2007 11:19 PM, Michael Hoffman wrote: >> stef wrote: >>> hello, >>> >>> In the previous language I used, >>> when reading a line by readline, the EOL character was removed. > > Very interesting; how did you distinguish between EOF and an empty line? > Did you need to call an isEOF() method before each read? > >>> >>> Now I'm reading a text-file with CR+LF at the end of each line, >>>Datafile = open(filename,'r')line = Datafile.readline() >>> >>> now this gives an extra empty line >>>print line >>> >>> and what I expect that should be correct, remove CR+LF, >>> gives me one character too much removed >>>print line[,-2] > > Stef, that would give you a syntax error. I presume that you meant to > type line[:-2] > >>> >>> while this gives what I need ??? >>>print line[,-1] >>> >>> Is it correct that the 2 characters CR+LF are converted to 1 character ? > > In text mode (the default), whatever is the line ending on your platform > is converted to a single "newline" '\n' which is the same as LF. > > Using line[:-1] is NOT recommended, as the last line in your file may > not be terminated, and in that case you would lose the last data character. > >>> Is there a more automatic way to remove the EOL from the string ? >> >> line = line.rstrip("\r\n") should take care of it. If you leave out >> the parameter, it will strip out all whitespace at the end of the >> line, which is what I do in most cases. > > If you want *exactly* what is in the line, use line.rstrip('\n') -- this > will remove only the trailing newline (if it exists). > > If you want to strip all trailing whitespace, use line.rstrip() as > Michael suggested. > > Michael, note carefully that line.rstrip('\r\n') removes instances of > '\r' OR '\n' -- the arg is a set of characters to be removed, not a > suffix to be removed. In Stef's situation, it "works" only by accident. > Using that would not always give you the correct answer -- e.g. if your > (Windows) file had a line ending in CR CR LF [I've seen stranger]. I knew that about line.rstrip, but didn't consider the possibility of \r\r\n, while still wanting the first \r. Yuck. Honestly, I almost always use line.rstrip()--it is seldom that I care about closing whitespace. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: My newbie annoyances so far
John Nagle wrote: > (P.S. PEP 3117 is a joke, right?) Note date of creation. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: regex question
proctor wrote: > On Apr 27, 1:33 am, Paul McGuire <[EMAIL PROTECTED]> wrote: >> On Apr 27, 1:33 am, proctor <[EMAIL PROTECTED]> wrote: >>> rx_test = re.compile('/x([^x])*x/') >>> s = '/xabcx/' >>> if rx_test.findall(s): >>> print rx_test.findall(s) >>> >>> i expect the output to be ['abc'] however it gives me only the last >>> single character in the group: ['c'] > >> As Josiah already pointed out, the * needs to be inside the grouping >> parens. > so my question remains, why doesn't the star quantifier seem to grab > all the data. Because you didn't use it *inside* the group, as has been said twice. Let's take a simpler example: >>> import re >>> text = "xabc" >>> re_test1 = re.compile("x([^x])*") >>> re_test2 = re.compile("x([^x]*)") >>> re_test1.match(text).groups() ('c',) >>> re_test2.match(text).groups() ('abc',) There are three places that match ([^x]) in text. But each time you find one you overwrite the previous example. > isn't findall() intended to return all matches? It returns all matches of the WHOLE pattern, /x([^x])*x/. Since you used a grouping parenthesis in there, it only returns one group from each pattern. Back to my example: >>> re_test1.findall("xabcxaaaxabc") ['c', 'a', 'c'] Here it finds multiple matches, but only because the x occurs multiple times as well. In your example there is only one match. > i would expect either 'abc' or 'a', 'b', 'c' or at least just > 'a' (because that would be the first match). You are essentially doing this: group1 = "a" group1 = "b" group1 = "c" After those three statements, you wouldn't expect group1 to be "abc" or "a". You'd expect it to be "c". -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: getting rid of EOL character ?
stef wrote: > hello, > > In the previous language I used, > when reading a line by readline, the EOL character was removed. > > Now I'm reading a text-file with CR+LF at the end of each line, >Datafile = open(filename,'r')line = Datafile.readline() > > now this gives an extra empty line >print line > > and what I expect that should be correct, remove CR+LF, > gives me one character too much removed >print line[,-2] > > while this gives what I need ??? >print line[,-1] > > Is it correct that the 2 characters CR+LF are converted to 1 character ? > Is there a more automatic way to remove the EOL from the string ? line = line.rstrip("\r\n") should take care of it. If you leave out the parameter, it will strip out all whitespace at the end of the line, which is what I do in most cases. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt
Gregory Bloom wrote: > I'm running Python 2.5 under Windows. If I fire up IDLE and enter: > >>>> import webbrowser >>>> url = 'http://www.python.org' >>>> webbrowser.open_new(url) > > it works like a champ, opening the page in Firefox. Same thing goes > from a Windows cmd shell: it works as advertised. > > But if I open a cygwin bash shell and try the same thing from a python > prompt, I get: > >>>> import webbrowser >>>> url = 'http://www.python.org' >>>> webbrowser.open_new(url) > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\webbrowser.py", line 60, in open_new > return open(url, 1) > File "C:\Python25\lib\webbrowser.py", line 55, in open > if browser.open(url, new, autoraise): > File "C:\Python25\lib\webbrowser.py", line 185, in open > p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) > File "C:\Python25\lib\subprocess.py", line 551, in __init__ > raise ValueError("close_fds is not supported on Windows " > ValueError: close_fds is not supported on Windows platforms > > What's up with that? It's not a Cygwin issue, really. This occurs when one of ["firefox", "firebird", "seamonkey", "mozilla", "netscape", "opera"] is in your path. Your Cygwin environment must be set so one of these is in your path when it isn't normally. You should also submit a bug. > And, more to the point, how can I use webbrowser from scripts launched under > cygwin? If you're using native Windows Python as you seem to be, try webbrowser.get("windows-default").open_new(url) If you want to use Cygwin Python instead, I submitted a patch more than 1.5 years ago to allow it, but it hasn't been reviewed: http://python.org/sf/1244861 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: List objects are un-hashable
Andy wrote: > Hi, I'm trying to search and print any no# of Python keywords present > in a text file (say - foo.txt), and getting the above error. Sad for > not being able to decipher such a simple problem (I can come up with > other ways - but want to fix this one FFS). It helps a lot of if you post the traceback with your problem. The line it occurred on is crucial for debugging. But I will use my psychic debugger which tells me that the error is here: > if keyword.iskeyword(tempwords): tempwords is a list. You need to iterate over the contents of the list and run keyword.iskeyword() for each one. Here's an example for Python 2.5. I've cleaned up some extra lines of code that didn't have any eventual effects in your current implementation from __future__ import with_statement import keyword INFILENAME = "foo.txt" with open(INFILENAME) as infile: for line in infile: words = line.split() for word in words: if keyword.iskeyword(word): print word This will print multiple lines per input line. If you wanted one line per input line then try: with open(INFILENAME) as infile: for line in infile: words = line.split() print " ".join(word for word in words if keyword.iskeyword(word)) -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Generalized range
Michael Hoffman wrote: > How about something like this: > > index = 0 > while res < maximum: > yield minimum + (step * index) > index += 1 Well it really would have to be something LIKE that since I never defined res. Let's try that again: index = 0 res = minimum while res < maximum: yield res res = minimum + (step * index) index += 1 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Generalized range
[EMAIL PROTECTED] wrote: > Thanks - you have covered a fair bit of gorund here - I will modify > myRange taking your suggestions into account. The one suggestion that > I'm going to have to think through is repeatedly incrementing res. > > I deliberately did not use this as repeated addition can cause > rounding errors to accumulate, making the loop run a little longer or > shorter than necessary. I thought I would be far less likely to run > into rounding issues with a multiplicative construct - hence my use of > epsilon, and my question about an appropriate value for it You are right about rounding issues--with a sufficiently small step, the way I have done it, it could become an infinite loop. But you can still do it with multiplication, without using an epsilon constant. How about something like this: index = 0 while res < maximum: yield minimum + (step * index) index += 1 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Dedicated CPU core for Python?
Louise Hoffman wrote: > I was wondering, if Python in the foerseeable future will allocate one > CPU core just for the interpreter, so heavy Python operations does > slow down the OS? When running scripts, or loading modules, Python does not really behave as an interpreter. Instead it compiles the human-readable code to a bytecode which it then runs on a virtual machine. -- Michael Hoffman (no relation) -- http://mail.python.org/mailman/listinfo/python-list
Re: My python annoyances so far
[EMAIL PROTECTED] wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? They don't have to be. They just are. That's like asking why do some functions start with the letters a-m, and others with n-z. Why can't they all begin with a-m? The answer would be that it would make the language harder to use to cram concepts that should more naturally start with n-z into spellings that start with a-m. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Generalized range
[EMAIL PROTECTED] wrote: > I need to create ranges that can start and end with real numbers. > Searching this newsgroup brought me to a function that I then modified > as follows: > > def myRange(iMin, iMax=None, iStep=1): > """Extends range to real numbers. Wherever possible, use Python's > range . >In other cases, make the behavior follow the spirit of Python's > range """ >epsilon = 1.e-8 > > if iMax == None and iStep == 1: > return range(int(iMin)) > > elif type(iMin).__name__.lower() in ('int', 'long') and \ > type(iMax).__name__.lower() in ('int', 'long') and \ > type(iStep).__name__.lower() in ('int', 'long') and iStep != > 0: > return range( iMin, iMax, iStep) > > elif iMin <= iMax and iStep > 0: > return [ iMin+i*iStep for i in range( int(math.ceil((iMax - > iMin - epsilon)/iStep)) )] > > elif iMin >= iMax and iStep < 0: > return [ iMin+i*iStep for i in range(-int(math.ceil((iMin - > iMax + epsilon)/iStep)) )] > > else: > raise ValueError, 'Cannot construct a range with steps of size > ' + str(iStep) + ' between ' + str(iMin) + ' and ' + str(iMax) > > > The one part of my implementation that has me a bit queasy (i.e. > works in my current application, but I can see it misbehaving > elsewhere) is the addition/subtraction of a fixed epsilon to ensure > that my rounding goes the right way. A clean implementation would > modify epsilon based on the achievable level of precision given the > particular values of iMax, iMin and iStep. I suspect this requires a > detailed understanding of the implementation of floating point > arithmetic, and would appreciate hearing any thoughts you might have > on gilding this lily. In addition to the comments of Stargaming, most of which I agree with, I think you would be far better dropping the epsilon business and doing something like: # requires that minimum <= maximum; swap values if necessary res = minimum while res < maximum: yield res res += step -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: My python annoyances so far
7stud wrote: > [EMAIL PROTECTED] wrote: >> Annoyances: >> > > Every language has annoyances. Python is no exception. Post away. > Anyone that is offended can go drink a Guinness. I find Guinness annoying. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
Neil Cerutti wrote: >> On Apr 23, 1:38 pm, Antoon Pardon <[EMAIL PROTECTED]> wrote: >>> The following is part of the explanation on slices in the >>> tutorial: >>> >>> The best way to remember how slices work is >> ... >>> +---+---+---+---+---+ >>> | H | e | l | p | A | >>> +---+---+---+---+---+ >>> 0 1 2 3 4 5 >>> -5 -4 -3 -2 -1 > > I object only to the word "best". I don't like the above model > because it divorces the indexes that appear in subscripts from > those that appear in slices. I 't find it complicated to think: > a[2:4] is the contiguous slice of elements starting at the gap > between element 1 and 2, and ending at the gap between element 3 > and 4. I've always found thinking of [2:4] as a half-open range > much easier. > > I suppose the above model could avoid this notational problem if > you say that a[k] means the one element slice a[k:k+1] > (technically true for strings, but false for lists), rather than > ever thinking of item indexes as pointing directly at an item. > > So I vote that the word "best" be removed. I agree. It would be better to say that, "One way to help you understand how slices work is to think of..." -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Access to raw command line?
Pieter Edelman wrote: > Hi, > > I'm currently writing a command-line program in Python, which takes > commands in the form of: > ./myprog.py [OPTIONS] ARGS > So pretty standard stuff. In my case, ARGS is a list of image files. > > One of the possible options is to specify a file holding information > about the photos. You'd specify it with (in this particular case) the - > t switch, and you can specify multiple files by repeating this switch: > ./myprog.py -t info1.gpx -t info2.gpx -t info3.gpx *jpg > > Now, one of the users has quite a lot of info files, and asked me if > it's possible to use a wildcard in specifying these, so he would just > have to do: > ./myprog.py -t *.gpx *.jpg > > This seems like a sensible option at first sight, but it's difficult > to implement because the wildcard is expanded by the shell, so > sys.argv gets a list containing "-t", all .gpx files and all .jpg > files. With this list, there's no way to tell which files belong to > the "-t" switch and which are arguments (other than using the > extension). > > One possible way to work around this is to get the raw command line > and do the shell expansions ourselves from within Python. Ignoring the > question of whether it is worth the trouble, does anybody know if it > is possible to obtain the raw (unexpanded) command line? > Alternatively, does anybody have suggestion of how to do this in a > clean way? One option would be to accept a directory argument to -t and to recursively inlcude all the gpx files in that directory. Another option would be to use some sort of optional separator, like ./myprog.py -t *.gpx -j *.jpg where everything between -t and -j would be considered a -t option. I think this breaks the usual UNIX options paradigm though. Of course UNIX itself does that--dd is an example of a program that doesn't follow it. Another option would be to accept a list of gpx files from a file: find . -name '*.gpx' > gpxlist.txt ./myprog.py --gpx-file=gpxlist.txt *.jpg Or to accept more than one file per argument: ./myprog.py -t "$(echo *.gpx)" *.jpg Personally I would prefer the file list approach. If you start expanding wildcards yourself, then if someone stupidly wants to use a wildcard character, they'll have to triple-escape things, and it'll just be messy. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding conventions for class names
Kay Schluehr wrote: > What happens when an enthusiast re-implements a stdlib module e.g. > decimal s.t. it becomes a builtin module? Will the stdlib module serve > as a wrapper to conform the current API or will the builtin module > conform to the current interface. Well, the best example is probably the transition from sets.Set to __builtin__.set. The API changed but only slightly. So far sets.Set retains the old implementation--it is not a wrapper for __builtin__.set. Future modules may be implemented differently. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting question
belinda thom wrote: > Hi, > > I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am not > sure if I can get the operator.itemgetter to do what I want for my > particular need. I'm also not sure why creating my own cmp for pulling > tuple parts out and passing it to a list sort doesn't just work. > > I'm sure this stuff is old hat to many on this list. Suggestions happily > accepted. > > Suppose I've got a list like: > > l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))] > > and I want to sort on the 2nd item in the 2nd tuple. sorted(l, key=lambda item: item[1][1]) > I've tried things like: > > cmp = lambda x,y : x[1][1] > y[1][1] > l.sort(cmp=cmp) Don't call your comparison function cmp. There's already a built-in, which is what you should be using: l.sort(cmp=lambda x, y: cmp(x[1][1], y[1][1])) cmp returns -1, 0, or 1, but your function only returned 0 or 1. But using key is better, because the key function has to be run only once per item. The comparison has to be run for every comparison--which there can be many of if you are sorting a long list. > but l isn't then changed in place. > > Using > > sorted(l,operator.itemgetter(1)) > > behaves as I'd expect, but I really want something like > operator.itemgetter(1).itemgetter(1), which (understandably) causes a > syntax error. Unless you are doing something really weird, it should cause an AttributeError, not a SyntaxError. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: bitwise shift?
Jean-Paul Calderone wrote: > On Wed, 25 Apr 2007 22:54:12 +0200, desktop <[EMAIL PROTECTED]> wrote: >> I have found a code example with this loop. >> >> for k in range(10, 25): >> n = 1 << k; >> >> >> I have never read Python before but is it correct that 1 get multiplied >> with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift >> left by k" which is the same as multiplying with k. > > No. > > http://python.org/doc/ref/shifting.html "A right shift by n bits is defined as division by pow(2,n). A left shift by n bits is defined as multiplication with pow(2,n); for plain integers there is no overflow check so in that case the operation drops bits and flips the sign if the result is not less than pow(2,31) in absolute value. Negative shift counts raise a ValueError exception." >>> sys.maxint << 2 8589934588L >>> 2**31 2147483648L It looks like the limitation has been removed. This might be a nice optimization as well, as 1 << n is faster than 2**n for large enough n. Might be rare, although I have a friend who has been doing this all day. In Python. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: bitwise shift?
desktop wrote: > I have found a code example with this loop. > > for k in range(10, 25): > n = 1 << k; > > > I have never read Python before but is it correct that 1 get multiplied > with the numbers 10,11,12,12,...,25 No. > assuming that 1 << k means "1 shift left by k" Yes. > which is the same as multiplying with k. No. Try starting the Python interpreter and entering 1 << 10. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding conventions for class names
Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, Kay Schluehr > wrote: > >> set, int, float, list, object,... >> >> Don't see any of the basic types following the capitalized word >> convention for classes covered by PEP 08. This does not hold only for >> __builtins__ in the strict sense but also for types defined in builtin >> modules like datetime. > > Most built-ins are easy to explain: They were functions long before it > was possible to use them as base classes and stayed lowercase for > backwards compatibility. Don't know about `set` and `object`. I guess > it's foolish consistency!? Well originally there was sets.Set (uppercase). It became set when it went to being a built-in. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Coding conventions for class names
Kay Schluehr wrote: > My question is: does anyone actually follow guidelines here Yes. > and if yes > which ones and are they resonable ( e.g. stable with regard to > refactoring etc. )? All of them that I know of. What does it mean to be "stable with regard to refactoring etc."? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system('tar -c * | tar -C dst') ##Any other suggestions...
[EMAIL PROTECTED] wrote: > I'm getting the following error: > > tar: You must specify one of the `-Acdtrux' options > Try `tar --help' or `tar --usage' for more information. > tar: -: Cannot write: Broken pipe > tar: Error is not recoverable: exiting now > > Any suggestions on a different approach or fix? What do you want to do? What do you think that is supposed to do? What does this have to do with Python? -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Catching a specific IO error
Steven Howe wrote: > Steve Holden wrote: >> Thomas Krüger wrote: >> >>> Tina I schrieb: >>> >>>> Now, this works but of course it catches every IOError, and I can not >>>> figure out how to restrict it to only catch the "[Errno 2]"? >>>> >>> There's an example that uses the error number: >>> http://docs.python.org/tut/node10.html#SECTION001030 >>> >>> >> So what you'll need to do is catch all IOError exceptions, then test >> to see if you've got (one of) the particular one(s) you are interested >> in. If not then you can re-raise the same error with a bare "raise" >> statement, and any containing exception handlers will be triggered. If >> there are none then you will see the familiar traceback termination >> message. >> >> regards >> Steve >> > you could also use some pre-testing of the filename os.path.isfile, > os.path.isdir, os.path.split are good > functions to test file/directory existence. Also to verify that you have > permission to manipulate a file, os.access is a good function. The try first approach is better for at least two reasons: 1) It saves you an extra stat() on the disk, which can be really important for some filesystems I use :) 2) It is atomic. If os.path.isfile() returns True but the file is deleted before you open it, you are still going to have to handle the exception. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: defining user exceptions
CSUIDL PROGRAMMEr wrote: > I am trying to write a user defined exception that will catch for > failed dependencies when a rpm is installed > > try: > rpm -ivh xxx.rpm --force; > except RPMError: >print RPM failed dependency > > > Can some one tell me how to define this RPMError. I looked at python > docs but they were not useful. http://docs.python.org/tut/node10.html#SECTION001050 -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
[Michael Hoffman] >> Personally, I do not think of slices in the way this tutorial suggests, >> but I think taking it out without replacement would not help. If you >> want to add a more accurate replacement, I think that would be better >> received than just saying that the section should be removed. Even more >> so if you provide it in the form of a patch. [Antoon Pardon] > Well people could suggest that instead of just removing the section > there should be a replacement and then we could discuss how such > a replacement should look like. Isn't that what I have done? And William Hamilton suggested an alternative way of looking at it which you could have just incorporated into your patch. > I just started with what I see as > a problem and one possible fix. Now I guess that if people would > agree that there is problem but don't agree with my fix they would > comment on my fix. Instead most reactions seem to suggest there is > not really a problem. Now I am not going to waste my time writing > a patch for something that doesn't seem to be considered a problem. Really only one person has argued that the docs do not need to be changed. The other two people seemed to think you were asking for help rather than discussing how to revise the docs. Understandable, since that's why most people come to this group in my estimation. Your time is your own and it is good to spend your efforts on what you think will be most fruitful. But if you are going to let the opposition of one person stop you from doing anything, you will not accomplish very much. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorial creates confusion about slices
Antoon Pardon wrote: >> Submit a patch if you want it changed. I'm sure your valuable >> insights will greatly improve the quality of the python documentation. > > Fat chance, if they reason like you. I don't think that Michael Bentley is the documents maintainer. Are you trying to pick a fight with him or improve the docs? Personally, I do not think of slices in the way this tutorial suggests, but I think taking it out without replacement would not help. If you want to add a more accurate replacement, I think that would be better received than just saying that the section should be removed. Even more so if you provide it in the form of a patch. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: adjust
[EMAIL PROTECTED] wrote: > How do i right adjust my output using python. http://docs.python.org/lib/typesseq-strings.html > minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 1, 6, 3, 17, 1, Something like: >>> def write_sequence(label, sequence): ... expanded_text = ",".join("%4d" % item for item in sequence) ... print "%s=%s" % (label, expanded_text) ... >>> write_sequence("minlength", minlength) minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1 Completing with a trailing ",", using the entire sequence instead of a subset, and dealing with your hex constants are left as an exercise to the reader. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Would You Write Python Articles or Screencasts for Money?
Jeff Rush wrote: > There is discussion by the Python Software Foundation of offering cash > bounties or perhaps periodic awards to the "best of" for magazine articles, > video/screencast clips and such. > > If YOU would be swayed to get involved in producing content in exchange for > cash, please speak up on the advocacy mailing list and also drop an email to > Steve Holden <[EMAIL PROTECTED]>, current champion of this idea and looking > for encouragement. The very next thread I see after this one in this newsgroup is "work at home from internet.and earn 4000USD every month." So you'll have to do better than that for an adequate incentive. ;) Seems like a good idea, although I don't have any constructive suggestions at this point. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: I/O Error
[EMAIL PROTECTED] wrote: > file_input = raw_input("Enter The ODX File Path:") > odx_file_output = raw_input("Enter the output file path : ") > log_file_output = raw_input("Enter the path for LogFile : ") > > saveout = sys.stdout > try: > f_open=open(odx_file_output, 'w') > except: > print "cant open file" > sys.exit() > sys.stdout = f_open > > try: > input_xml = open(file_input,'r') > except: > print "The File Cannot Be Opened" > sys.exit() > > if input_xml.read(5)!=' print "Invalid File" > input_xml.close() > sys.exit() > else: > xmldoc = minidom.parse(input_xml) > input_xml.close() > > if xmldoc.childNodes[1].getAttribute("DtdVers") == u'1.1.4' or > xmldoc.childNodes[1].getAttribute("DtdVers")== u'1.1.5': > pass > else: > print "Invalid Version" > sys.exit() > > After this some more code follows,but i have > pasted only the i/o part . In the future, it is best to be able to produce a short and complete test case. Doing so may help you find your error, without assistance. > Traceback (most recent call last): > File "C:\Projects\ODX Import\code_ini\odxparse.py", line 250, in > > file_input = raw_input("Enter The ODX File Path:") > ValueError: I/O operation on closed file Well, you set sys.stdout to f_open, and you probably closed it without setting it back. Can't tell because you didn't include the whole script (and you shouldn't do that either--make a test case). Here are some general comments: 1) Redirecting sys.stdout does not seem advisable in this case, and seems to be causing some confusion. It's far better to make a new file handle for your output. You can print to it using: print >>filehandle, "message" 2) Interactively asking for filenames like this will cause irritation for yourself, and possibly your users if they ever want to automate things. My personal preference would be to accept the arguments on the command line. If your users don't know how to use a command line, then you should really be getting the filenames through some sort of GUI instead of raw_input(). 3) I try to name my file-related variables consistently so I know where they are. Naming the file name variable and the file handle variable something completely different is confusing. 4) If you have some abnormal exit condition, you should exit with sys.exit(1) or really any number besides 0. Exiting with sys.exit() or sys.exit(0) means everything is fine. 5) If an exception occurs that will result in the end of the program, there's no point in catching it just to print a less descriptive error message and quit. It makes your code harder to understand with all the exception catching, and it makes it harder to debug because you lose crucial details of where the exception occurred and what its calling stack was. 6) Further, I'm not sure how much sense it makes to double-check that the file begins with "http://mail.python.org/mailman/listinfo/python-list
Re: python style guide inconsistencies
Darren Dale wrote: > Bjoern Schliessmann wrote: > >> Darren Dale wrote: >> >>> I was just searching for some guidance on how to name packages and >>> modules, and discovered some inconsistencies on the >>> www.python.org. http://www.python.org/doc/essays/styleguide.html >>> says "Module names can be either MixedCase or lowercase." That >>> page also refers to PEP 8 at >>> http://www.python.org/dev/peps/pep-0008/, which says "Modules >>> should have short, all-lowercase names. ... Python packages should >>> also have short, all-lowercase names ...". >>> >>> Which is most up to date? >> The priority is, IMHO, clear. The old style guide essay says, at the >> beginning: >> >> | This style guide has been converted to several PEPs (Python >> | Enhancement Proposals): PEP 8 for the main text, PEP 257 for >> | docstring conventions. See the PEP index. >> >> So PEP 8 is the most recent. > > Then perhaps http://www.python.org/doc/essays/styleguide.html should either > be updated to either agree with or simply link to PEPs 8 and 257. What is > the point of keeping old, out-of-date essays up on python.org? That > beginning comment does not indicate that the essay is any different from > the PEPs. http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
Steven W. Orr wrote: > On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: > > =>Chris Lasher wrote: > =>> Should a Python module not intended to be executed have shebang/ > =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a > =>> shebang in every .py file but I recently heard someone argue that > =>> shebangs were only appropriate for Python code intended to be > =>> executable (i.e., run from the command line). > => > =>Personally I include it in all of them, as part of boilerplate in a > =>template. > > I'd recommend againt it. The shebang doesn't do you any good unless it's > also in the presence of a file that has its executable bit set. It doesn't do any bad either, so I don't understand why you would recommend against it. And the bash function I use to create new files from the template also does chmod a+x. Not to mention that I have emacs set such that things with shebangs at the top are automatically chmod a+x, so in my programming environment, having a shebang on files I create and being executable are one and the same. > For example, let's leave python out for a second: I have a shell script. > And I also have lots of files which are not intended to be executed which > are also shell scripts, but which are sucked in by the shell "." or > "source" command (which is *somewhat* analogous to python's import). Lots > of these shell "library" scripts can't execute as standalone. The same > thing is possible with pything scripts. > > Of course, anything that has > if __name__ == "__main__": > in it should always have a shebang and be executable. That's in my template as well. :) I try to write all my modules so that they can easily be adapted to run as scripts, and all my scripts so that they can easily be adapted to use as modules. This has served me well many, many times. I see no reasons to create an artificial barrier to doing this by leaving the shebang out of files where it has no ill effect. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Two syntax questions (newbie)
Diez B. Roggisch wrote: >> This is already better. Is it possible to define function composition >> as an operator and have something like ([EMAIL PROTECTED]@sorted)(items) >> or (list*reversed*sorted)(items) ? > > Not on functions, but on classes/instances. So something like this might > work for you (untested): > > class FunctionComposer(object): > def __init__(self, f=None): > if f is None: >f = lambda x: x > self._f = f > > def __call__(self, *args, **kwargs): > return self._f(*args, **kwargs) > > def __mul__(self, other): > def combined(*args, **kwargs): > return other(self._f(*args, **kwargs)) > return FunctionComposer(combined) > > fc = FunctionComposer > > Then you can write > > (fc() * list * reversed * sorted)(items) A clever little hack, but please don't do this. Anyone else who will read your code will thank you. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang or Hashbang for modules or not?
Chris Lasher wrote: > Should a Python module not intended to be executed have shebang/ > hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a > shebang in every .py file but I recently heard someone argue that > shebangs were only appropriate for Python code intended to be > executable (i.e., run from the command line). Personally I include it in all of them, as part of boilerplate in a template. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestion: str.itersplit()
Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, Dustan wrote: > >> From my searches here, there is no equivalent to java's >> StringTokenizer in python, which seems like a real shame to me. >> >> However, str.split() works just as well, except for the fact that it >> creates it all at one go. I suggest an itersplit be introduced for >> lazy evaluation, if you don't want to take up recourses, and it could >> be used just like java's StringTokenizer. >> >> Comments? > > Does it really make such a difference? It would if you were dealing with enormous blocks of text at once, say from a database. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: setDaemon problem.
Richard Brodie wrote: > "Michael Hoffman" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >>> Neither is particularly intuitive; it just depends whether you are more >>> familiar with the Posix terminology or the Java one. I personally prefer >>> detached but there is little chance of a name change now. >> Why not? That's what Python 3.0 is for. > > I think you need a better reason than: "it's mildly confusing to people, if > they don't read the manual" for an API change; but that's just my opinion. One of the goals of Python 3.0 is to clean up previous warts in the language, and there will be a number of API changes. And one of the good things about Python in general is that things frequently can be understood without reading a manual. I think anything to aid this should be encouraged. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: setDaemon problem.
Richard Brodie wrote: > "Ramashish Baranwal" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> I was also wondering about "daemonizing" a thread, but I interpreted >> that it would daemonize the process which it didn't. I think setDaemon >> should be renamed to setDetached or something similar. > > Neither is particularly intuitive; it just depends whether you are more > familiar with the Posix terminology or the Java one. I personally prefer > detached but there is little chance of a name change now. Why not? That's what Python 3.0 is for. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with os.rename
loial wrote: > How can I get more info what the cause of the OSError exception is? For starters, post the traceback here. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Spawn/Exec with asterisk in argument
[EMAIL PROTECTED] wrote: > Thanks for the reply Michael. No problem. > I used ls as a simple example, but I'm > using this with scp to transfer files and need shell expansion. It > makes sense since the shell isn't spawning the process, but it's been > a while since I've worked with ipc. I usually don't think of starting new processes as being IPC. I've only ever seen it used to refer to communicating between processes after they have started. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python un-plugging the Interpreter
S.Mohideen wrote: > I was thinking about the feasbility of adjusting Python as a > compiled language. In addition to the Python compilers listed by Steve, there is also Pyrex, which translates a Python-like language to C, and allows one to interact with it from Python with very little difficulty. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Using the Python interpreter
[EMAIL PROTECTED] wrote: > Instead of starting IDLE as I normally do, I started the Python > interpreter and tried to run a program. I got a Python prompt (>>>), > and then tried unsuccessfully to run a Python script named Script1.py > that runs perfectly well in IDLE. Here's what I did: > >>>> Script1.py > Traceback (most recent call last): > File "", line 1, in ? > NameError: name Script1 is not defined > >>>> python Script1.py You need to do this from a Windows command line, not from Python. C:\Python25>python Script1.py Hello, world! -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Spawn/Exec with asterisk in argument
[EMAIL PROTECTED] wrote: > The spawn* and exec* functions appear to escape asterisks, I'm > guessing all shell characters too, before the spawn/exec'ed process > sees them. No. It is the shell that ordinarily processes these characters and gives them a special meaning. On most systems, ls does not give any special meaning to asterisk. > Is there a way around this? If you want to process asterisk the way the shell does, you can pass things through the shell. os.system is one way of doing that. Probably better is: subprocess.check_call("ls -l *", shell=True) Another way is using the glob module (and optionally os.path.expanduser() for tilde expansion and os.path.expandvars() for variable expansion, other things that are normally taken care of by the shell). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: comparison with None
[EMAIL PROTECTED] wrote: > On Apr 18, 3:19 pm, Steven Howe <[EMAIL PROTECTED]> wrote: >> I've read and found that 'None' comparisons is not always a good idea. >> Better to: >> from types import NoneType >> >> x = None >> if type( x ) == NoneType: >> # true >> < code > >> else: >> # false; do something else. >> < more code > >> >> Steven Howe > > Is that any better than this? > > if x is None: > # do something > else: > # do something else To the contrary, it's not as good. "if x is None" is much clearer, and probably faster. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: converting currency using locals
Grzegorz Ślusarek wrote: > Hi all. I have situation that I have value that holds price and I must show > this price using national specification(e.g. thousands_sep). Any idea how > this can be done under python 2.4.4? I saw that function format from module > locals can format value with national specification, but this could be done > only in python 2.5. Any solution for 2.4? I think you mean locale, for anyone else who was puzzled by this. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: X root Operator help
[Michael Hoffman] >> For x root use y**(1/x) [Steve Holden] > >>> 3.14159 ** (1/3) > 1.0 > >>> > > So the cube root of pi is 1? I don't think so. > > For generic roots use y ** (1.0 / x) Yes, good point. :) -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: X root Operator help
[Michael Hoffman] >> In floating point arithmetic, the naive way of calculating both roots >> always using the formula (-b +/- sqrt(b**2 - 4*a*c))/2*a will give you >> inaccurate results sometimes. See >> <http://www.cse.uiuc.edu/eot/modules/floating_point/quadratic_formula/>. [lucidparadox] > Thanks. As of right now I'm just trying to familiarize myself with > the syntax of Python. Actually I should have thought of y**(1/x). math.sqrt(y) might be faster or even more accurate (depending on platform) than y**0.5. > I'm currently a freshman in college so the alternative formula hasn't > been introduced to me yet. It probably won't be unless you take a class in numerical analysis. Many a person has been burned by not thinking about these sorts of things until it is too late (myself included). -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list