[issue1154351] add get_current_dir_name() to os module

2018-10-29 Thread Michael Hoffman


Michael Hoffman  added the comment:

`getcwd()` in many ways serves the purpose that a `lget_current_dir_name()` 
might.

--

___
Python tracker 
<https://bugs.python.org/issue1154351>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1154351] add get_current_dir_name() to os module

2018-10-29 Thread Michael Hoffman


Michael Hoffman  added the comment:

> * For some libc functions we add options to existing functions rather of 
> duplicating the number of names in the os module. For example the dir_fd  
> option instead of *at() functions. Wouldn't be better to add a buulean 
> parameter (with platform-depending default) to getcwd()?

I agree, adding an option to `getcwd()` would probably be a better approach and 
reduce some of the other potential confusion.

--

___
Python tracker 
<https://bugs.python.org/issue1154351>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1154351] add get_current_dir_name() to os module

2018-10-28 Thread Michael Hoffman


Michael Hoffman  added the comment:

glibc `getcwd()` and `get_current_dir_name()` are not the same. glibc
`get_current_dir_name()` does, in fact, check the `PWD` environment
variable.

https://www.gnu.org/software/libc/manual/html_node/Working-Directory.html

The get_current_dir_name function is basically equivalent to
getcwd (NULL, 0), except the value of the PWD environment variable is first
examined, and if it does in fact correspond to the current directory, that
value is returned. This is a subtle difference which is visible if the path
described by the value in PWD is using one or more symbolic links, in which
case the value returned by getcwd would resolve the symbolic links and
therefore yield a different result.

On Sun, Oct 28, 2018 at 5:27 PM Braden Groom report-at-bugs.python.org
|Python/Example Allow| <16snny1crx82...@sneakemail.com> wrote:

>
> Braden Groom  added the comment:
>
> Victor, FWIW I don't need this functionality and your suggestion on the PR
> seems reasonable to me. I only picked up this issue as a way to become
> familiar with contributing to the project. I'm okay with closing both the
> PR and the ticket.
>
> --
> nosy: +bradengroom
>
> ___
> Python tracker 
> <https://bugs.python.org/issue1154351>
> ___
>

--

___
Python tracker 
<https://bugs.python.org/issue1154351>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue2571] cmd.py always uses raw_input, even when another stdin is specified

2010-11-13 Thread Michael Hoffman

Changes by Michael Hoffman qq9jsuv...@snkmail.com:


--
nosy: +hoffman

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue2571
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10396] stdin argument to pdb.Pdb doesn't work unless you also set Pdb.use_rawinput = False

2010-11-13 Thread Michael Hoffman

Michael Hoffman qq9jsuv...@snkmail.com added the comment:

As always, it seems a bit more complicated than I originally expected. Since 
it's too late for a Python 2.x feature addition, I'll wait until I upgrade to 
3.x to work on that.

You are correct, technically this is not a docs bug but I think the clarity of 
the docs would be greatly improved if you would add the text from the cmd 
module docs to the pdb docs:

If you want a given stdin to be used, make sure to set the instance’s 
use_rawinput attribute to False, otherwise stdin will be ignored.

I hope you will agree that this is unexpected behavior that doesn't really fit 
into the zen of Python.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10396
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10396] stdin argument to pdb.Pdb doesn't work unless you also set Pdb.use_rawinput = False

2010-11-12 Thread Michael Hoffman

New submission from Michael Hoffman qq9jsuv...@snkmail.com:

If you create a Pdb instance with an stdin argument, the default behavior is 
for commands to be retrieved using raw_input(), which uses sys.stdin instead, 
thereby causing the stdin argument to be without effect.

You can work around this by setting the use_rawinput attribute of the instance 
to False, but this should be done whenever an stdin argument is given to the 
constructor.

--
components: Library (Lib)
files: testcase.py
messages: 121050
nosy: hoffman
priority: normal
severity: normal
status: open
title: stdin argument to pdb.Pdb doesn't work unless you also set 
Pdb.use_rawinput = False
type: behavior
versions: Python 2.7
Added file: http://bugs.python.org/file19580/testcase.py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10396
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue10396] stdin argument to pdb.Pdb doesn't work unless you also set Pdb.use_rawinput = False

2010-11-12 Thread Michael Hoffman

Changes by Michael Hoffman qq9jsuv...@snkmail.com:


