Re: PEP: possibility of inline using of a symbol instead of "import"

2011-01-06 Thread Mike Kent
On Jan 6, 11:02 am, Duncan Booth  wrote:

> Your complaint seems to be that:
>
>    r1 = myFunc1(...)
>
> is unclear when you don't know where myfunc1 originates, so why don't
> you write:
>
>    r1 = MyModule1.myFunc1(...)
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

My interpretation of his proposal is a bit different.  I thought he
meant that '@MyModule.myFunc' (yes, using '@' here is bad, but for
conversation sake...) would cause MyModule to be imported if this was
the first time '@MyModule' was encountered in the current module.
Sort of an implied 'import MyModule', which would eliminate the need
to actually use the explicit import.

My reaction to his proposal is 'Meh.'  Explicit is better than
implicit.  Python is not Perl.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what happens to Popen()'s parent-side file descriptors?

2010-10-13 Thread Mike Kent
You might want to check out the Python 2.7 'pipes' standard library
module: http://docs.python.org/library/pipes.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ordering tests in a testsuite

2010-10-08 Thread Mike Kent
But sometimes you just wanna do it the way you wanna do it.  If you
name your tests like 'test_01_yadda' and test_02_whatever', then they
will be run in the order you want, as given by the numbers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to python - parse data into Google Charts

2010-09-03 Thread Mike Kent
On Sep 3, 1:52 pm, alistair  wrote:
> I'm new to python and my programming years are a ways behind me, so I
> was looking for some help in parsing a file into a chart using the
> Google Charts API.
>

Try this:
http://pygooglechart.slowchop.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does MySQLdb rollback on control-C? Maybe not.

2010-09-03 Thread Mike Kent
On Sep 3, 12:22 am, John Nagle  wrote:
>     I would expect MySQLdb to rollback on a control-C, but it doesn't
> seem to have done so.  

> Something is broken.

I wouldn't expect it to, I'd expect to roll back on an exception, or
commit if not.  Perhaps this will help you.  I use it in production
code.

##
# This is a transaction context manager.  It will ensure that the code
in
# the context block will be executed inside a transaction.  If any
exception
# occurs, the transaction will be rolled back, and the exception
reraised.
# If no exception occurs, the transaction will be committed.
# db is a database connection object.

from contextlib import contextmanager

@contextmanager
def transaction(db):
db.begin()
try:
yield None
except:
db.rollback()
raise
else:
db.commit()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python database

2010-09-03 Thread Mike Kent
On Sep 3, 2:36 am, shai garcia  wrote:
> can you pls help me to make a database program in python?

It's better if you do your homework yourself.  You learn more that
way.  Now, if you have a specific question about some detail of your
assignment, and can show us that you've really tried to do the work
yourself, that's another matter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python -Vs- Ruby: A regexp match to the death!

2010-08-09 Thread Mike Kent
On Aug 8, 8:43 pm, rantingrick  wrote:
> Hello folks,
>
> You all know i been forced to use Ruby and i am not happy about that.

***Blablabla cut long rant***

Xah, this is really you, isn't it.  Come on, confess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie problem with str.replace

2010-08-04 Thread Mike Kent
On Aug 4, 9:10 am, BobAalsma  wrote:
> I'm working on a set of scripts and I can't get a replace to work in
> the script - please help.

>                         bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN)

I'm not sure what you are intending to do here, but string.replace
does not do its replacement in-place.  It returns a copy of the
original string, with the replacement done in the copy.  You are not
assigning the string returned by string.replace to anything,
therefore, it is immediately thrown away.

Secondly, and this is just a guess, but since you are doing the
string.replace inside of an os.walk loop, you appear to be trying to
do a filename change.  I hope you realize that this will in no way
change the name of the file *on disk*; it will only change it in
memory.
-- 
http://mail.python.org/mailman/listinfo/python-list


SEC apparently about to mandate Python for a particular financial use

2010-04-16 Thread Mike Kent
http://jrvarma.wordpress.com/2010/04/16/the-sec-and-the-python/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reactive programming in Python ?

2010-04-16 Thread Mike Kent
On Apr 16, 11:18 am, pca  wrote:
> Dear all,
>
> Could “reactive programming” still increase the productivity and joy
> of Python programming?  I’d like to hear your thoughts on the idea
> that object-oriented “programming by formula”, as in a spreadsheet,
> would simplify our work, because we would not have to worry about the
> sequence of program execution anymore.
>
> In fact, I have seeded an open-source project, Yoopf, that enables
> programming by formula within Python, with the goal of dramatically
> accelerating the development of the model view in the MVC model.
> Declarative-style programming has accelerated the development of the
> presentation layer (with HTML, CSS) and the Database layer (with SQL),
> so why not take advantage of it for the Business Logic layer too?
>
> You can find more information on this project atwww.yoopf.org.  Your
> comments are more than welcome!
>
> Best regards,
> P. Carbonnelle

The requested URL /www.yoopf.org was not found on this server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Relocatable python install

2010-04-14 Thread Mike Kent
On Apr 14, 4:50 pm, Michel  wrote:
> Hi,
>
> I would like to create a binary package of python that we will ship
> with our product. I need to be able to install the package anywhere in
> the file system.
>
> The interpreter seems to be ok with that, but a few other tools that
> are installed in the PREFIX/bin directory (pydoc, py2to3, python-
> config,...) contain hardcoded path to the interpreter.
>
> Is there a way around that? Or an configure option to prevent these
> files to be installed?
>
> Regards,
>
> Michel.

The standard way to handle this seems to be to write a post-install
script that edits the interpreter path in those scripts to point it to
the actual install path.  I had to handle the same thing, and others
have done it as well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (a==b) ? 'Yes' : 'No'

2010-03-30 Thread Mike Kent
On Mar 30, 11:40 am, gentlestone  wrote:
> Hi, how can I write the popular C/JAVA syntax in Python?
>
> Java example:
>     return (a==b) ? 'Yes' : 'No'
>
> My first idea is:
>     return ('No','Yes')[bool(a==b)]
>
> Is there a more elegant/common python expression for this?

return ('Yes' if a == b else 'No')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-05 Thread Mike Kent
On Mar 4, 8:04 pm, Robert Kern  wrote:

> No, the try: finally: is not implicit. See the source for
> contextlib.GeneratorContextManager. When __exit__() gets an exception from the
> with: block, it will push it into the generator using its .throw() method. 
> This
> raises the exception inside the generator at the yield statement.

Wow, I just learned something new.  My understanding of context
managers was that the __exit__ method was guaranteed to be executed
regardless of how the context was left.  I have often written my own
context manager classes, giving them the __enter__ and __exit__
methods.  I had mistakenly assumed that the @contextmanager decorator
turned a generator function into a context manager with the same
behavior as the equivalent context manager class.  Now I learn that,
no, in order to have the 'undo' code executed in the presence of an
exception, you must write your own try/finally block in the generator
function.

This raises the question in my mind: What's the use case for using
@contextmanager rather than wrapping your code in a context manager
class that defines __enter__ and __exit__, if you still have to
manager your own try/finally block?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-04 Thread Mike Kent
On Mar 3, 12:00 pm, Robert Kern  wrote:
> On 2010-03-03 09:39 AM, Mike Kent wrote:
>
> > What's the compelling use case for this vs. a simple try/finally?
>
> >     original_dir = os.getcwd()
> >     try:
> >         os.chdir(somewhere)
> >         # Do other stuff
> >     finally:
> >         os.chdir(original_dir)
> >         # Do other cleanup
>
> A custom-written context manager looks nicer and can be more readable.
>
> from contextlib import contextmanager
> import os
>
> @contextmanager
> def pushd(path):
>      original_dir = os.getcwd()
>      os.chdir(path)
>      try:
>          yield
>      finally:
>          os.chdir(original_dir)
>
> with pushd(somewhere):
>      ...

Robert, I like the way you think.  That's a perfect name for that
context manager!  However, you can clear one thing up for me... isn't
the inner try/finally superfluous?  My understanding was that there
was an implicit try/finally already done which will insure that
everything after the yield statement was always executed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-04 Thread Mike Kent
On Mar 4, 12:30 pm, Robert Kern  wrote:

> He's ignorant of the use cases of the with: statement, true.

 Ouch!  Ignorant of the use cases of the with statement, am I?
Odd, I use it all the time. 

> Given only your
> example of the with: statement, it is hard to fault him for thinking that try:
> finally: wouldn't suffice.

 Damn me with faint praise, will you? 

I'm kinda amazed at the drama my innocent request for the use case
elicited.  From what I've gotten so far from this thread, for the
actual example Mr. Steinbach used, the only disadvantage to my counter-
example using try/finally is that the chdir in the finally part will
always be executed, even if the chdir in the try part did not
succeed.  I concede that, and was aware of it when I wrote it.  For
the simple example given, I did not consider it compelling.  A more
complex example, that would have required multiple, nested try/finally
blocks, would show the advantages of Mr Steinbach's recipe more
clearly.

However, I fail to understand his response that I must have meant try/
else instead, as this, as Mr. Kern pointed out, is invalid syntax.
Perhaps Mr. Steinbach would like to give an example?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-04 Thread Mike Kent
On Mar 3, 10:56 am, "Alf P. Steinbach"  wrote:
> * Mike Kent:
>
> > What's the compelling use case for this vs. a simple try/finally?
>
> if you thought about it you would mean a simple "try/else". "finally" is 
> always
> executed. which is incorrect for cleanup
>
> by the way, that's one advantage:
>
> a "with Cleanup" is difficult to get wrong, while a "try" is easy to get 
> wrong,
> as you did here
>
>    ---
>
> another general advantage is as for the 'with' statement generally
>
> >    original_dir = os.getcwd()
> >    try:
> >        os.chdir(somewhere)
> >        # Do other stuff
>
> also, the "do other stuff" can be a lot of code
>
> and also, with more than one action the try-else introduces a lot of nesting
>
> >    finally:
> >        os.chdir(original_dir)
> >        # Do other cleanup
>
> cheers & hth.,
>
> - alf

Wrong?  In what way is my example wrong?  It cleanly makes sure that
the current working directory is the same after the try/finally as it
was before it.  Suboptimal, perhaps, in that the chdir in the finally
part is always executed, even if the chdir in the try part failed to
change the working directory.

That is a clear advantage to the code you presented, in that you have
the ability to register an 'undo' function only if the 'do' code
succeeded.  Your code also avoids a problem with many nested try/
finally blocks.  But for the simple chdir example you gave, I think
'wrong' isn't the word you were looking for regarding the try/finally
example I gave.

Anyway, I'll keep your code in mind the next time I want to avoid a
bunch of nested try/finally blocks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A "scopeguard" for Python

2010-03-03 Thread Mike Kent
What's the compelling use case for this vs. a simple try/finally?

   original_dir = os.getcwd()
   try:
   os.chdir(somewhere)
   # Do other stuff
   finally:
   os.chdir(original_dir)
   # Do other cleanup
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a maximum size to a Python program?

2009-04-27 Thread Mike Kent
On Apr 27, 1:49 am, John Machin  wrote:

> > I am
> > having a look at eval and exec
>
> WRONG WAY
> GO BACK

+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Can I use setup.py to ship and install only .pyc files?

2009-04-16 Thread Mike Kent
I'd like to ship only the .pyc files for a module.  I was hoping the
standard distutils setup.py could handle this, but so far, I've not
figured out how.

After a bit of work, I discovered that if I create a MANIFEST.in file,
and put 'include mymodule/*.pyc' and 'exclude mymodule/*.py' in it,
then running 'python setup.py sdist' would generate a tar.gz file for
me that contained the setup.py file and all my .pyc files, just like I
wanted.  However, when I then extract that tar.gz file, and try to run
'python setup.py install', it complains about the missing .py files,
and creates the 'mymodule' directory in the site-packages directory
but without putting any of the .pyc files in it.

At this point, I'm stumped.  I was hoping someone out there had gone
down this same route and could tell what I'm doing wrong.  Can
setup.py even handle this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: FTP libs for Python?