Added file: http://bugs.python.org/file19581/expected_behavior.py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue10396
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Updating path.py

2010-07-27 Thread Michael Hoffman

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

2010-07-26 Thread Michael Hoffman
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

2009-04-24 Thread Michael Hoffman

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.1C:\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 module
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 bound method VertexDomain.__del__ of 
vertexdom...@a9c7350 allocs

=[] 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

2009-04-24 Thread Michael Hoffman

Sebastian Wiesner wrote:

Michael Hoffman – Donnerstag, 23. April 2009 19:52


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


Presentation software for Python code

2009-04-23 Thread Michael Hoffman
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: Presentation software for Python code

2009-04-23 Thread Michael Hoffman

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


Finding the full path of an executable

2009-01-16 Thread Michael Hoffman
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: Finding the full path of an executable

2009-01-16 Thread Michael Hoffman

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 stdin, line 1, in module
  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 cwd/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


[issue2155] optparse.OptionGroup with_statement context handling

2008-12-11 Thread Michael Hoffman

Michael Hoffman michaelfilter.57405...@bloglines.com added the comment:

Is there anything I can do to get this feature request considered
earlier? I can generate a real patch, but I figured that wouldn't
necessary for something so simple. This has the advantage that it can
probably be cut/pasted into any version of the code.

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue2155
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4245] threading documentation: reorder sections

2008-10-31 Thread Michael Hoffman

New submission from Michael Hoffman [EMAIL PROTECTED]:

It is somewhat confusing that the meat of the threading module, the
Thread object itself, is so far down in the documentation. It should be
the first  section after the module functions and objects.

http://docs.python.org/library/threading.html

--
assignee: georg.brandl
components: Documentation
messages: 75422
nosy: georg.brandl, hoffman
severity: normal
status: open
title: threading documentation: reorder sections

___
Python tracker [EMAIL PROTECTED]
http://bugs.python.org/issue4245
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Using NamedTemporaryDir instead of multiple NamedTemporaryFiles

2008-09-09 Thread Michael Hoffman
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: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles

2008-09-09 Thread Michael Hoffman
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


Re: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles

2008-09-09 Thread Michael Hoffman

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


[issue1180] Option to ignore or substitute ~/.pydistutils.cfg

2008-03-19 Thread Michael Hoffman

Michael Hoffman [EMAIL PROTECTED] added the comment:

That is up to you of course, and being able to ignore is better than
nothing. But creating a new account is not really an option for
everyone. On the system I would like to use this feature the most, I am
not a system administrator, so I cannot create new user accounts. I
maintain a directory for production use of people in my workgroup. I
also maintain my own for testing and development.

Thanks for your work on this patch. At least being able to use
--no-user-cfg will be very helpful.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1180
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue2155] optparse.OptionGroup with_statement context handling

2008-02-21 Thread Michael Hoffman

New submission from Michael Hoffman:

Adding these four lines to optparse.OptionGroup makes using option
groups vastly easier:

def __enter__(self):
return self

def __exit__(self, *exc_info):
self.parser.add_option_group(self)

You can then do things like:

with OptionGroup(parser, Group name) as group:
group.add_option(...)

--
components: Library (Lib)
messages: 62625
nosy: hoffman
severity: normal
status: open
title: optparse.OptionGroup with_statement context handling
type: feature request

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue2155
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue2130] [feature-request] Please add bool data type to optparse module

2008-02-21 Thread Michael Hoffman

Michael Hoffman added the comment:

As gpolo points out, this facility already exists. This RFE should be
closed.

--
nosy: +hoffman

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue2130
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1186] optparse documentation: -- being collapsed to - in HTML

2007-09-24 Thread Michael Hoffman

Michael Hoffman added the comment:

At the very least could you change the -- to be the verbatim class
that shows up properly beneath? There has to be another solution that
would result in the docs at least being correct even if we can't get
LaTeX to do exactly what we want.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1186
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1186] optparse documentation: -- being collapsed to - in HTML

2007-09-24 Thread Michael Hoffman

Michael Hoffman added the comment:

Also, see http://bugs.python.org/issue798006 which shows how to fix a
similar problem elsewhere in the docs.

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1186
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1186] optparse documentation: -- being collapsed to - in HTML

2007-09-21 Thread Michael Hoffman

New submission from Michael Hoffman:

See http://docs.python.org/lib/optparse-callback-example-6.html where
it says 'either - or - can be option arguments'. One of these should
be --. The same error occurs several times on the same page.

Not a problem in the Optik docs at
http://optik.sourceforge.net/doc/1.5/callbacks.html.

--
components: Documentation
messages: 56074
nosy: gward, hoffman
severity: normal
status: open
title: optparse documentation: -- being collapsed to - in HTML
versions: Python 2.5

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1186
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1180] Option to ignore ~/.pydistutils.cfg

2007-09-19 Thread Michael Hoffman

Changes by Michael Hoffman:


--
components: Distutils
severity: normal
status: open
title: Option to ignore ~/.pydistutils.cfg
type: rfe
versions: Python 2.6

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1180
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1180] Option to ignore or substitute ~/.pydistutils.cfg

2007-09-19 Thread Michael Hoffman

Changes by Michael Hoffman:


--
title: Option to ignore ~/.pydistutils.cfg - Option to ignore or substitute 
~/.pydistutils.cfg

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1180
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1643369] function breakpoints in pdb

2007-09-19 Thread Michael Hoffman

Michael Hoffman added the comment:

Agree with isandler. This is not a bug.

--
nosy: +hoffman

_
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1643369
_
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue1180] Option to ignore ~/.pydistutils.cfg

2007-09-19 Thread Michael Hoffman

New submission from Michael Hoffman:

It would be useful if setup.py instances had an option to ignore
~/.pydistutils.cfg or substitute it with another file. For example, this
would be highly useful to people who maintain a system site-packages
directory along with one in their own home directory.

--
nosy: +hoffman

__
Tracker [EMAIL PROTECTED]
http://bugs.python.org/issue1180
__
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: pylint style convention

2007-07-23 Thread Michael Hoffman
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

2007-07-13 Thread Michael Hoffman
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?

2007-07-10 Thread Michael Hoffman
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)

2007-07-04 Thread Michael Hoffman
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 changing keywords name

2007-07-02 Thread Michael Hoffman
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: Python compilation ??

2007-07-02 Thread Michael Hoffman
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: Excuse me!!