2009-02-20 Thread Mike Kent
I use Fabric (http://www.nongnu.org/fab/) as my Python-based
deployment tool, but it uses ssh/scp, not sftp.
--
http://mail.python.org/mailman/listinfo/python-list


Re: function scope

2009-02-02 Thread Mike Kent
On Feb 2, 6:40 pm, Baris Demir  wrote:

> def simpleCut(d=dict()):
>        temp=d
>        for i in temp.keys():
>            if    (temp[i] == ...) :
>               temp[i]=new_value
> return temp

You have been bitten by the shared default parameter noobie trap:
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
--
http://mail.python.org/mailman/listinfo/python-list


Problem building Python 2.5.2 curses module on HP/UX 11.11

2009-01-06 Thread Mike Kent
I'm having a problem building the Python 2.5.2 curses module on HP/UX
11.11 using gcc 3.3.6, and was hoping someone had a solution.
Compiling Modules/_cursesmodule.c is giving several warnings, but no
errors.  The relevant compile/link output is below.  The key output
line is:

*** WARNING: renaming "_curses" since importing it failed: dynamic
module does n
ot define init function (init_curses)

So, given that there are no actual errors during the compile, and the
warnings are probably benign, does anyone know what would cause the
resulting compiled module to NOT have the init function?

Full build output:

building '_curses' extension
gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-
prototype
s -I. -I/usr/local/src/xyzpython/Python-2.5.2/./Include -I/usr/local/
xyz/python/
include -I. -IInclude -I./Include -I/usr/local/include -I/usr/local/
src/xyzpytho
n/Python-2.5.2/Include -I/usr/local/src/xyzpython/Python-2.5.2 -c /usr/
local/src
/xyzpython/Python-2.5.2/Modules/_cursesmodule.c -o build/temp.hp-ux-B.
11.11-9000
-800-2.5/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.o
In file included from /usr/local/src/xyzpython/Python-2.5.2/Include/
Python.h:8,
 from /usr/local/src/xyzpython/Python-2.5.2/Modules/
_cursesmodul
e.c:102:
pyconfig.h:942:1: warning: "_POSIX_C_SOURCE" redefined
:6:1: warning: this is the location of the previous
definition
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: In
function `PyCu
rsesWindow_AddStr':
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:449:
warning: impl
icit declaration of function `getattrs'
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: In
function `PyCu
rses_getsyx':
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:1712:
warning: imp
licit declaration of function `getsyx'
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: In
function `PyCu
rses_setsyx':
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:2369:
warning: imp
licit declaration of function `setsyx'
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: In
function `PyCu
rses_UnCtrl':
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:2499:
warning: imp
licit declaration of function `unctrl'
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:2499:
warning: pas
sing arg 1 of `PyString_FromString' makes pointer from integer without
a cast
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: In
function `PyCu
rses_getsyx':
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:1708:
warning: `x'
 might be used uninitialized in this function
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:1708:
warning: `y'
 might be used uninitialized in this function
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c: At top
level:
/usr/local/src/xyzpython/Python-2.5.2/Modules/_cursesmodule.c:2266:
warning: `up
date_lines_cols' defined but not used
ld -b build/temp.hp-ux-B.11.11-9000-800-2.5/usr/local/src/xyzpython/
Python-2.5.2
/Modules/_cursesmodule.o -L/usr/local/xyz/python/lib -L/usr/local/lib -
lncurses
-o build/lib.hp-ux-B.11.11-9000-800-2.5/_curses.sl
*** WARNING: renaming "_curses" since importing it failed: dynamic
module does n
ot define init function (init_curses)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Possible read()/readline() bug?

2008-10-23 Thread Mike Kent
To followup on this:

Terry: Yes, I did in fact miss the 'buffer' parameter to open.
Setting the buffer parameter to 0 did in fact fix the test code that I
gave above, but oddly, did not fix my actual production code; it
continues to get the data as first read, rather than what is currently
on the disk.  I'm still investigating why.

Carl: I tried the above test code, without 'buffer=0' in the open, but
with a flush added before reads in the appropriate places. The flush
made no difference; readline continued to return the old data rather
than what was actually on the disk.  So, flush isn't the answer.  I
suppose that means that, when the document states it flushes the
buffer, it's referring to the output buffer, not the input buffer.
--
http://mail.python.org/mailman/listinfo/python-list


Possible read()/readline() bug?

2008-10-22 Thread Mike Kent
Before I file a bug report against Python 2.5.2, I want to run this by
the newsgroup to make sure I'm not being stupid.

I have a text file of fixed-length records I want to read in random
order.  That file is being changed in real-time by another process,
and my process want to see the changes to the file.  What I'm seeing
is that, once I've opened the file and read a record, all subsequent
seeks to and reads of that same record will return the same data as
the first read of the record, so long as I don't close and reopen the
file.  This indicates some sort of buffering and caching is going on.

Consider the following:

$ echo "hi" >foo.txt  # Create my test file
$ python2.5  # Run Python
Python 2.5.2 (r252:60911, Sep 22 2008, 16:13:07)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('foo.txt')  # Open my test file
>>> f.seek(0)# Seek to the beginning of the file
>>> f.readline() # Read the line, I get the data I expected
'hi\n'
>>> # At this point, in another shell I execute 'echo "bye" >foo.txt'.  
>>> 'foo.txt' now has been changed
>>> # on the disk, and now contains 'bye\n'.
>>> f.seek(0)# Seek to the beginning of the still-open file
>>> f.readline() # Read the line, I don't get 'bye\n', I get the 
>>> original data, which is no longer there.
'hi\n'
>>> f.close() # Now I close the file...
>>> f = open('foo.txt') # ... and reopen it
>>> f.seek(0)   # Seek to the beginning of the file
>>> f.readline()# Read the line, I get the expected 'bye\n'
'bye\n'
>>>

It seems pretty clear to me that this is wrong.  If there is any
caching going on, it should clearly be discarded if I do a seek.  Note
that it's not just readline() that's returning me the wrong, cached
data, as I've also tried this with read(), and I get the same
results.  It's not acceptable that I have to close and reopen the file
before every read when I'm doing random record access.

So, is this a bug, or am I being stupid?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to delete a last character from a string

2008-08-29 Thread Mike Kent
On Aug 29, 2:28 pm, [EMAIL PROTECTED] wrote:
> Sorry : Earlier mail had a typo in Subject line which might look
> in-appropriate to my friends
>
> Hi,
>
> I've a list some of whose elements with character \.
> I want to delete this last character from the elements that have this
> character set at their end,
>
> I have written a small program, unfortunately this does not work:
>
> dirListFinal = []
> for item in dirList:
>            print item
>            if item.endswith('\\') == True:
>                item = item[0:-1]         # This one I googled and
> found to remove the last character /
>                dirListFinal.append(item)
>            else:
>                dirListFinal.append(item)
>
> item.endswith() does not seem to be working.
>
> Please help
> --
> Regrads,
> Rajat

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "hello\\"
>>> s.endswith("\\")
True
>>> s[:-1]
'hello'

I hate to say "works for me", but it works for me.  Perhaps you should
put some debugging statements in your code to see if that data you are
working on is what you are expecting.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python multimap

2008-08-27 Thread Mike Kent
On Aug 27, 9:35 am, brad <[EMAIL PROTECTED]> wrote:
> Recently had a need to us a multimap container in C++. I now need to
> write equivalent Python code. How does Python handle this?
>
> k['1'] = 'Tom'
> k['1'] = 'Bob'
> k['1'] = 'Joe'
> ...
>
> Same key, but different values. No overwrites either They all must
> be inserted into the container
>
> Thanks,
> Brad

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> k = {}
>>> k['1'] = []
>>> k['1'].append('Tom')
>>> k['1'].append('Bob')
>>> k['1'].append('Joe')
>>>
>>> k['1']
['Tom', 'Bob', 'Joe']
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to char array

2008-07-01 Thread Mike Kent
On Jul 1, 2:49 pm, "Brandon" <[EMAIL PROTECTED]> wrote:
> How do I convert a string to a char array?  I am doing this so I can edit
> the string received from an sql query so I can remove unnecessary
> characters.

Answering your specific question:

Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'hello'
>>> l = list(s)
>>> l
['h', 'e', 'l', 'l', 'o']
>>>

But more generally, you might want to read up on the string methods
available to you, such as replace():
http://docs.python.org/lib/string-methods.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Notify of change to list

2008-06-16 Thread Mike Kent
I recently wanted to do the same kind of thing.  See this tread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f27c3b7950424e1c
for details on how to do it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing list, what special methods do this?

2008-06-14 Thread Mike Kent
On Jun 13, 8:43 pm, Matimus <[EMAIL PROTECTED]> wrote:

...chop...
> So, it looks like as long as you want to subclass list, you are stuck
> implementing both __*slice__ and __*item__ methods.
>
> Matt

Thanks.  That was clear and concise, just what I needed.
--
http://mail.python.org/mailman/listinfo/python-list


Subclassing list, what special methods do this?

2008-06-13 Thread Mike Kent
For Python 2.5 and new-style classes, what special method is called
for mylist[2:4] = seq and for del mylist[2:4] (given that mylist is a
list, and seq is some sequence)?

I'm trying to subclass list, and I'm having trouble determining what
special methods I have to override in my class for the above two
operations.  From my testing, it seems to be __setslice__ for both,
but the docs say __setslice__ and brethren are deprecated.  I would
have thought that __setitem__ and __delitem__ would be what was
called, but again, my testing says otherwise.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Constructor re-initialization issue

2008-06-03 Thread Mike Kent
On Jun 3, 6:11 pm, [EMAIL PROTECTED] wrote:
> Hello all,
>
> I have come across this issue in Python and I cannot quite understand
> what is going on.
>
> class Param():
> def __init__(self, data={}, condition=False):
> if condition:
> data['class']="Advanced"
> print data
>
> In the previous example, I expect the variable data to be re-
> initialized every time I construct an object type Param. However, when
> I do the following:
>
> Param(condition=True)
> Param(condition=False)
>
> The second call still prints {'class': 'Advanced'}
>
> Shouldn't data be initialized to {} since it is the default in
> __init__? Why would the state of data be preserved between two
> independent instantiations?
>
> Any help would be greatly appreciated.
>
> M.

This is a Frequently Asked Question (FAQ):
http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects
--
http://mail.python.org/mailman/listinfo/python-list


Re: list index out of range

2008-05-13 Thread Mike Kent
On May 13, 2:39 pm, Georgy Panterov <[EMAIL PROTECTED]> wrote:
>
> def deal_hand(deck):
> HAND=[]
> for _ in range(2):
> i=random.randint(0,len(deck)) #produces a random card from the deck
  ^ Here i can be from 0 thru (the number of cards in the
deck).

> HAND.append(deck[i]) # appends the card to the players' hand list
   ^ Here you index into the deck to get a
card.  The legal indexes are 0 thru (number of cards in the deck - 1)
 What happens if i is (the number of cards
in the deck)?

> deck.remove(deck[i]) #removes the card from the deck
> return HAND
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: creating a list from a inconsistent text file

2008-05-02 Thread Mike Kent
On May 2, 9:47 am, Jetus <[EMAIL PROTECTED]> wrote:

> Hello Marc;
> Thanks for the input! I am worried about the comma in the "" data
> items, how do I tell Python to look for the "" data first, then use
> the comma separator?

Marc has already given you the correct answer.  You really should read
up on the csv module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonically extract data from a list of tuples (getopt)

2008-04-23 Thread Mike Kent
You could use http://docs.python.org/lib/module-optparse.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finally had to plonk google gorups.

2008-04-16 Thread Mike Kent
On Apr 16, 10:26 am, Mike Driscoll <[EMAIL PROTECTED]> wrote:

> Yeah, I noticed that Google Groups has really sucked this week. I'm
> using the Google Groups Killfile for Greasemonkey now and it helps a
> lot. I like Google, but my loyalty only goes to far. This is a
> complete lack of customer service.
>
> Mike

Bless you.  I just installed Greasemonkey and the Google Groups
Killfile.  Works like a charm.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Talking to a usb device (serial terminal)

2008-03-03 Thread Mike Kent

> So my question is this - what is the easiest way to interface to this
> "serial" device?
>

http://pyserial.sourceforge.net/

or perhaps

http://pyusb.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


What should I use under *nix instead of freeze?

2008-02-01 Thread Mike Kent
In a comment Guido made on a recent bug report for the 'freeze'
utility, he stated:

"I think nobody really cares about freeze any more -- it isn't
maintained."

That being the case, what is the preferred/best replacement for freeze
on a *nix platform?  I'm looking for something that, like freeze,
turns my application into a single-file executable, of the smallest
size possible, that can be executed on a machine with no Python
installation or development system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: raw_input(), STRANGE behaviour

2008-01-26 Thread Mike Kent
On Jan 26, 7:23 am, Dox33 <[EMAIL PROTECTED]> wrote:
> I ran into a very strange behaviour of raw_input().
> I hope somebody can tell me how to fix this.
===CUT===
> *** Thirst, redirect stderr to file, STRANGE behaviour..
> From the command prompt I run:
> python script.py 2> stderr_catch.txt
> This should redirect strerr to the file and stdout should stay on the
> screen.
>
> But. What happens?
> After a few 'enter' keys, on screen apears:
> 1: This is the print statement.
> 3: This is a possible solution.
>
> WHERE IS THE SECOND LINE?
> It is in the file stderr_catch.txt!!!
>
>  See the problem?
> Please Tell me? Why is the prompt produced by raw_input() printed to
> the error channel? It should be stdout, just as the print statement
> does.

I recently ran into this behaviour myself, and reported it both here
and to the python-dev mailing list.  See
http://groups.google.com/group/comp.lang.python/browse_thread/thread/1011238ac6b79292/6f8b7c47873a4a1e?lnk=gst&q=unexpected+behavior#6f8b7c47873a4a1e

It turns out that *if* you don't have GNU readline installed, Python
falls back to its own implementation of readline, which is hard-coded
to send the prompt output to stderr.  Guido agreed that this is wrong,
and a bug for it has been entered into the Python bug tracking
database.

Your workaround until this bug is fixed is to install GNU readline,
and rebuild your python installation to use it rather than the fall-
back version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reporting Python bugs (was: Can someone explain this unexpectedraw_input behavior?)

2008-01-24 Thread Mike Kent
On Jan 24, 5:13 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Ben Finney" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | Mike Kent <[EMAIL PROTECTED]> writes:
> |
> | > A bug issue has been opened in the Python Trac system for this.
> |
> | Wouldn't it be better to report it in the official Python bug tracker
> | http://bugs.python.org/>, which is Roundup, not Trac?
>
> Has been by Skip:  http://bugs.python.org/issue1927

My mistake in using the word 'Trac'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone explain this unexpected raw_input behavior?

2008-01-24 Thread Mike Kent

> If it weren't for the documentation...
>
> "If the prompt argument is present, it is written to *standard output*
> without a trailing newline."
>
> --
> mvh Björn

I have reported this issue to the python-dev mailing list, and Guido
agrees that this is a bug in Python.  It turns out that the key is
that my site does not have GNU readline installed, so Python falls
back to its own implementation of readline.  Using GNU readline,
raw_input will write its prompt to stdout.  Python's own
implementation of readline sends the output to stderr.  As Bjorn
states, the documentation for raw_input says it writes its prompt to
stdout.  A bug issue has been opened in the Python Trac system for
this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone explain this unexpected raw_input behavior?

2008-01-23 Thread Mike Kent
Gabriel, thank you for clarifying the source of this behavior.  Still,
I'm surprised it would be hard-coded into Python.  Consider an
interactive program, that asks the user several questions, and
displays paragraphs of information based on those questions.  The
paragraphs are output using print, and the questions are asked via
raw_input. You want to do some simple debugging of the program by
printing some debugging statements via 'print >>sys.stderr', and you
don't want the debug output mixed in with the normal output on the
screen, so you try to route the debugging output to a file by adding
'2>filename' to the end of the command line.

Unfortunately, you will no longer see any of the questions being
printed via raw_input.  The rest of the output will be fine, but the
questions disappear.  Your program just stops, without asking
anything... you have to guess what should be there.

I'm surprised that Python hard-codes this behavior without giving the
programmer any way to change it.  It leaves me with two options: to
either always use the logging module for debugging messages (which is
not odious at all, it's just that the code in question predates the
logging module, which is why debugging was done as it is), or change
the program so that raw_input is never used with a prompt parameter;
the prompt must always be printed separately.

  At least I now know I'm not crazy... regarding this, anyway.
-- 
http://mail.python.org/mailman/listinfo/python-list


Can someone explain this unexpected raw_input behavior?

2008-01-23 Thread Mike Kent
It's often useful for debugging to print something to stderr, and to
route the error output to a file using '2>filename' on the command
line.

However, when I try that with a python script, all prompt output from
raw_input goes to stderr.  Consider the following test program:

=== Start test.py ===
import sys

def main():
print "Hello world"
raw_input("Press ENTER")
print "Goodbye world"

if __name__ == "__main__":
main()
=== End test.py ===

If I run it with the command line 'python2.5 test.py', I get the
following output:

Hello world
Press ENTER<=== This appeared,the program paused, I press ENTER,
and the program continued
Goodbye world

However, if I run it with the command line 'python2.5 test.py 2>/dev/
null' (I'm routing stderr output to /dev/null), I instead get:

Hello world
  <=== No output appeared, the program paused, I
press ENTER, and the program continued
Goodbye world

This indicates to me that the prompt output of raw_input is being sent
to stderr.  I did check the source code for raw_input, and it appears
to be sending it to stdout as expected.

I get this behavior on multiple OS platforms, with multiple versions
of Python.  I am building python on these platforms myself, but to my
knowledge, I am not doing anything special which could account for
this behavior.

Any suggestions or pointers on how to get the expected behavior out of
raw_input?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How avoid both a newline and a space between 2 print commands?

2008-01-23 Thread Mike Kent
On Jan 23, 9:03 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> print "foo"
> print "bar"
>
> has a newline in between "foo" and "bar"
>
> print "foo",
> print "bar"
>
> has a space in between "foo" and "bar"
>
> How prevent ANYTHING from going in between "foo" and "bar" ??
>
> (Without defining a string variable.)
>
> Chris

print "%s%s" % ("foo", "bar")  ## If "%s%s" doesn't violate your
condition of not defining a string variable, I'm not sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Need some help with 'with'

2007-11-27 Thread Mike Kent
I recently found myself needing to do this a lot:

lock a record in a file
read the record into a buffer
alter the buffer
write the buffer back to the record
unlock the record

I'd love to be able to create a context for this to use with the
'with' statement, something like:

from __future__ import with_statement
from contextlib import contextmanager
from fcntl import lockf, LOCK_EX, LOCK_UN

@contextmanager
def lockedRecord(fileObj, offset, length):
lockf(fileObj, LOCK_EX, offset, length)
try:
fileObj.seek(offset)
buff = fileObj.read(length)
newBuff = (yield buff)
fileObj.seek(offset)
fileObj.write(newBuff)
finally:
lockf(fileObj, LOCK_UN, offset, length)

Which would let me write code like:

fileObj = open("myfile.dat", "r+b")

with lockedRecord(fileObj, 20, 10) as rec:
newRec = rec.replace('foo', 'bar')
# Somehow send newRec back into the context

I know you can now send data back into a generator via the send method
of the generator, however i don't seem to have access to the generator
object itself.

I figure that if instead of returning the buffer from the context
directly, I instead returned the buffer in a list, I could then change
the buffer, put it in the returned list, then I'd have access to it
back inside the context, but this seems a bit ugly.

Does anyone have insight into the right way of doing this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python question!!

2007-11-22 Thread Mike Kent
On Nov 22, 8:23 pm, "bruce" <[EMAIL PROTECTED]> wrote:

> is there a function/feature/etc.. that i can run on "foo.py" that would walk
> through the entire list of files that make up foo.py, so i could see the
> list of *.py files that are required to run "foo.py".

There's this:
http://www.tarind.com/depgraph.html

It generates a nice chart showing the 'tree' of imports for your
program.  I found it valuable for helping me resolve a circular import
problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


ACM SIGAPL / APL2007 Conference / Montreal / one week away

2007-10-15 Thread Mike Kent
Conference page
// with links to program details //
(updated Friday 10/12)

http://www.sigapl.org/apl2007.html


Co-located with OOPSLA 2007

http://www.oopsla.org/oopsla2007


On-line registration (through Wednesday 10/17)

http://www.regmaster.com/conf/oopsla2007.html

-- 
http://mail.python.org/mailman/listinfo/python-list


APL2007 reminder: early (cheaper) registration ends Thursday 9/13

2007-09-08 Thread Mike Kent
On-line registration is through the OOPSLA registrar

http://www.regmaster.com/conf/oopsla2007.html


APL 2007 home page

http://www.sigapl.org/apl2007.html
-- 
http://mail.python.org/mailman/listinfo/python-list


What's on at APL 2007, Montreal, October 21, (Tutorials) 22, 23 (Program)

2007-08-30 Thread Mike Kent
( Details and abstracts coming to the APL 2007 web page

   http://www.sigapl.org/apl2007.html

   shortly.  In the meantime ... )


Tutorials and workshops

 Introduction to APL (Ray Polivka)

 OO for APLers, APL for OOers (Dan Baronet)

 ... others in the works


Presentations

No Experience Necessary:
Hire for Aptitude - Train for Skills
 (Brooke Allen)

 Compiling APL with APEX
 (Robert Bernecky)

 APL, Bioinformatics, Cancer Research
 (Ken Fordyce)

 Generic Programming on Nesting Structure
 (Stephan Herhut, Sven-Bodo Scholz, Clemens Grelck)

 Interactive Array-Based Languages and Financial Research
 (Devon McCormick)

 Array vs Non-Array Approaches to Programming Problems
 (Devon McCormick)

 Design Issues in APL/OO Interfacing
 (Richard Nabavi)

 Arrays of Objects, or Arrays within Objects
 (Richard Nabavi)

 Competing, with J
 (John Randall)



Plus representatives of vendors:

Dyalog  --  IBM  --  MicroAPL
-- 
http://mail.python.org/mailman/listinfo/python-list


(Re)announcing APL 2007

2007-08-05 Thread Mike Kent

APL 2007 conference on Array Programming

 co-located with OOPSLA 2007


Sponsor:  ACM SIGAPL

Where:Montreal

When: October 21 (tutorials)
   October 22/23  (main conference program)

Keynote   Guy Steele
speaker:  Sun Microsystems Laboratories


Links:
 Info: http://www.sigapl.org/apl2007.html
 Registration: http://www.regmaster.com/conf/OOP07/oop07.pdf

 OOPSLA:   http://www.OOPSLA.org/oopsla2007
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Announcing: ACM SIGAPL apl 2007 -- Arrays and Objects

2007-05-31 Thread Mike Kent
The APL2007 URL was given incorrectly  should be

   http://www.sigapl.org/apl2007.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Announcing: ACM SIGAPL apl 2007 -- Arrays and Objects

2007-05-27 Thread Mike Kent


The APL 2007 conference, sponsored by ACM SIGAPL,
has as its principal theme "Arrays and Objects" and,
appropriately, is co-located with OOPSLA 2007, in
Montreal this October.


APL 2007 starts with a tutorial day on Sunday, October 21, followed by a
two-day program on Monday and Tuesday, October 22 and 23.

APLers are welcome to attend OOPSLA program events on Monday and Tuesday
(and OOPSLA attendees are welcome to come to APL program events).

Registrants at APL 2007 can add full OOPSLA attendance at a favorable price.


Dates:

 Sunday  Oct 21   Tutorials
 Monday, Tuesday Oct 22,23APL 2007 program
 Monday-Friday   Oct 22-26OOPSLA program


APL 2007 keynote speaker:  Guy Steele, Sun Microsystems Laboratories


Tutorials

 Using objects within APL

 Array language practicum

 Intro to [language] for other-language users
 ( We expect that there will be at least one introductory
   tutorial on "classic" APL, and hope to have introductions
   to a variety of array languages )





We solicit papers and proposals for tutorials, panels and workshops on
all aspects of array-oriented programming and languages; this year we
have particular interest in the themes of

  integrating the use of arrays and objects

  languages that support the use of arrays as a
  central and thematic technique

  marketplace and education:  making practitioners aware of
  array thinking and array languages


Our interest is in the essential use of arrays in programming in any
language (though our historical concern has been the APL family of
languages:  classic APL, J, K, NIAL, ).


Dates:

 Tutorial, panel, and workshop proposals, and notice of intent to
 submit papers, are due by Friday June 15, to the Program Chair.

 Contributed papers, not more than 10 pages in length, are due
 by Monday, July 23, to the Program Chair.  Details of form of
 submission can be obtained from the program chair.


 Deadline for detailed tutorial/panel/workshop information TBA.


Cost (to SIGAPL and ACM members, approximate $US, final cost TBA)

 APL2007 registration $375
 Tutorial day $250
 Single conference days   $200



Social events:Opening reception Monday
   Others TBA


Conference venue: Palais de Congres, Montreal, Quebec, CANADA
Conference hotel: Hyatt Regency Montreal


Committee

General Chair Guy Laroque  [EMAIL PROTECTED]
Program Chair Lynne C. Shaw[EMAIL PROTECTED]
Treasurer Steven H. Rogers [EMAIL PROTECTED]

    Publicity Mike Kent[EMAIL PROTECTED]



Links

APL2007  http://www.sigapl.org/apl2007
OOPSLA 2007  http://www.oopsla.org/oopsla2007
Palais de Congreshttp://www.congresmtl.com/
Hyatt Regency Montreal   http://montreal.hyatt.com

Guy Steelehttp://research.sun.com/people/mybio.php?uid=25706

ACM SIGAPLhttp://www.sigapl.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Join strings - very simple Q.

2007-03-23 Thread Mike Kent
On Mar 23, 2:37 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote:
> Hi!
>
> I was told in this NG that string is obsolet. I should use
> str methods.
>
> So, how do I join a list of strings delimited by a given
> char, let's say ','?
>
> Old way:
>
> l=['a','b','c']
> jl=string.join(l,',')
>
> New way?
>
> Thanks
> Paulo

New way:
l=['a','b','c']
jl=','.join(l)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle Problem

2007-03-15 Thread Mike Kent
On Mar 15, 11:13 am, "tonyr1988" <[EMAIL PROTECTED]> wrote:

> if __name__=='__main__':
> x = DemoClass
> x.WriteToFile
>

You meant to create a DemoClass instance object, but instead, you
obtained a reference to the class object.  You want 'x = DemoClass()'
instead.
You meant to call the WriteToFile method, but instead, you obtained a
reference to the method object.  You want 'x.WriteToFile()' instead.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: doxygen

2007-03-04 Thread Mike Kent
On Mar 4, 1:15 pm, Jan Danielsson <[EMAIL PROTECTED]> wrote:

>When I run doxygen on my python files, it does document classes, but
> not "standalone" functions.

Look in the doxygen config file for your python project, named
'Doxyfile', for the config setting
'EXTRACT_ALL', and read the comments there.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: conditional computation

2006-10-26 Thread Mike Kent

robert wrote:
> I want to use a computation cache scheme like
>
>
>   o = CACHECOMPUTE  complex-key-expr  expensive-calc-expr
>
>
> frequently and elegantly without writing complex-key-expr or 
> expensive-calc-expr twice.
> So its ugly:
>
>   _=complex-key-expr; o=cache.get(_) or 
> cache.setdefault(_,expensive-calc-expr)
>
> Any ideas?
>
> -robert

Your question is a bit terse, so my answer might not be spot on for it,
but it sounds like you want what is typically called 'memoization',
whereby a function caches its expensive-to-calculate return values,
where the cache is keyed by the function arguments.

See:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
and various other implimentations in the Cookbook for details.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about True values

2006-10-25 Thread Mike Kent

John Salerno wrote:
> I'm a little confused. Why doesn't s evaluate to True in the first part,
>   but it does in the second? Is the first statement something different?
>
>  >>> s = 'hello'
>  >>> s == True
> False
>  >>> if s:
>   print 'hi'
>
>
> hi
>  >>>
>
> Thanks.

Excellent question!  This should help:

>>> s = "Hello"
>>> s
'Hello'
>>> bool(s)
True
>>> s == True
False

The value of s is not equal to the value of True.  But, the *boolean*
value of s is True, since it is not 0 or an empty string.  The python
'if' statement evaluates the boolean value of the condition expression.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python newbie with a problem writing files

2006-09-03 Thread Mike Kent

> feed_list = open("feed_listing.conf","r")

What could it be about the above line that means "Open this file for
READ ONLY"?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newb question: file searching

2006-08-08 Thread Mike Kent

[EMAIL PROTECTED] wrote:
> I'm new at Python and I need a little advice.  Part of the script I'm
> trying to write needs to be aware of all the files of a certain
> extension in the script's path and all sub-directories.

What you want is os.walk().

http://www.python.org/doc/current/lib/os-file-dir.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Process files in order

2006-07-27 Thread Mike Kent
How about using os.listdir to build a list of filenames, then sorting
them by modification time (via os.stat)?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to automate user input at the command prompt?

2006-07-21 Thread Mike Kent

[EMAIL PROTECTED] wrote:
> You may want to look at pexpect:
>
> http://pexpect.sourceforge.net/
>
> But I am not sure about its support on windows.

To the best of my recent investigation, and an email exchange with the
author of pexpect, it is NOT supported under Windows.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiplatform scripts: Can I avoid os.sep?

2006-07-13 Thread Mike Kent
gmax2006 wrote:
> Hi,
>
> I am developing scripts that must run on both Linux and windows.
>
> My scripts contain lots of relative paths (such as log\\log.txt or
> ctl\\table.ctl) If I use os.sep, it makes the code ugly. Is there any
> tips or techniques to have Python automatically converts \\ to / when
> the script runs on Linux? What is the best way to deal with this
> situation?

Use Jason Orendorff's path module:

http://www.jorendorff.com/articles/python/path/

Then you can do things like:

targetPath = 'some' / 'random' / 'path'

and the overridden '/' operator will do the right thing for the OS you
are on.
Of course, using the '/' operator in this manner makes some people's
heads explode.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advice for Python Reporting Tool

2006-07-12 Thread Mike Kent
rwboley wrote:

> My question is: how can I make that graphing step easier?  Ideally I'd
> like the chart to exist on it's own page, but I have no idea where to
> even begin to implement this.  Any thoughts would be appreciated.

I've seen several people recommend matplotlib for this kind of thing.

http://matplotlib.sourceforge.net/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2 problems

2006-07-07 Thread Mike Kent

[EMAIL PROTECTED] wrote:
> Hello,Im using Python 2.4.2 and I'm starting a few very basic
> programs,but theres two problems I've not found the answers for.
> My first problem is I need code that will count the number of letters
> in a string and return that number to a variable.

>>> s = "hello"
>>> len(s)
5

> My second problem stems from the first as I need a function that can
> slice the string into letters and have those put in seperate
> strings.Ive tried using the normal [:1],[:2],etc but I need a function
> that can do that a variable amount of times due to the varying number
> of letters in the input.

>>> s = "hello"
>>> list(s)
['h', 'e', 'l', 'l', 'o']

>
> This would be of great help,as python is new to me.

Welcome aboard!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easier way to save result of a function?

2006-07-04 Thread Mike Kent
James Mitchelhill wrote:
> Sorry for the clunky subject line - I have a feeling that not knowing
> the proper terms for this is part of my problem.
>
> I'm trying to write a class that analyses some data. I only want it to
> do as much work as necessary, so it saves method results to a
> dictionary, like so:

The term for this is 'memoization'.  You can find several recipes for
this in the online Python Cookbook; for example, see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466320

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Manipulation

2006-07-04 Thread Mike Kent
Roman wrote:
> Thanks for your help
>
> My intention is to create matrix based on parsed csv file.  So, I would
> like to have a list of columns (which are also lists).
>
> I have made the following changes and it still doesn't work.
>
>
> cnt = 0
> p=[[], [], [], [], [], [], [], [], [], [], []]
> reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
>  quotechar="'", delimiter='\t')
> for line in reader:
> if cnt > 6:
>break
> j = 0
> for col in line:
>p[j].append(col)
>j=j+1
> cnt = cnt + 1
>
> print p

p[j] does not give you a reference to an element inside p.  It gives
you a new sublist containing one element from p.  You then append a
column to that sublist.  Then, since you do nothing more with that
sublist, YOU THROW IT AWAY.

Try doing:

p[j] = p[j].append(col)

However, this will still result in inefficient code.  Since every line
you read in via the csv reader is already a list, try this (untested)
instead:

reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
 quotechar="'", delimiter='\t')
p = [ line for line in reader[:7] ]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List Manipulation

2006-07-04 Thread Mike Kent
Roman wrote:
> I would appreciate it if somebody could tell me where I went wrong in
> the following snipet:
>
> When I run I get no result
>
> cnt = 0
> p=[]
> reader = csv.reader(file("f:\webserver\inp.txt"), dialect="excel",
>  quotechar="'", delimiter='\t')
> for line in reader:
> if cnt > 6:
>break
> for col in line:
>p[:0].append(str(col))
> cnt = cnt + 1
>
> print p

I'm having trouble deciding what you *intend* this program to do.  It
looks like you want to take the first 7 lines of the input file, and
append all the data elements in those lines into one long list.  If
that's what you want to do, then you are almost there, although you
could have written it better.  If that's NOT what you want to do...
well, there are tutorials.

The problem with this code is in the line 'p[:0].append(str(col)).
Given a list p, p[:0] will give you the part of p *prior* to element 0.
 Since there is never anything in a list prior to element 0, you will
always get an empty list back.

I assume this is not what you intended.  But just *what* do you intend?
 I sure can't say.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unittest behaving oddly

2006-06-20 Thread Mike Kent
David Vincent wrote:

> > import unittest
> >
> > class IntegerArithmenticTestCase(unittest.TestCase):
> > def testAdd(self):  ## test method names begin 'test*'
> > assertEquals((1 + 2), 3)
> > assertEquals(0 + 1, 1)

assertEquals is a member function, inherited from unittest.TestCase, so
you must call it as self.assertEquals.  ForEx:

class IntegerArithmenticTestCase(unittest.TestCase):
 def testAdd(self):  ## test method names begin 'test*'
 self.assertEquals((1 + 2), 3)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of accessing functions in a module?

2006-06-13 Thread Mike Kent
Yes, you can go that route.  But since it appears that what you are
doing is unit testing related, and you are interested in aranging for
all of your unit test cases to be run automatically, I'd suggest using
the unittest module.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Searching and manipulating lists of tuples

2006-06-12 Thread Mike Kent

MTD wrote:
> Hello,
>
> I'm wondering if there's a quick way of resolving this problem.
>
> In a program, I have a list of tuples of form (str,int), where int is a
> count of how often str occurs

...

> So clearly that doesn't work... any ideas?

Yes, use the proper tool for the job.  Tuples are immutable (they are
read-only once created).  Instead use a dictionary.  They key would be
your string, the value would be the count.

Also, don't use 'str' as the name for a string, as it shadows the
built-in 'str' function.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with google api / xml

2006-05-31 Thread Mike Kent

robin wrote:

> from SOAPpy import WSDL
> WSDLFILE = '/pathtomy/googleapi/GoogleSearch.wsdl'
> APIKEY = ''
> _server = WSDL.Proxy(WSDLFILE)

Robin, note this part of the URI set in WSDLFILE:
'/pathtomy/googleapi'.  Get it?  'path to my google api'.  You must set
this part to the actual path where the file 'GoogleSearch.wsdl' is
found.  In addition, doesn't APIKEY = '' look a bit odd to you?
Hmm, what could this mean.  APIKEY.  Perhaps you need to get an API key
from Google in order to use their search API, and fill it in there?

;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Anyone compiling Python 2.3 on an SCO OpenServer 5 box?

2006-05-25 Thread Mike Kent
I need to compile Python on OpenServer  5 because I need to 'freeze'
our Python app, and running 'freeze' requires a working, compilable
source installation of Python.

-- 
http://mail.python.org/mailman/listinfo/python-list


Anyone compiling Python 2.3 on an SCO OpenServer 5 box?

2006-05-25 Thread Mike Kent
If anyone is successfully compiling Pyton 2.3 on an SCO OpenServer 5
box, I'd appreciate hearing from you on how you managed to do it.  So
far, I'm unable to get a python that doesn't coredump.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List behaviour

2006-05-17 Thread Mike Kent
When you did:
b = a[:]

b was then a copy of a, rather than just a reference to the same a.
But what does a contain?  It contains two sublists -- that is, it
contains references to two sublists.  So b, which is now a copy of a,
contains copies of the two references to the same two sublists.

What you need to do instead is:
b = copy.deepcopy(a)

to get you what you actually want.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I take a directory name from a given dir?

2006-05-01 Thread Mike Kent
Python 2.4.2 (#1, Nov 29 2005, 14:04:55)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> d = "/home/testuser/projects"
>>> os.path.basename(d)
'projects'
>>> os.path.dirname(d)
'/home/testuser'
>>>

-- 
http://mail.python.org/mailman/listinfo/python-list