2007-06-28 Thread Michael Hoffman
[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

2007-06-25 Thread Michael Hoffman
[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: Accessing variable from a function within a function

2007-06-24 Thread Michael Hoffman
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: dealing with emf/wmf files

2007-06-24 Thread Michael Hoffman
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: PEP 3107 and stronger typing (note: probably a newbie question)

2007-06-23 Thread Michael Hoffman
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: Python changing keywords name

2007-06-23 Thread Michael Hoffman
[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: Indenting in Emacs

2007-06-22 Thread Michael Hoffman
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: What was that web interaction library called again?

2007-06-22 Thread Michael Hoffman
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

2007-06-21 Thread Michael Hoffman
[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: Can python access windows clipboard

2007-06-21 Thread Michael Hoffman
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: DFW Pythoneers Meeting THIS Saturday

2007-06-20 Thread Michael Hoffman
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: DFW Pythoneers Meeting THIS Saturday

2007-06-20 Thread Michael Hoffman
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: PEP 3107 and stronger typing (note: probably a newbie question)

2007-06-20 Thread Michael Hoffman
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: How can I capture all exceptions especially when os.system() fail? Thanks

2007-06-14 Thread Michael Hoffman
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: os.path.normpath bug?

2007-06-14 Thread Michael Hoffman
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: Questions about mathematical and statistical functionality in Python

2007-06-14 Thread Michael Hoffman
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


Optimizing constants in loops

2007-06-13 Thread Michael Hoffman
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: Optimizing constants in loops

2007-06-13 Thread Michael Hoffman
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


Re: Pyrex problem with cdef'd attribute

2007-06-10 Thread Michael Hoffman
[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: load data infile problem

2007-06-10 Thread Michael Hoffman
[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: *Naming Conventions*

2007-06-05 Thread Michael Hoffman
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: Pyrex: problem with blanks in string

2007-06-04 Thread Michael Hoffman
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*

2007-06-04 Thread Michael Hoffman
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: *Naming Conventions*

2007-06-03 Thread Michael Hoffman
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: *Naming Conventions*

2007-06-03 Thread Michael Hoffman
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: __getslice__ depreciation

2007-06-02 Thread Michael Hoffman
[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?

2007-05-31 Thread Michael Hoffman
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: questions about programming styles

2007-05-20 Thread Michael Hoffman
[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: Can't embed python in C++(Mingw[3.*] compiler)

2007-05-20 Thread Michael Hoffman
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: Inverse of id()?

2007-05-20 Thread Michael Hoffman
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: Slicing Arrays in this way

2007-05-03 Thread Michael Hoffman
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: While we're talking about annoyances

2007-05-02 Thread Michael Hoffman
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: open(output/mainwindow.h,'w') doesn't create a folder for me

2007-05-02 Thread Michael Hoffman
[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: Slicing Arrays in this way

2007-05-02 Thread Michael Hoffman
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: While we're talking about annoyances

2007-04-30 Thread Michael Hoffman
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: How do I parse a string to a tuple??

2007-04-30 Thread Michael Hoffman
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

2007-04-29 Thread Michael Hoffman
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: While we're talking about annoyances

2007-04-29 Thread Michael Hoffman
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: getting rid of EOL character ?

2007-04-28 Thread Michael Hoffman
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: Numbers and truth values

2007-04-28 Thread Michael Hoffman
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: List objects are un-hashable

2007-04-27 Thread Michael Hoffman
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: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt

2007-04-27 Thread Michael Hoffman
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 stdin, line 1, in module
   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: getting rid of EOL character ?

2007-04-27 Thread Michael Hoffman
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: regex question

2007-04-27 Thread Michael Hoffman
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: My newbie annoyances so far

2007-04-27 Thread Michael Hoffman
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: Coding conventions for class names

2007-04-26 Thread Michael Hoffman
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: Access to raw command line?

2007-04-26 Thread Michael Hoffman
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: Tutorial creates confusion about slices

2007-04-26 Thread Michael Hoffman
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: My python annoyances so far

2007-04-26 Thread Michael Hoffman
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: Generalized range

2007-04-26 Thread Michael Hoffman
[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

2007-04-26 Thread Michael Hoffman
[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: Dedicated CPU core for Python?

2007-04-26 Thread Michael Hoffman
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: Generalized range

2007-04-26 Thread Michael Hoffman
[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: Generalized range

2007-04-26 Thread Michael Hoffman
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: Coding conventions for class names

2007-04-25 Thread Michael Hoffman
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: Coding conventions for class names

2007-04-25 Thread Michael Hoffman
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: bitwise shift?

2007-04-25 Thread Michael Hoffman
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: bitwise shift?

2007-04-25 Thread Michael Hoffman
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: sorting question

2007-04-25 Thread Michael Hoffman
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: I/O Error

2007-04-24 Thread Michael Hoffman
[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)!='?xml':
 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
 module
 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 ?xml. minidom.parse will check that just fine. 
And it will catch all sorts of other errors as well, and you can't do 
them all yourself at this point.

Here's how I would rewrite it using Python 2.5:

from __future__ import with_statement

import sys
from xml.dom import minidom

ACCEPTABLE_DTD_VERSIONS = [u'1.1.4', u'1.1.5']

class DTDVersionError(StandardError):
 pass

def io(infilename, outfilename, logfilename):
 with open(outfilename, w) as outfile:
 with open(infilename) as infile:
 xmldoc = minidom.parse(input_xml)

 dtd_version = xmldoc.childNodes[1].getAttribute(DtdVers)
 if dtd_version not in ACCEPTABLE_DTD_VERSIONS:
 raise DTDVersionError(infilename)

def main(args):
 return io(*args)

if __name__ == __main__:
 sys.exit(main(sys.argv[1:]))

As far as the interface goes, you can run this from the commandline as 
example.py INFILE OUTFILE LOGFILE. Or from IDLE as io(INFILE, 
OUTFILE, LOGFILE). That way you can re-run it many times without 
having to retype three file names each time, yuck. If you want to add a 
GUI for other users to select files, you can call it from main() if 
there are no command-line arguments, keeping the bulk of your logic in 
io() separate from the interface.

Let us know if you have any questions about what I have done here.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-24 Thread Michael Hoffman
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: adjust

2007-04-24 Thread Michael Hoffman
[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: Tutorial creates confusion about slices

2007-04-24 Thread Michael Hoffman
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: Tutorial creates confusion about slices

2007-04-24 Thread Michael Hoffman
[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


  1   2   3   4   5   >