Re: type = "instance" instead of "dict"

2006-02-27 Thread Fredrik Lundh
James Stroud wrote:

> Perhaps you did not know that you can inheret directly from dict, which
> is the same as {}. For instance:
>
> class Dict({}):
>pass
>
> Is the same as
>
> class Dict(dict):
>pass

it is ?

>>> class Dict({}):
... pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Error when calling the metaclass bases
dict expected at most 1 arguments, got 3





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


Re: newbie

2006-02-27 Thread Steve Holden
Brain Murphy wrote:
[...]
> also i have heard that there are no crackers using python why is this??
>  
Because the Python Secret Underground seeks hackers out and
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Carl Banks
Ben Finney wrote:
> This PEP specifies an enumeration data type for Python.

-1 for this particular proposal as a builtin.  I feel it's not a great
design of something that isn't terribly useful to begin with.  +0 for
the standard library, only after a couple changes.  As I see it, this
whole proposal is a minor improvement over doing something like the
following, but too minor an improvement to add to the builtin
namespace:

MON = 'mon'
TUE = 'tue'
etc.

DAYS_OF_WEEK  = (MON,TUE,etc.)


[snip]
> It is possible to simply define a sequence of values of some other
> basic type, such as ``int`` or ``str``, to represent discrete
> arbitrary values.  However, an enumeration ensures that such values
> are distinct from any others, and that operations without meaning
> ("Wednesday times two") are not defined for these values.

Here's why I think it's not too useful to begin with: the benefits of
the enum you describe here are pretty weak.

It's a pretty weak case to have a dedicated builtin to prevent
duplicates in something that changes maybe once a month, as enums tend
to change rather slowly.  (At least, that's the way enums in other
languages are used, and the design you present here seems to suggest
you intend to use them that way as well.)  And frankly, a unit test or
assertion could check this.

As for preventing nonsensical operations on enum constants: good idea,
but let's face it: a decent programmer knows whether he or she's
dealing with a enum value or a piece of string data.  This is why I
said it's not terribly useful (as opposed to not useful at all).
Unfortunately, this proposal fails to prevent a nonsensical operation
in the case where it would be most useful to do so.


[snip]
> Enumerations with no values are meaningless.  The exception
> ``EnumEmptyError`` is raised if the constructor is called with no
> value arguments.

No strong feeling on this issue.  Probably no use for an empty enum,
but no harm either.


[snip]
> This allows the operation to succeed, evaluating to a boolean value::
>
> >>> gym_night = Weekdays.wed
> >>> gym_night < Weekdays.mon
> False
> >>> gym_night < Weekdays.wed
> False
> >>> gym_night < Weekdays.fri
> True
> >>> gym_night < 23
> False
> >>> gym_night > 23
> True
> >>> gym_night > "wed"
> True
> >>> gym_night > Grades.B
> True

The nonsensical comparisions should throw value errors.  You say that
you want to get rid of operations that don't make sense, but it seems
misguided that we would get rid of multiplying by a integer (something
that's not likely to happen much at all) but retain comparison with
other types (something that's going to be much more common).

I realize that this is a thoughtful decision on your part, that you
have some reason for it and were not just blindly following the example
of other Python builtins.  However, IMHO, this design decision forsakes
the single most useful feature of an enum, and replaces it with
confusion.


[snip examples of use]

One thing I'd add is something like Weekdays.get_constant("wed").  I
realize that you can do this with getattr, but you can also do
getattr(Weekdays,"__dict__") with getattr, and you ought to have a
method that thows and exception if you try to access the __dict__
constant.

Also, it blesses the operation, so that people who are trying to access
the constant after reading its name from the database don't have to
feel guilty about using getattr.


[snip]
> Metaclass for creating enumeration classes
> --
>
> The enumerations specified in this PEP are instances of an ``enum``
> type.  Some alternative designs implement each enumeration as its own
> class, and a metaclass to define common properties of all
> enumerations.
>
> One motivation for having a class (rather than an instance) for each
> enumeration is to allow subclasses of enumerations, extending and
> altering an existing enumeration.  A class, though, implies that
> instances of that class will be created;

How so?  This is true of classes with metaclass type, but using a
different metaclass suggests maybe it isn't like a regular class.  In
particular, constructing an instance could be a non-op; instead the
class creates it's own instances at definition time.  I don't see
anything that implies that a class can't do that.

> it is difficult to imagine
> what it means to have separate instances of a "days of the week"
> class, where each instance contains all days.

I don't understand what you're saying here.  It doesn't seem to me hard
to imagine that a class could create its own instances, but I'm not
sure if that's what you're talking about.

> This usually leads to
> having each class follow the Singleton pattern, further complicating
> the design.

Meh.  I don't feel too strongly about this, but I'd think an enum as a
class is better, because you can't (or, rather, oughtn't) compare
constants from different enums.  That's a logical demarcatio

Re: type = "instance" instead of "dict"

2006-02-27 Thread Steve Holden
James Stroud wrote:
> Cruella DeVille wrote:
> 
>>I'm trying to implement a bookmark-url program, which accepts user
>>input and puts the strings in a dictionary. Somehow I'm not able to
>>iterate myDictionary of type Dict{}
>>
>>When I write print type(myDictionary) I get that the type is
>>"instance", which makes no sense to me. What does that mean?
>>Thanks
>>
> 
> 
> Perhaps you did not know that you can inheret directly from dict, which 
> is the same as {}. For instance:
> 
> class Dict({}):
>pass
> 
> Is the same as
> 
> class Dict(dict):
>pass
> 
With the minor exception that the second is valid Python, while the 
first isn't:

  >>> class Dict({}):
  ...pass
  ...
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: Error when calling the metaclass bases
 dict expected at most 1 arguments, got 3
  >>>

It's quite an interesting error message, though ;-)

> Now Dict can do everything that dict ({}) can do, but you can also 
> specialize it:
> 
> py> class Dict(dict):
> ...   def __str__(self):
> ... return "I am %s long. But you should read the tutorial!" % len(self)
> ...
> py> d = Dict()
> py> d['a'] = 1
> py> d['b'] = 2
> py>
> py> d['a']
> 1
> py> d['b']
> 2
> py> print d
> I am 2 long. But you should read the tutorial!
> 
You're right about that, but we all need a helping hand now and then ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: changing params in while loop

2006-02-27 Thread Ben Cartwright
robin wrote:
> i have this function inside a while-loop, which i'd like to loop
> forever, but i'm not sure about how to change the parameters of my
> function once it is running.
> what is the best way to do that? do i have to use threading or is there
> some simpler way?


Why not just do this inside the function?  What exactly are you trying
to accomplish here?  Threading could work here, but like regexes,
threads are not only tricky to get right but also tricky to know when
to use in the first place.

That being said, here's some example threading code to get you started
(PrinterThread.run is your function; the ThreadSafeStorage instance
holds your parameters):

import threading
import time

class ThreadSafeStorage(object):
def __init__(self):
object.__setattr__(self, '_lock', threading.RLock())
def acquirelock(self):
object.__getattribute__(self, '_lock').acquire()
def releaselock(self):
object.__getattribute__(self, '_lock').release()
def __getattribute__(self, attr):
if attr in ('acquirelock', 'releaselock'):
return object.__getattribute__(self, attr)
self.acquirelock()
value = object.__getattribute__(self, attr)
self.releaselock()
return value
def __setattr__(self, attr, value):
self.acquirelock()
object.__setattr__(self, attr, value)
self.releaselock()

class PrinterThread(threading.Thread):
"""Prints the data in shared storage once per second."""
storage = None
def run(self):
while not self.storage.killprinter:
self.storage.acquirelock()
print 'message:', self.storage.message
print 'ticks:', self.storage.ticks
self.storage.ticks += 1
self.storage.releaselock()
time.sleep(1)

data = ThreadSafeStorage()
data.killprinter = False
data.message = 'hello world'
data.ticks = 0
thread = PrinterThread()
thread.storage = data
thread.start()
# do some stuff in the main thread
time.sleep(3)
data.acquirelock()
data.message = 'modified ticks'
data.ticks = 100
data.releaselock()
time.sleep(3)
data.message = 'goodbye world'
time.sleep(1)
# notify printer thread that it needs to die
data.killprinter = True
thread.join()

# output:
"""
message: hello world
ticks: 0
message: hello world
ticks: 1
message: hello world
ticks: 2
message: modified ticks
ticks: 100
message: modified ticks
ticks: 101
message: modified ticks
ticks: 102
message: goodbye world
ticks: 103
"""

--Ben

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


Re: type = "instance" instead of "dict"

2006-02-27 Thread James Stroud
Cruella DeVille wrote:
> I'm trying to implement a bookmark-url program, which accepts user
> input and puts the strings in a dictionary. Somehow I'm not able to
> iterate myDictionary of type Dict{}
> 
> When I write print type(myDictionary) I get that the type is
> "instance", which makes no sense to me. What does that mean?
> Thanks
> 

Perhaps you did not know that you can inheret directly from dict, which 
is the same as {}. For instance:

class Dict({}):
   pass

Is the same as

class Dict(dict):
   pass

Now Dict can do everything that dict ({}) can do, but you can also 
specialize it:

py> class Dict(dict):
...   def __str__(self):
... return "I am %s long. But you should read the tutorial!" % len(self)
...
py> d = Dict()
py> d['a'] = 1
py> d['b'] = 2
py>
py> d['a']
1
py> d['b']
2
py> print d
I am 2 long. But you should read the tutorial!

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


Re: Python and Flash

2006-02-27 Thread SamFeltus
PS.  Here is an example...

http://sonomasunshine.com/sonomasunshine/FrontPage.html

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


Re: Python and Flash

2006-02-27 Thread SamFeltus
PS.  Here is an example...

http://sonomasunshine.com/sonomasunshine/FrontPage.html

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


Re: Python and Flash

2006-02-27 Thread SamFeltus
Why not just have the Python on the server send a JSON string to the
Flash ap?  Easy easy.  Just use LoadVars on the Flash side.

All that SOAP and XML-RPC sounds might be an needless overcomplication.

Sam the Gardener

http://sonomasunshine.com

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Alex Martelli
Ben Finney <[EMAIL PROTECTED]> wrote:
   ...
> The Python parser knows what to do when a comparison returns
> NotImplemented.

The parser has nothing to do with it, but the bytecode interpreter sure
does;-).


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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Alex Martelli
Terry Reedy <[EMAIL PROTECTED]> wrote:
   ...
> I suspect that the notion of empty  set was once controversial.

Yep: Reverend Dodgson (best known by his pen name of Lewis Carroll, and
as the author of the Alice novels, but a logician and mathematician IRL)
fought long and hard against Cantor's set theory, focusing on "the empty
set" (singular: in Cantor's theory there can be only one) but not
managing to build an actual contradiction around it.  The poor man died
just before his compatriot Bertrand Russell found "Russell's Paradox"
(which destroyed Frege's logic -- but is quite applicable to destroying
a foundation stone of Cantor's set theory as well).

I personally believe that Dodgson was reaching towards what today we
call modal logic (particularly intensional logic), though he could
hardly get there with such encumbrances as his fiction writing, his
photography, his heavy smoking of cannabis, etc, etc. But, that's just
me, and I can't claim to be an expert at modern set theory (though I do
know enough of it to see that it's quite different from Cantor's "naive"
version that's still taught in most schools...!-), much less of the
subtleties of modal logic.  Still, if you give a set interpretation of
modal logic, there isn't ONE empty set: the crucial point of modal
logic, from my semi-learned POV, is that it distinguishes what JUST
HAPPENS to be false, from what MUST INTRINSICALLY be false (and ditto
for true).  In set terms, say, "all integers x such that x>x" would be
an *intrinsically* empty set, while "all dogs that are in this house
right now" would be a set which *just happens* to be empty -- they
aren't "one and the same, the sole empty set" any more than they are in
commonsense (the notion Dodgson fought against).


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


Re: Use of __slots__

2006-02-27 Thread Alex Martelli
MrJean1 <[EMAIL PROTECTED]> wrote:

> An example of the RARE use case may be this particular one
> 
>   

A benchmark is not a use case.


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


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 27)

2006-02-27 Thread Cameron Laird
QOTW:  "Actually, Python has the distinction of being both a great tool
language *and* a great Zen language. That's what makes Python so cool
;-)))" - Ron Stephens

"It is probably possible to do the whole thing with a regular expression.
It is probably not wise to do so." - John Zenger (among MANY other wise
people)


Steve Holden generates abundant volume of PyCon reportage
when executive responsibilities don't tether him:
   http://holdenweb.blogspot.com/

A question from Brian Blais on the simplest non-trivial sorting
elicits a satisfying range of expressions:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/560fda5a309a08ab/

Use the 'Net for backups in a far more sophisticated way:
http://www.csua.berkeley.edu/~emin/source_code/dibs/   

A beta release of the updated official Python site will go 
live on 5 March 2006:
http://wiki.python.org/moin/PyCon2006/Sprints/PydotorgSprint



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
The old Python "To-Do List" now lives principally in a
SourceForge reincarnation.
http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
http://python.sourceforge.net/peps/pep-0042.html
 
The online Python Journal is posted at pythonjournal.cognizor.com.
[EMAIL PROTECTED] and [EMAIL PROTECTED]
welcome submission of material that helps people's understanding
of Python use, and offer Web presentation of your work.

del.icio.us presents an intriguing approach to reference commentary.
It already aggregates quite a bit of Python intelligence.
http://del.icio.us/tag/python

*Py: the Journal of the Python Language*
http://www.pyzine.com

Archive pr

Re: How to do an 'inner join' with dictionaries

2006-02-27 Thread Michael J. Fromberger
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Let's say I have two dictionaries:
> dict1 is  1:23,  2:76,  4:56
> dict2 is  23:A, 76:B,  56:C
> 
> How do I get a dictionary that is
> 1:A, 2:B, 4:C

The following should work:

  j = dict((k, dict2[dict1[k]]) for k in dict1 if dict1[k] in dict2)

Cheers,
-M

-- 
Michael J. Fromberger | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort one list using the values from another list

2006-02-27 Thread Kent Johnson
Simon Sun wrote:
> Magnus Lycka wrote:
> 
>>Is there something here I can't see, or did you just
>>change a variable name and present that as another
>>solution?
> 
> Heh, I have use python for a very short time. Base your statements, I test
> in python, found `_' is a valid variable name. So I don't know it is a just
> a plain variable or like something pattern matching in Haskell.

_ is just a plain variable name in Python. It is sometimes when a 
variable is needed to receive a value that won't be used. So your 
example was correct and idiomatic but functionally identical to mine.

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Roy Smith
A few random questions:

a = enum ('foo', 'bar', 'baz')
b = enum ('foo', 'bar', 'baz')

what's the value of the following:

a == b
a is b
a.foo == b.foo
a.foo is b.foo
len (a)
str (a)
repr (a)
hash (a)
type (a)

Can you make an enum from a sequence?

syllables = ['foo', 'bar', 'baz']
c = enum (syllables)

You imply that it works from "An enumerated type is created from a sequence 
of arguments to the type's constructor", but I suspect that's not what you 
intended.

BTW, I think this is a great proposal; enums are a badly needed part of the 
language.  There's been a number of threads recently where people called 
regex methods with flags (i.e. re.I) when integers were expected, with 
bizarre results.  Making the flags into an enum would solve the problem 
while retaining backwards compatibility.  You would just have to put in the 
re module something like:

flags = enum ('I', 'L', 'M', 'S', 'U', 'X')
I = flags.I
L = flags.L
M = flags.M
S = flags.S
U = flags.U
X = flags.X

then the methods which expect a flag can do:

if flag is not in re.flags:
   raise ValueError ("not a valid flag")

and the ones which expect an integer would (if nothing better), raise 
NotImplemented when they tried to use the value as an integer if you passed 
it a flag by mistake.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort one list using the values from another list

2006-02-27 Thread Simon Sun
Magnus Lycka wrote:

> Is there something here I can't see, or did you just
> change a variable name and present that as another
> solution?
Heh, I have use python for a very short time. Base your statements, I test
in python, found `_' is a valid variable name. So I don't know it is a just
a plain variable or like something pattern matching in Haskell.
-- 
Simon Sun

you can logout any time you like,
but you can never leave...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Ben Finney <[EMAIL PROTECTED]> wrote:

> I'll amend the specification so empty enumerations are not an
> error. (This will also remove the last remaining exception class from
> the specification, making it cleaner still. Good.)

And once you've done that, we can build an enum of all the exceptions which 
enums can raise :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> By way of explanation, my earlier implementations of this didn't have
> enumerations as sequences. Now that the design has converged more on a
> sequence and container idiom, I agree with you.

say that 
   Weekdays = enum('mon', 'tue', ...)

What is the type of Weekdays.mon supposed to be?

Do you anticipate having parameters like socket.AF_INET that are
currently integers, become enumeration members in future releases?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spaces at ends of filenames or directory names on Win32

2006-02-27 Thread [EMAIL PROTECTED]

rtilley wrote:
> Roel Schroeven wrote:
> > rtilley schreef:
> >
> >> This will at least allow me to ID folders that start with
> >> whitespace... from within Windows too :) yet I still cannot rename the
> >> folders after stripping the whitespace... attempting to gives an
> >> [Errno 2] No such file or directory. The strip seems to work right too
> >> according to the prints before and after.
> >
> >
> > Does the rename work if try with other names?
>
> Yes, the script can rename files that have no end whitespace. Also, I
> should note the the Windows GUI cannot rename the files. Same error...
> cannot stat the file. The only way I've been able to rename is through
> the cmd prompt using quotes like this:
>
> ren " bad file with end spaces " good_file_no_end_spaces
>
> I should also note that the code I posted earlier is misleading as
> os.listdir() gets dirs and files... not just dirs as I implied. Here's a
> better example that should get whitespace at either end (and does indeed
> on Mac and Unix... but not Windows)

It works for me.

And although you can't put leading spaces in file names using
Windows explorer, you don't have to use command line rename.

I modified your program to also put leading spaces back in.

It works fine also. See sample run at end of code.





import os
import os.path
import string

# dirs is actually files and folders, not just folders.
dirs =  os.listdir(os.getcwd())
path = os.getcwd()
print path

for d in dirs:
# If folder name begins with whitespace.
if d[0] in string.whitespace:
print d
try:
new_path = os.path.join(path, d.strip())
old_path = os.path.join(path, d)
print new_path
print old_path
os.renames(old_path, new_path)
except Exception, e:
print e

# If folder name ends with whitespace.
elif d[-1] in string.whitespace:
print d
try:
new_path = os.path.join(path, d.strip())
old_path = os.path.join(path, d)
print new_path
print old_path
os.renames(old_path, new_path)
except Exception, e:
print e

# Folder name is OK, so put spaces back in.
else:
if d[0] in '123':
try:
new_path = os.path.join(path, ' '*int(d[0])+d)
old_path = os.path.join(path, d)
print new_path
print old_path
os.renames(old_path, new_path)
except Exception, e:
print e

"""

D:\wstest>dir
 Volume in drive D is VOL_LOG1
 Volume Serial Number is CCB3-C62B

 Directory of D:\wstest

02/27/2006  07:38p.
02/27/2006  07:38p..
02/27/2006  07:03p   1,0523
02/27/2006  07:03p   1,052   2
02/27/2006  07:03p   1,052  1
02/27/2006  07:37p   1,344 wstest.py
   4 File(s)  4,500 bytes
   2 Dir(s)   1,007,540,736 bytes free

D:\wstest>C:\Python24\python.exe wstest.py
D:\wstest
   3
D:\wstest\3
D:\wstest\   3
  2
D:\wstest\2
D:\wstest\  2
 1
D:\wstest\1
D:\wstest\ 1

D:\wstest>dir
 Volume in drive D is VOL_LOG1
 Volume Serial Number is CCB3-C62B

 Directory of D:\wstest

02/27/2006  07:38p.
02/27/2006  07:38p..
02/27/2006  07:03p   1,052 1
02/27/2006  07:03p   1,052 2
02/27/2006  07:03p   1,052 3
02/27/2006  07:37p   1,344 wstest.py
   4 File(s)  4,500 bytes
   2 Dir(s)   1,007,540,736 bytes free

D:\wstest>C:\Python24\python.exe wstest.py
D:\wstest
D:\wstest\ 1
D:\wstest\1
D:\wstest\  2
D:\wstest\2
D:\wstest\   3
D:\wstest\3

D:\wstest>dir
 Volume in drive D is VOL_LOG1
 Volume Serial Number is CCB3-C62B

 Directory of D:\wstest

02/27/2006  07:40p.
02/27/2006  07:40p..
02/27/2006  07:03p   1,0523
02/27/2006  07:03p   1,052   2
02/27/2006  07:03p   1,052  1
02/27/2006  07:37p   1,344 wstest.py
   4 File(s)  4,500 bytes
   2 Dir(s)   1,007,540,736 bytes free

"""

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


Re: PEP 354 -- "in" operator?

2006-02-27 Thread Ben Finney
[fixing References field. Please reply in the original thread so I can
find you easily.]

Roy Smith <[EMAIL PROTECTED]> writes:
> If I have an enum, how can I verify that it's a legal value?  Can I
> do:
>
> Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
>
> def foo (day):
>if day not in Weekdays:
>   raise ValueError

The current PEP text doesn't specify; that's an omission on my
part. The answer should be "yes, an enum can be tested for
membership".

I'll add that to the specification.

> Also, do enums have __dict__ slots?

Not specified as having one, no.

> Can I do something like:
>
> day = 'sun'
> print Weekdays.__dict__[day]

You can do the same thing more elegantly by explicitly querying the
attributes of the enumeration::

>>> day = 'sun'
>>> print getattr(Weekdays, day)
sun

-- 
 \"There was a point to this story, but it has temporarily |
  `\ escaped the chronicler's mind."  -- Douglas Adams |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
Tim Chase <[EMAIL PROTECTED]> writes:
> Just a couple thoughts:

Appreciated.

>> An enumeration is an exclusive set of symbolic names bound
>> to arbitrary unique values.
>
> Uniqueness imposes an odd constraint that you can't have synonyms in
> the set:
>
>  >>> shades = enum({white:100, grey:50, gray:50, black:0})

I think a dict is best used for this purpose. An enumeration is for
when you want all the values in the collection to be unique, but don't
care particularly what those values *are*.

>  > >>> Grades = enum('A', 'B', 'C', 'D', 'F')
>
> This produces the counter-intuitive result of
>
>   >>> Grades.A > Grades.B
>   False
>
> Sure, one can bung with it and create the set of grades backwards,
> but then iteration becomes weird.  Perhaps the ability to override
> the comparitor?

Again, if you actually want specific values associated with each
member of the collection, I think a dict is best.

Note that the enumeration values *can* be dict keys, so you could
associate the values with other objects that way.

-- 
 \   "I was in a bar the other night, hopping from barstool to |
  `\ barstool, trying to get lucky, but there wasn't any gum under |
_o__)any of them."  -- Emo Philips |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
"Giovanni Bajo" <[EMAIL PROTECTED]> writes:
> Ben Finney wrote:
>> Values within an enumeration cannot be meaningfully compared except
>> with values from the same enumeration.  The comparison operation
>> functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a
>> value from an enumeration is compared against any value not from the
>> same enumeration or of a different type::
>> [...]
>> This allows the operation to succeed, evaluating to a boolean value::
>
> Given that this is going to change in Python 3.0 for builtin types,
> I'm not sure there's much reason to keep it this way.

What is it that will change? Can you point to something we should read
about this?

> I'd rather a comparison operation between different enum types to
> raise an exception. This would be a very compelling feature to use
> enum (and in fact, the implementation I chose in Cookbook for my
> programs have this feature).

A previous implementation raised exceptions from failed comparisons.
Here is the discussion that convinced me that was not the right thing
to do::


http://groups.google.com/group/comp.lang.python/browse_thread/thread/140de1765bbb8d2d/>

>> Coercing a value from an enumeration to a ``str`` results in the
>> string that was specified for that value when constructing the
>> enumeration::
>>
>> >>> gym_night = Weekdays.wed
>> >>> str(gym_night)
>> 'wed'
>
> What's the repr of an enumeration value?

Hmm, the PEP doesn't specify. I was leaving it up to the
implementation.

> OTOH, it should be something like "Weekdays.wed", so that
> eval(repr()) holds true. Also, it'd be very useful in debug dumps,
> tracebacks and whatnot.

An enumeration value object knows the enumeration object that created
it, but that enumeration doesn't know its own name; objects don't know
their own name, since they could have many, or none.

Even if an enumeration value were to know the name of the enumeration
that created it, you still have this problem::

>>> Colours = enum('red', 'green', 'blue')
>>> repr(Colours.green)
Colours.green
>>> Lamps = Colours
>>> repr(Lamps.red)
Colours.red

Is this desirable behaviour? I don't think so.

-- 
 \"I went to the hardware store and bought some used paint. It |
  `\   was in the shape of a house."  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


changing params in while loop

2006-02-27 Thread robin
hi,

i'm a newbie, but please bear with me for a second.
i have this function inside a while-loop, which i'd like to loop
forever, but i'm not sure about how to change the parameters of my
function once it is running.
what is the best way to do that? do i have to use threading or is there
some simpler way?
here's some code to show the structure of the problem:

from time import *

b = 44

def printStuff(a):
print a
sleep(1)
print b
sleep(1)

while 1:
printStuff("bibi")

now how can i make printStuff() print "fifi" instead of "bibi" or 88
instead of 44 once it is running?

thank y'all for your help
do the snake!

robin

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Paul Rubin
Ben Finney <[EMAIL PROTECTED]> writes:
> If an enumeration object were to be derived from, I would think it
> just as likely to want to have *fewer* values in the derived
> enumeration. Subclassing would not appear to offer a simple way to do
> that.

pentium_instructions = enum('add', 'sub', 'mul', ) # etc

athlon64_instructions = enum('add64', 'sub64', # etc
 base_enum=pentium_instructions)

# 386 has no floating point unit
i386_instructions = enum(base_enum=pentium_instructions,
 remove=('addf', 'subf', 'mulf',))  # etc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Mikalai
Steven D'Aprano wrote:
> Paul Rubin wrote:
>
> What is an empty enum? How and when would you use it?
>
> The best I can come up with is that an empty enum would
> be the enumerated values you have when you don't
> actually have any enumerated values. This is not to be
> confused with an empty list: an empty list is a
> well-defined concept. It is just a list (a container)
> with nothing in it. A list of X is like a box
> containing X, and like boxes, an empty list (or set, or
> dict) is meaningful. An enum of X is just the Xs
> themselves. If there is no X, there is nothing there.

"Nothing" in python is None. If empty enum is None, then it is the same
as empty list in Lisp is nil, i.e. type-of(nil)=='list. Giving a type
to nothing, isn't really useful. Thus, empty enum is needed.

Programaticaly or, say, in implementation, enum is some structure that
holds some stuff. Just like tuples and lists are structures to hold
something. As a structure, it can be empty.

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote
>> A list is a container.
>
> I think it is misleading, if not wrong, to refer to Python
> collections as 'containers', 'boxes', or similar.  A object in a box
> cannot be in another disjoint box.  A object in a box cannot be in
> the box a second time.  But both 'cannot's are 'can's for Python
> objects in respect to Python collections.  So, bad metaphor.

Thanks. Earlier today I referred to my conceptual model for
enumerations as "container". I agree with you that should be amended
to "collection".

Since an empty enumeration is consistent with the "collection" idiom,
and has obvious behaviour, I see no problem changing the specification
to remove that restriction.

> To me, 'I can't think of a use for X' is insufficient reason to
> prohibit X in Python.

I'm finding that most of the changes I made to the specification
before submitting the initial draft were removing such
restrictions. I'm glad to see that continues :-)

-- 
 \"Either he's dead or my watch has stopped."  -- Groucho Marx |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
Paul Rubin  writes:
> Hmm, I also see the PEP doesn't specify what's supposed to happen with
>
>   Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
>   Solar_system = enum('sun', 'mercury', 'venus', 'earth',)  # etc.
>   print Weekdays.sun == Solar_system.sun
>
> so that's another shortcoming with the PEP. 

The PEP text specifies::

Values within an enumeration cannot be meaningfully compared
except with values from the same enumeration.  The comparison
operation functions return ``NotImplemented`` when a value from an
enumeration is compared against any value not from the same
enumeration or of a different type

The Python parser knows what to do when a comparison returns
NotImplemented.

-- 
 \   "It ain't so much the things we don't know that get us in |
  `\  trouble. It's the things we know that ain't so."  -- Artemus |
_o__)  Ward (1834-67), U.S. journalist |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catch exceptions

2006-02-27 Thread Jonathan Gardner
(A) You'll have to be more specific about your problem if you want us
to help. Under which circumstances did it work or not? What exactly is
the problem?

(B) Where you put your error-handling is up to you. It depends on what
the function does and how it is to respond. Do you want the function to
throw an exception if the file is not found, or do you want it to do
something else? Think about the interface of the functions (which is
the sum of the parameters, response, possible exceptions, and expected
behavior) and it should be clear where to put the exception handling.

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
Paul Rubin  writes:
> Ben Finney <[EMAIL PROTECTED]> writes:
>> Enumerations with no values are meaningless.  The exception
>> ``EnumEmptyError`` is raised if the constructor is called with no
>> value arguments.
>
> Why are empty enumerations not allowed?  Empty sets, empty lists,
> empty dictionaries are all allowed.  I don't see any obvious benefits
> to not allowing empty enumerations.

By way of explanation, my earlier implementations of this didn't have
enumerations as sequences. Now that the design has converged more on a
sequence and container idiom, I agree with you.

I'll amend the specification so empty enumerations are not an
error. (This will also remove the last remaining exception class from
the specification, making it cleaner still. Good.)

-- 
 \   "I love to go down to the schoolyard and watch all the little |
  `\   children jump up and down and run around yelling and screaming. |
_o__)  They don't know I'm only using blanks."  -- Emo Philips |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type = "instance" instead of "dict"

2006-02-27 Thread Jonathan Gardner
You should probably spend a bit more time in the documentation reading
things for yourself. Read
http://www.python.org/doc/2.4.2/ref/types.html under "Class Instances"
for your answer.

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Ben Finney
"Giovanni Bajo" <[EMAIL PROTECTED]> writes:
> Kay Schluehr wrote:
>> Ben Finney wrote:
>>> One motivation for having a class (rather than an instance) for
>>> each enumeration is to allow subclasses of enumerations, extending
>>> and altering an existing enumeration.  A class, though, implies
>>> that instances of that class will be created; it is difficult to
>>> imagine what it means to have separate instances of a "days of the
>>> week" class, where each instance contains all days.  This usually
>>> leads to having each class follow the Singleton pattern, further
>>> complicating the design.
>>
>> Maybe a metaclass implementation complicates design, but usage is
>> quite simple and flexible. The classics is already referenced by
>> the Python docs:
>>
>> http://www.python.org/doc/essays/metaclasses/Enum.py
>
> Agreed. Allowing subclassing of an existing enum is a strong plus to me.

Having classes as enumerations seems to me to complicate the
conceptual model. As I see it, an enumeration is a container
object. For a container object to be subclassed has no obvious
semantic meaning.

If an enumeration object were to be derived from, I would think it
just as likely to want to have *fewer* values in the derived
enumeration. Subclassing would not appear to offer a simple way to do
that.

To preserve the promise that every enumeration's values are unique,
even the values that were inherited would need to be different in each
enumeration. This, again, doesn't fit well with the concept of
subclassing.

I can see value in wanting to derive a new enumeration from an
existing one; I just don't think subclassing makes sense for that
operation.

How would you specify the interface for deriving one enumeration from
another?

-- 
 \"Good judgement comes from experience. Experience comes from |
  `\   bad judgement."  -- Frederick P. Brooks |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catch exceptions

2006-02-27 Thread Cruella DeVille
I put the try catch in my main-method, and it worked to some extent
(except from when I try to read from a file with no content)

Any idea how to solve that?
And is it a good place to have a try-except in main instead of in the
class methods?

My code is at http://nibbler.no/blog/wp-includes/Bookmarks.py

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


Re: str.count is slow

2006-02-27 Thread Terry Reedy

"Ben Cartwright" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Your evidence points to some unoptimized code in the underlying C
> implementation of Python.  As such, this should probably go to the
> python-dev list (http://mail.python.org/mailman/listinfo/python-dev).
>
> The problem is that the C library function memcmp is slow, and
> str.count calls it frequently.  See lines 2165+ in stringobject.c
> (inside function string_count):
>
> r = 0;
> while (i < m) {
> if (!memcmp(s+i, sub, n)) {
> r++;
> i += n;
> } else {
> i++;
> }
> }
>
> This could be optimized as:
>
> r = 0;
> while (i < m) {
> if (s[i] == *sub && !memcmp(s+i, sub, n)) {
> r++;
> i += n;
> } else {
> i++;
> }
> }
>
> This tactic typically avoids most (sometimes all) of the calls to
> memcmp.  Other string search functions, including unicode.count,
> unicode.index, and str.index, use this tactic, which is why you see
> unicode.count performing better than str.count.

If not doing the same in str.count is indeed an oversight.  a patch should 
be welcome (on the SF tracker). 



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


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Great! That worked fine after I played with it for a bit. One last
question though. How do I label the ticks with the product of the
exponentiation? For instance:

100 

instead of 

10**2

Thanks for all the help,
Derek Basch

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


Re: sort one list using the values from another list

2006-02-27 Thread bearophileHUGS
Following Ron Adam solution (and using [] instead of list() in the last
line), this may be a possible solution of the problem, that is often
quite fast:

def psort16(s1, s2):
try:
d = dict(izip(s2, s1))
except TypeError:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)
else:
if len(d) == len(s1):
s1[:] = [d[v] for v in sorted(d)]
else:
_indices = range(len(s1))
_indices.sort(key=s2.__getitem__)
s1[:] = map(s1.__getitem__, _indices)

Bye,
bearophile

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Paul Rubin
"I V" <[EMAIL PROTECTED]> writes:
> I think it does, doesn't it? From the PEP:
> 
> "Values within an enumeration cannot be meaningfully compared *except
> with values from the same enumeration*.  The comparison operation
> functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a
> value from an enumeration is compared against any value not from the
> same enumeration or of a different type." (my emphasis)

Oh ok, thanks.  I didn't understand this before.  The link from the
footnote explains it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catch exceptions

2006-02-27 Thread Crutcher
Without seeing more of your code, I'm not sure what you are doing
wrong. This works:
 ex.py vv
def xopen(path):
  try:
return open(path)
  except IOError, e:
print 'Error:', e.args[1]

xopen('xyzzy')
^^
$ python ex.py
Error: No such file or directory

Could you give us the traceback?

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


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 27)

2006-02-27 Thread Cameron Laird
QOTW:  "Actually, Python has the distinction of being both a great tool
language *and* a great Zen language. That's what makes Python so cool
;-)))" - Ron Stephens

"It is probably possible to do the whole thing with a regular expression.
It is probably not wise to do so." - John Zenger (among MANY other wise
people)


Steve Holden generates abundant volume of PyCon reportage
when executive responsibilities don't tether him:
   http://holdenweb.blogspot.com/

A question from Brian Blais on the simplest non-trivial sorting
elicits a satisfying range of expressions:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/560fda5a309a08ab/

Use the 'Net for backups in a far more sophisticated way:
http://www.csua.berkeley.edu/~emin/source_code/dibs/   

A beta release of the updated official Python site will go 
live on 5 March 2006:
http://wiki.python.org/moin/PyCon2006/Sprints/PydotorgSprint



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
The old Python "To-Do List" now lives principally in a
SourceForge reincarnation.
http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
http://python.sourceforge.net/peps/pep-0042.html
 
The online Python Journal is posted at pythonjournal.cognizor.com.
[EMAIL PROTECTED] and [EMAIL PROTECTED]
welcome submission of material that helps people's understanding
of Python use, and offer Web presentation of your work.

del.icio.us presents an intriguing approach to reference commentary.
It already aggregates quite a bit of Python intelligence.
http://del.icio.us/tag/python

*Py: the Journal of the Python Language*
http://www.pyzine.com

Archive pr

Re: str.count is slow

2006-02-27 Thread Fredrik Lundh
Ben Cartwright wrote:

> > On my machine, the output is:
> >
> > str: 0.29365715475
> > array:   0.448095498171
> > unicode: 0.0243757237303

> This tactic typically avoids most (sometimes all) of the calls to
> memcmp.  Other string search functions, including unicode.count,
> unicode.index, and str.index, use this tactic, which is why you see
> unicode.count performing better than str.count.

it's about time that someone sat down and merged the string and unicode
implementations into a single "stringlib" code base (see the SRE sources for
an efficient way to do this in plain C).

moving to (basic) C++ might also be a good idea (in 3.0, perhaps).  is any-
one still stuck with pure C89 these days ?





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


Re: spaces at ends of filenames or directory names on Win32

2006-02-27 Thread rtilley
Roel Schroeven wrote:
> rtilley schreef:
> 
>> This will at least allow me to ID folders that start with 
>> whitespace... from within Windows too :) yet I still cannot rename the 
>> folders after stripping the whitespace... attempting to gives an 
>> [Errno 2] No such file or directory. The strip seems to work right too 
>> according to the prints before and after.
> 
> 
> Does the rename work if try with other names? 

Yes, the script can rename files that have no end whitespace. Also, I 
should note the the Windows GUI cannot rename the files. Same error... 
cannot stat the file. The only way I've been able to rename is through 
the cmd prompt using quotes like this:

ren " bad file with end spaces " good_file_no_end_spaces

I should also note that the code I posted earlier is misleading as 
os.listdir() gets dirs and files... not just dirs as I implied. Here's a 
better example that should get whitespace at either end (and does indeed 
on Mac and Unix... but not Windows)



import os
import os.path
import string

# dirs is actually files and folders, not just folders.
dirs =  os.listdir(os.getcwd())
path = os.getcwd()
print path

for d in dirs:

 # If folder name begins with whitespace.
 if d[0] in string.whitespace:
 print d
 try:
 new_path = os.path.join(path, d.strip())
 old_path = os.path.join(path, d)
 print new_path
 print old_path
 os.renames(old_path, new_path)
 except Exception, e:
 print e

 # If folder name ends with whitespace.
 elif d[-1] in string.whitespace:
 print d
 try:
 new_path = os.path.join(path, d.strip())
 old_path = os.path.join(path, d)
 print new_path
 print old_path
 os.renames(old_path, new_path)
 except Exception, e:
 print e

 # Folder name is OK, so skip it.
 else:
 pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Catch exceptions

2006-02-27 Thread Cruella DeVille
In my application of bookmarks I get a filename as a parameter in one
of my methods. I want to catch the "FileNotFoundException" if the user
types an invalid filename. My code (that doesn't do what I want it to
do - namely print a nicely formatted error message, and no stack trace)

def openFile(self):
try:
return open(self.fileName, self.mode)
except IOError:
print("%s" %("The file was not found"))

But this one never occurs even if I write the name of a non-existing
file.

I also assign a variable, filePointer to a filename (the result of
openFile(self)), with a AttributeError
 if self.filePointer is None:
   raise AttributeError, "Assignment failed"

But I still get this stack trace (or trackback?)

How do I implement a try- except? Is it in my method where i open the
file or when I try to open the file in my "main-method"?

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


Re: str.count is slow

2006-02-27 Thread Ben Cartwright
[EMAIL PROTECTED] wrote:
> It seems to me that str.count is awfully slow.  Is there some reason
> for this?
> Evidence:
>
>  str.count time test 
> import string
> import time
> import array
>
> s = string.printable * int(1e5) # 10**7 character string
> a = array.array('c', s)
> u = unicode(s)
> RIGHT_ANSWER = s.count('a')
>
> def main():
> print 'str:', time_call(s.count, 'a')
> print 'array:  ', time_call(a.count, 'a')
> print 'unicode:', time_call(u.count, 'a')
>
> def time_call(f, *a):
> start = time.clock()
> assert RIGHT_ANSWER == f(*a)
> return time.clock()-start
>
> if __name__ == '__main__':
> main()
>
> ## end 
>
> On my machine, the output is:
>
> str: 0.29365715475
> array:   0.448095498171
> unicode: 0.0243757237303
>
> If a unicode object can count characters so fast, why should an str
> object be ten times slower?  Just curious, really - it's still fast
> enough for me (so far).
>
> This is with Python 2.4.1 on WinXP.
>
>
> Chris Perkins


Your evidence points to some unoptimized code in the underlying C
implementation of Python.  As such, this should probably go to the
python-dev list (http://mail.python.org/mailman/listinfo/python-dev).

The problem is that the C library function memcmp is slow, and
str.count calls it frequently.  See lines 2165+ in stringobject.c
(inside function string_count):

r = 0;
while (i < m) {
if (!memcmp(s+i, sub, n)) {
r++;
i += n;
} else {
i++;
}
}

This could be optimized as:

r = 0;
while (i < m) {
if (s[i] == *sub && !memcmp(s+i, sub, n)) {
r++;
i += n;
} else {
i++;
}
}

This tactic typically avoids most (sometimes all) of the calls to
memcmp.  Other string search functions, including unicode.count,
unicode.index, and str.index, use this tactic, which is why you see
unicode.count performing better than str.count.

The above might be optimized further for cases such as yours, where a
single character appears many times in the string:

r = 0;
if (n == 1) {
/* optimize for a single character */
while (i < m) {
if (s[i] == *sub)
r++;
i++;
}
} else {
while (i < m) {
if (s[i] == *sub && !memcmp(s+i, sub, n)) {
r++;
i += n;
} else {
i++;
}
}
}

Note that there might be some subtle reason why neither of these
optimizations are done that I'm unaware of... in which case a comment
in the C source would help. :-)

--Ben

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


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread John Hunter
> "Derek" == Derek Basch <[EMAIL PROTECTED]> writes:

Derek> Thanks for the reply. I need a scatter plot though. Can
Derek> that be done?

You can set the scale of xaxis and yaxis to either log or linear for
scatter plots

In [33]: ax = subplot(111)

In [34]: ax.scatter( 1e6*rand(1000), rand(1000))
Out[34]: 

In [35]: ax.set_xscale('log')

In [36]: ax.set_xlim(1e-6,1e6)
Out[36]: (9.9995e-07, 100.0)

In [37]: draw()

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


Re: sort one list using the values from another list

2006-02-27 Thread Ron Adam
Scott David Daniels wrote:
> Ron Adam wrote:
>> Ron Adam wrote:

>> This probably should be:
>>
>> def psort11(s1, s2):
>> d = dict(zip(s2,s1))
>> assert len(d) == len(s1)
>> s1[:] = list(d[v] for v in sorted(d))
> 
> You could do this to avoid all of those lookups:
> 
>  def psort_xx(s1, s2):
>  pairs = sorted(dict(zip(s2, s1)).iteritems())
>  assert len(pairs) == len(s1)
>  s1[:] = [s1_value for s2_value, s1_value in pairs]

This version takes twice as long on my system, although the result may 
vary on other platforms. Dictionary lookups are very fast.

Although replacing zip with izip cut the time in half.


def psort11(s1, s2):
 d = dict(izip(s2,s1))
 assert len(d) == len(s1)
 s1[:] = list(d[v] for v in sorted(d))

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


MySQLdb compile error with AMD64

2006-02-27 Thread keith
Hi,

I have been using MySQLdb on a 32-bit processor, no worries. Love it.

I went to install on an AMD64 running the 64-bit version of SUSE 10.0.

I get the following error during the "python setup.py build"

gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -fmessage-length=0 -Wall
-D_FORTIFY_SOURCE=2 -g -fPIC -I/usr/include/mysql
-I/usr/include/python2.4 -c _mysql.c -o
build/temp.linux-x86_64-2.4/_mysql.o -I/usr/include/mysql -g
-march=i586 -mcpu=i686 -fmessage-length=0
`-mcpu=' is deprecated. Use `-mtune=' or '-march=' instead.
_mysql.c:1: error: CPU you selected does not support x86-64 instruction
set
_mysql.c:1: error: CPU you selected does not support x86-64 instruction
set
error: command 'gcc' failed with exit status 1

Any ideas on what I have to do to make this work?

Any help appreciated!

Cheers
Keith


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


Re: type = "instance" instead of "dict"

2006-02-27 Thread Steve Juranich
Cruella DeVille wrote:

> I created a class Dict (not dict), but since it only complicates things
> for me I implemented my program without it.
> 
> when I wrote myDictionary = dictionary.__dict__.iteritems() it worked
> better...
> what does the __dict__ mean?

This is something else entirely and almost *certainly* not what you want. 
Here's the skinny on how to subclass the built-in `dict' type.

class Dict(dict):
  # Your mods go here.

>From your earlier posts, it sounds like you've managed to get a
"classic" (i.e., old, almost deprecated) class.  Change your class
definition to look more like what I have above and things should start
working.

If you're willing to post the code, we could pinpoint the problems much
faster.

-- 
Steve Juranich
Tucson, AZ
USA

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


Re: PEP 354: Enumerations in Python

2006-02-27 Thread I V
Paul Rubin wrote:
> Hmm, I also see the PEP doesn't specify what's supposed to happen with
>
>   Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
>   Solar_system = enum('sun', 'mercury', 'venus', 'earth',)  # etc.
>   print Weekdays.sun == Solar_system.sun
>
> so that's another shortcoming with the PEP.

I think it does, doesn't it? From the PEP:

"Values within an enumeration cannot be meaningfully compared *except
with values from the same enumeration*.  The comparison operation
functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a
value from an enumeration is compared against any value not from the
same enumeration or of a different type." (my emphasis)

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


Re: type = "instance" instead of "dict"

2006-02-27 Thread Cruella DeVille
I created a class Dict (not dict), but since it only complicates things
for me I implemented my program without it.

when I wrote myDictionary = dictionary.__dict__.iteritems() it worked
better...
what does the __dict__ mean?

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


Re: ''.join() with encoded strings

2006-02-27 Thread Sandra-24
Sorry, this was my mistake, I had some unicode strings in the list
without realizing it. I deleted the topic within 10 minutes, but
apparently I wasn't fast enough. You're right join works the way it
should, I just wasn't aware I had the unicode strings in there.

-Sandra

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


Re: Firebird and Python

2006-02-27 Thread Ray Cote
At 5:07 PM +0100 2/27/06, Magnus Lycka wrote:
>
>  I'm still interested
>in experiences from Pythonistas using Firebird--
>especially embedded.

Works great.
Python and Firebird embedded (at least on Windows) is very simple to use.
Not currently using it on other platforms.
--Ray

-- 

Raymond Cote
Appropriate Solutions, Inc.
PO Box 458 ~ Peterborough, NH 03458-0458
Phone: 603.924.6079 ~ Fax: 603.924.8668
rgacote(at)AppropriateSolutions.com
www.AppropriateSolutions.com
-- 
http://mail.python.org/mailman/listinfo/python-list


PyQT: QDialog and QMainWindow interacting with each other

2006-02-27 Thread Fabian Steiner
Hello!

I have got a QMainWindow with a QListView, in which the different 
entries of a database are shown to the user. Moreover it has got a 
QPushButton, so that another QDialog can be opened where the user is 
able to add a new entry:

...

self.connect(self.btnNew, SIGNAL('clicked()'), self.openNewDialog)
...

def openNewDialog(self):
dialog = MyDialog(self)
dialog.show()
self.showListViewItems() # this line isn't recognized


MyDialog is closed by calling MyDialog.accept(). What can I do so that 
self.showListViewItems() is called after MyDialog has been closed?

Thank you for any input!

Cheers,
Fabian Steiner
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bsddb3 database file, are there any unexpected file size limits occuring in practice?

2006-02-27 Thread Klaas
Claudio writes:
> I am on a Windows using the NTFS file system, so I don't expect problems
> with too large file size.

how large can files grow on NTFS?  I know little about it.

> (I suppose it in having only 256 MB RAM available that time) as it is
> known that MySQL databases larger than 2 GByte exist and are in daily
> use :-( .

Do you have more ram now?  I've used berkeley dbs up to around 5 gigs
in size and they performed fine.  However, it is quite important that
the working set of the database (it's internal index pages) can fit
into available ram.  If they are swapping in and out, there will be
problems.

-Mike

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


Re: unicode question

2006-02-27 Thread Edward Loper
Walter Dörwald wrote:
> Edward Loper wrote:
> 
>> [...]
>> Surely there's a better way than converting back and forth 3 times?  Is
>> there a reason that the 'backslashreplace' error mode can't be used 
>> with codecs.decode?
>>
>>  >>> 'abc \xff\xe8 def'.decode('ascii', 'backslashreplace')
>> Traceback (most recent call last):
>>File "", line 1, in ?
>> TypeError: don't know how to handle UnicodeDecodeError in error callback
> 
> The backslashreplace error handler is an *error* *handler*, i.e. it 
> gives you a replacement text if an input character can't be encoded. But 
> a backslash character in an 8bit string is no error, so it won't get 
> replaced on decoding.

I'm not sure I follow exactly -- the input string I gave as an example 
did not contain any backslash characters.  Unless by "backslash 
character" you mean a character c such that ord(c)>127.  I guess it 
depends on which class of errors you think the error handler should be 
handling. :)  The codec system's pretty complex, so I'm willing to 
accept on faith that there may be a good reason to have error handlers 
only make replacements in the encode direction, and not in the decode 
direction.

> What you want is a different codec (try e.g. "string-escape" or 
> "unicode-escape").

This is very close, but unfortunately won't quite work for my purposes, 
because it also puts backslashes before "'" and "\\" and maybe a few 
other characters.  :-/

 >>> print "test: '\xff'".encode('string-escape').decode('ascii')
test: \'\xff\'

 >>> print do_what_i_want("test:\xff'")
test: '\xff'

I think I'll just have to stick with rolling my own.

-Edward

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


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Thanks for the reply. I need a scatter plot though. Can that be done?

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-27 Thread Roel Schroeven
rtilley schreef:
> This will at least allow me to ID folders that start with whitespace... 
> from within Windows too :) yet I still cannot rename the folders after 
> stripping the whitespace... attempting to gives an [Errno 2] No such 
> file or directory. The strip seems to work right too according to the 
> prints before and after.

Does the rename work if try with other names? Maybe the problem is not 
the whitespace; maybe Windows can't rename the folder because some 
process, possibly your program, has an open handle to a file or 
directory under your folder? Unix-systems are able to handle that 
easily, but Windows doesn't.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: type = "instance" instead of "dict"

2006-02-27 Thread Kent Johnson
Cruella DeVille wrote:
> So what you are saying is that my class Dict is a subclass of Dict, and
> user defined dicts does not support iteration?

I don't know what your class Dict is, I was guessing. The built-in is 
dict, not Dict.
> 
> What I'm doing is that I want to write the content of a dictionary to a
> file, and send the dictionary (favDict) as a parameter like this:
> favDict = Dict() <-- my own class (or not?)

Is this actual code or are you typing from memory?

> # put things in favDict (works fine)
> fileToWrite.writeFile(favDict) # AttributeError: Dict instance has no
> attribute 'itervalues'

What version of Python are you using? itervalues() is in Python 2.2 and 
later.

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


Re: Best python module for Oracle, but portable to other RDBMSes

2006-02-27 Thread Jonathan Gardner
I've never seen the points of those tools. Just lay it out on paper or
document it somewhere. Be consistant with your naming scheme and it
shouldn't be hard to see the relations. If found that the people who
don't understand how tables should relate to one another are also the
same people who don't understand the special arrows DBAs like to use.

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


Re: Kill forked processes

2006-02-27 Thread kmkz
I didn't mean that you'd have to write it for me, I meant that if what
you said works (atexit, signal) I will paypal you $10 for your generous
contribution to my project.

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


Re: Matplotlib logarithmic scatter plot

2006-02-27 Thread Bas
Try this, don't know if this works for al versions:

from pylab import *
x=10**linspace(0,5,100)
y=1/(1+x/1000)
loglog(x,y)
show()

If you only need a logarithm along one axis you can use semilogx() or
semilogy(). For more detailed questions go to the matplotlib mailing
list.

Cheers,
Bas

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


Re: expat

2006-02-27 Thread Jarek Zgoda
Katja Suess napisał(a):

> may I have a hint what the problem is in my situation?
> Is it a syntax error in sweetone.odt or in xml.parsers.expat?
> Same problem with different file instead of sweetone.odt means that it's
> not the file that has a syntax error.
> xml.parsers.expat is a standard module that probably has no errors.
> So what could cause this error message??

Malformed XML document, perhaps. This may be anything, that expat
doesn't like (i.e. wrong encoding, cp1252 declared as latin-1, document
declared as utf-8 but with BOM, and so on).

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: expat

2006-02-27 Thread Fredrik Lundh
Katja Suess wrote:

> may I have a hint what the problem is in my situation?
> Is it a syntax error in sweetone.odt or in xml.parsers.expat?

> xml.parsers.expat.ExpatError: syntax error: line 1, column 0

it's a problem with the file you're parsing (either because it's not a
valid XML file, or because it's encoded in some non-standard way).

can you post the first few lines from that file ?





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


Matplotlib logarithmic scatter plot

2006-02-27 Thread Derek Basch
Can anyone give any suggestions on how to make a logarithmic (base 10)
x and y axis (loglog) plot in matplotlib? The scatter function doesn't
seem to have any log functionality built into it.

Thanks,
Derek Basch

P.S. I suck at math so feel free to make me feel stupid if it is really
easy to do :).

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


str.count is slow

2006-02-27 Thread chrisperkins99
It seems to me that str.count is awfully slow.  Is there some reason
for this?
Evidence:

 str.count time test 
import string
import time
import array

s = string.printable * int(1e5) # 10**7 character string
a = array.array('c', s)
u = unicode(s)
RIGHT_ANSWER = s.count('a')

def main():
print 'str:', time_call(s.count, 'a')
print 'array:  ', time_call(a.count, 'a')
print 'unicode:', time_call(u.count, 'a')

def time_call(f, *a):
start = time.clock()
assert RIGHT_ANSWER == f(*a)
return time.clock()-start

if __name__ == '__main__':
main()

## end 

On my machine, the output is:

str: 0.29365715475
array:   0.448095498171
unicode: 0.0243757237303

If a unicode object can count characters so fast, why should an str
object be ten times slower?  Just curious, really - it's still fast
enough for me (so far).

This is with Python 2.4.1 on WinXP.


Chris Perkins

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


expat

2006-02-27 Thread Katja Suess
Hi,
may I have a hint what the problem is in my situation?
Is it a syntax error in sweetone.odt or in xml.parsers.expat?
Same problem with different file instead of sweetone.odt means that it's not 
the file that has a syntax error.
xml.parsers.expat is a standard module that probably has no errors.
So what could cause this error message??

Traceback (most recent call last):
  File "mytest.py", line 5, in ?
r = c.convert(s, 'HTML','sweetone.odt').decode('base64')
  File "/Users/katjasuess/links/soffice/python-core/lib/xmlrpclib.py", line 
1029, in __call__
return self.__send(self.__name, args)
  File "/Users/katjasuess/links/soffice/python-core/lib/xmlrpclib.py", line 
1316, in __request
verbose=self.__verbose
  File "/Users/katjasuess/links/soffice/python-core/lib/xmlrpclib.py", line 
1080, in request
return self._parse_response(h.getfile(), sock)
  File "/Users/katjasuess/links/soffice/python-core/lib/xmlrpclib.py", line 
1214, in _parse_response
p.feed(response)
  File "/Users/katjasuess/links/soffice/python-core/lib/xmlrpclib.py", line 
528, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: syntax error: line 1, column 0

Regards, Katja
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spaces at ends of filenames or directory names on Win32

2006-02-27 Thread rtilley
This will at least allow me to ID folders that start with whitespace... 
from within Windows too :) yet I still cannot rename the folders after 
stripping the whitespace... attempting to gives an [Errno 2] No such 
file or directory. The strip seems to work right too according to the 
prints before and after.

import os
import os.path
import string

dirs =  os.listdir(os.getcwd())
path = os.getcwd()
##print path

for d in dirs:
 # If the first space in a folder name is whitespace.
 if d[0] in string.whitespace:
##print d
 try:
 new_path = os.path.join(path, d.strip())
 old_path = os.path.join(path, d)
 print new_path
 print old_path
 os.renames(old_path, new_path)
 except Exception, e:
 print e
 else:
 pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type = "instance" instead of "dict"

2006-02-27 Thread Cruella DeVille
So what you are saying is that my class Dict is a subclass of Dict, and
user defined dicts does not support iteration?

What I'm doing is that I want to write the content of a dictionary to a
file, and send the dictionary (favDict) as a parameter like this:
favDict = Dict() <-- my own class (or not?)
# put things in favDict (works fine)
fileToWrite.writeFile(favDict) # AttributeError: Dict instance has no
attribute 'itervalues'
where fileToWrite is a filepointer in write-mode

Can I send a dictionary as a parameter the way I do here?

And another issue: what does the "self" - thing mean? I'm familiar with
java and php (is it like the java  and php- this?)

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


newbie

2006-02-27 Thread Brain Murphy
I have some questions, 1) I am trying to have multiple def's but it is not working.  for instance, i am using the tutoreals and am trying to combine the phone book as well as the grades..ect so that it would look somthing like this:     def print_options():      print "options:"      print " 'p' print options"      print " 'g' grades"      print " 'b' phonebook"      print " 'q' quit"  choice ="p"  while choice != "q":      if choice == "g": 
     def print_menu():  ...ect  what am i doing wrong.     also i have heard that there are no crackers using python why is this??     Brian
		Win a BlackBerry device from O2 with Yahoo!. Enter now.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: type = "instance" instead of "dict"

2006-02-27 Thread Kent Johnson
Cruella DeVille wrote:
> I'm trying to implement a bookmark-url program, which accepts user
> input and puts the strings in a dictionary. Somehow I'm not able to
> iterate myDictionary of type Dict{}
> 
> When I write print type(myDictionary) I get that the type is
> "instance", which makes no sense to me. What does that mean?

Maybe you have an instance of UserDict instead of a built-in dict?

  >>> type({})

  >>> from UserDict import UserDict
  >>> type(UserDict())


UserDict.UserDict is not iterable, though you can still use
   for k in myDictionary.keys()

There is also UserDict.IterableUserDict which does support iteration.

I don't think there is much reason to use UserDict in modern Python as 
dict can be subclassed.

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


Re: Use of __slots__

2006-02-27 Thread MrJean1
An example of the RARE use case may be this particular one

  

/Jean Brouwers

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


PDB on a large threaded application (QMTest)

2006-02-27 Thread [EMAIL PROTECTED]
Hi,
I'm trying to debug QMTest from Code Sourcery with PDB from inside
Emacs.
My problem is that without PDB, I have no problem, but when I'm using
PDB,
I get exceptions thrown.

Has anyone else tried using PDB on QMTest?
My python is 2.2, and QMTest is 2.0.3.

Thanks / Claes

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


Re: new wooden door step - fixing and finishing

2006-02-27 Thread robin
Jeffrey Schwab <[EMAIL PROTECTED]> wrote:

>> I was wondering about treating it
>> wilth liberal amounts of Teak Oil or similar...
>
>Some people, when confronted with a problem, think "I know, I?ll use 
>Teak Oil."  Now they have two problems.

+1 QOTW

BTW, I integrated a similar line into one of my readings (I sideline
as a poet), a piece entitled "Advice For Modern Living". Goes like
this:

"When confronted with a conflict some people go to a solicitor for
advice. Now they have two problems."

-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different ways to strip strings

2006-02-27 Thread rtilley
Kent Johnson wrote:
> So...
> s.strip() gets a bound method object from the class and calls it with no 
> additional argument.
> str.strip(s) gets an unbound method object from the class and calls it, 
> passing a class instance as the first argument.
> 
> Kent

Thank you Kent. That's a very informative explanation. It makes sense too :)
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie : econometrics in python

2006-02-27 Thread MARK LEEDS



i've used python in the past but only for data 
processing, writing to files, midifying files,
reading from files. now, my boss wants me to do some econometrics using python.
 
would anyone who has done this ( var, vecm, 
cointegration, ols, kalman filter whatever ) mind
sending me some sample code that i could use as a 
template.
 
i've spent 2 days, going through numpy, scipy, 
pytrix etc and i still
can't figure it out. thanks.
 
        
                
                
                
mark
-- 
http://mail.python.org/mailman/listinfo/python-list

type = "instance" instead of "dict"

2006-02-27 Thread Cruella DeVille
I'm trying to implement a bookmark-url program, which accepts user
input and puts the strings in a dictionary. Somehow I'm not able to
iterate myDictionary of type Dict{}

When I write print type(myDictionary) I get that the type is
"instance", which makes no sense to me. What does that mean?
Thanks

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


Re: How many web framework for python ?

2006-02-27 Thread robin
Steve Holden <[EMAIL PROTECTED]> wrote:

>Damn. More reading ...

Even more reading as of tomorrow, when I get my Web Application
Framework article up on my blog.

Even listing the vast number of frameworks & toolkits out there is
daunting, so I figured I may as well share my own outlook.

And FWIW, I have abandoned my own contribution, so that's one less out
in the wild!

-
robin
noisetheatre.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 354: Enumerations in Python

2006-02-27 Thread Terry Reedy

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote

> A list of X is like a box containing X,

and in another post

> A list is a container.

I think it is misleading, if not wrong, to refer to Python collections as 
'containers', 'boxes', or similar.  A object in a box cannot be in another 
disjoint box.  A object in a box cannot be in the box a second time.  But 
both 'cannot's are 'can's for Python objects in respect to Python 
collections.  So, bad metaphor.

(Yes, CPython implements the association of list positions with objects by 
putting an instance/copy of the id/address of the implemented object 'in' a 
particular position in a block of memory, but even then, the object itself 
in not 'in' the list block.  And that is so because of the need for 
multiple associations for each object.  Beside which, we are discussing the 
abstract notion of the empty enumeration.)

> You can take the elements away and still have the container left.

I would say instead that you have an empty roster ;-)
I suspect that the notion of empty  set was once controversial.
It certainly gives some set theory beginners a pause.

> But an enum is not a container.

But neither, I claim, is a list.  So to me, you have not drawn a 
distrinction, and therefore no justification for different treatment.

To me, the enum proposal is for an immutable ordered set (rather than 
multiset) with a friendly interface.  So, like other posters, I have no 
problem with one that is empty.  I also expect enum() to return such 
because that is GvR policy for builtin type constructors.

To me, 'I can't think of a use for X' is insufficient reason to prohibit X 
in Python.  You also need an 'X is tricky/difficult to implement' or 'X is 
harmful' claim.

Terry Jan Reedy



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


Re: making 'utf-8' default codec

2006-02-27 Thread Jarek Zgoda
Jorge Godoy napisał(a):

>>Bad idea. You may accidentally break some libraries that depend on ASCII
>>being default & standard.
> 
> And what would those produce as output when fed with unicode data?  How would
> they handle this input?  IMVHO nothing should rely on having a standard
> charset as input.  If it is required, then the library should set it up by
> itself: explicit is better than implicit.

Besides that, changing default encoding will make program nearly
absolutely unportable as Python by default installs nearly everywhere
with ASCII as default encoding (with iSeries being the only exception
known to me).

-- 
Jarek Zgoda
http://jpa.berlios.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different ways to strip strings

2006-02-27 Thread Kent Johnson
Crutcher wrote:
> It is something of a navel (left over feature). "xyz".strip() is (I
> think) newer than string.strip()
> 
Yes, but the question as written was about str.strip() which is an 
unbound method of the str class, not string.strip() which is a 
deprecated function in the string module.

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


Re: different ways to strip strings

2006-02-27 Thread Kent Johnson
rtilley wrote:
> s = ' qazwsx '
> 
> # How are these different?
> print s.strip()
> print str.strip(s)

They are equivalent ways of calling the same method of a str object.
> 
> Do string objects all have the attribute strip()? If so, why is 
> str.strip() needed? Really, I'm just curious... there's a lot  don't 
> fully understand :)

Actually strip is an attibute of the str class. This is generally true - 
methods are class attributes.

When you look up an attribute on an instance, if the instance does not 
have the attribute, it is looked up on the class. In the case of 
methods, there is some magic that converts the attribute to a 'bound 
method' - an object that wraps the method and the instance. When you 
call the bound method, the actual method is passed the instance (as the 
self parameter) plus whatever other arguments you have given it.

For example, here is a simple class with a single method:

  >>> class spam(object):
  ...   def ham(self, eggs):
  ... print eggs
  ...

Here is a normal method call:
  >>> s=spam()
  >>> s.ham('Ha!')
Ha!

What may not be immediately apparent is that s.ham('Ha!') is two 
separate operations. First is the attribute lookup of s.ham, which 
returns the bound method:
  >>> s.ham
>

Second is the actual call of the bound method, which forwards to the 
function defined in the class definition:
  >>> f = s.ham
  >>> f('Ha!')
Ha!


But that's only half the story. Since ham is a class attribute, it can 
be looked up on the class directly. Since there is no instance 
associated with the lookup, the result is an 'unbound method' object:

  >>> spam.ham


To call this method, you have to provide the instance as the first argument:
  >>> f=spam.ham
  >>> f(s, 'Ha!')
Ha!

So...
s.strip() gets a bound method object from the class and calls it with no 
additional argument.
str.strip(s) gets an unbound method object from the class and calls it, 
passing a class instance as the first argument.

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


Re: Waiting for Connection

2006-02-27 Thread D
Thanks Kent!  update_idletasks()  does exactly what I needed, which as
you mentioned was just to give it enough time to reconfigure the
button.

Doug

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


converting binary data

2006-02-27 Thread piotr maliński
I have a game file described here: http://iesdp.gibberlings3.net/ieformats/itm_v1.htm and I'm trying to read all the data:
plik = open('bow08.itm', 'rb')

try:

        tekst = plik.read()

finally:

        plik.close()



# char array - works

print tekst[0x0004:0x0004+4]

# resref - works

print tekst[0x003a:0x003a+8]



#dword - binary something, doesn't work
print tekst[0x004c:0x004c+4]##The dword and many other variables are binary code and I don't know how to convert them into "normal" data. NearInfinity, app written in Java converts dword and friends in this way:
##public static int convertInt(byte buffer[], int offset)

  {

    int value = 0;

    for (int i = 3; i >= 0; i--)

      value = (value << 8) | (buffer[offset + i] & 0xFF);

    return value;

  }
##How to pythonize this code, or make something in python to read the data from Baldurs Gate files ? :)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: sort one list using the values from another list

2006-02-27 Thread Scott David Daniels
Ron Adam wrote:
> Ron Adam wrote:
>> Alex Martelli wrote:
>>> Ron Adam <[EMAIL PROTECTED]> wrote:
>>>...
 Considering the number time I sort keys after getting them, It's the 
 behavior I would prefer.  Maybe a more dependable dict.sortedkeys() 
 method would be nice.  ;-)
>>>
>>> sorted(d) is guaranteed to do exactly the same thing as sorted(d.keys())
>>> AND to be faster (would be pretty weird if it weren't faster...!).
>>>
>>> E.g., ...:
>>>
>>> helen:~ alex$ python -mtimeit -s'd=dict(enumerate("tarazoplay"))'
>>> 'sorted(d.keys())'
>>> 10 loops, best of 3: 6.82 usec per loop
>>>
>>> helen:~ alex$ python -mtimeit -s'd=dict(enumerate("tarazoplay"))'
>>> 'sorted(d)'
>>> 10 loops, best of 3: 5.98 usec per loop
>>>
>>>
>>> Alex
>>
>>
>> Yes, it did decrease it.  And simplified it as well. ;)
>>
>> def psort11(s1, s2):
>> d = dict(zip(s2, s1))
>> assert len(d) == len(s1)
>> sorted(d)
>> s1[:] = d.values()

Dictionaries are not ordered, the "sorted" line does nothing except produce
a sorted list of the dictionary's keys which is ignored.

> This probably should be:
> 
> def psort11(s1, s2):
> d = dict(zip(s2,s1))
> assert len(d) == len(s1)
> s1[:] = list(d[v] for v in sorted(d))

You could do this to avoid all of those lookups:

  def psort_xx(s1, s2):
  pairs = sorted(dict(zip(s2, s1)).iteritems())
  assert len(pairs) == len(s1)
  s1[:] = [s1_value for s2_value, s1_value in pairs]


-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem(s) with import from parent dir: "from ../brave.py import sir_robin"

2006-02-27 Thread Magnus Lycka
per9000 wrote:
> ...and there was much rejoicing... Even better, thanks - you guys are
> the best.
> 
> import string, time, sys
> sys.path.append("../../py_scripts")
> 
> Works just nice, and yes, I removed the env.variable before I tried it
> :-D

The *right* thing to do might be to install the python libs
in the correct places. Probably under the site-packages
directory. Take a look at the distutils package.

http://www.python.org/doc/lib/module-distutils.html

It can even build Windows installers and RPMs.

These days there are also spiffy things, such as Python eggs,
ez_setup.py, PYPI and whatever it's called, but I haven't
tried those things.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: different ways to strip strings

2006-02-27 Thread Crutcher
It is something of a navel (left over feature). "xyz".strip() is (I
think) newer than string.strip()

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


Re: different ways to strip strings

2006-02-27 Thread Crutcher
It is something of a navel (left over feature). "xyz".strip() is (I
think) newer than string.strip()

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


different ways to strip strings

2006-02-27 Thread rtilley
s = ' qazwsx '

# How are these different?
print s.strip()
print str.strip(s)

Do string objects all have the attribute strip()? If so, why is 
str.strip() needed? Really, I'm just curious... there's a lot  don't 
fully understand :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ''.join() with encoded strings

2006-02-27 Thread Fredrik Lundh
"Sandra-24" wrote:

> I'd love to know why calling ''.join() on a list of encoded strings
> automatically results in converting to the default encoding. First of
> all, it's undocumented, so If I didn't have non-ascii characters in my
> utf-8 data, I'd never have known until one day I did, and then the code
> would break. Secondly you can't override (for valid reasons) the
> default encoding, so that's not a way around it. So ''.join becomes
> pretty useless when dealing with the real (non-ascii) world.

if all strings in a sequence are encoded strings (byte buffers), join does
the right thing.

if all strings in a sequence are Unicode strings, join does the right thing.

if all strings are ascii strings, join does the right thing.

the only way to mess up is to mix byte buffers containing encoded data
with decoded strings.  the solution is simple: make sure to *decode* all
data you're using, *before* using it.





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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-27 Thread Magnus Lycka
Claudio Grondi wrote:
> I mean, that using time.clock() solves the problem, because the output 
> of the following code:

On Windows that it. At least on Linux and Solaris, time.clock() returns
CPU time. If time.clock() returns significantly different values before
and after time.sleep(1), there's something seriously broken in sleep on
such platforms.

Anyway, what is the perceived problem?
A) That sleep takes too much time, or
B) that time measurements don't work right?

If A), the problem is solved if what really happens is clock-setting
glitches.

If B), I see two options:

- Use some proper external and stable time source. (It should be
   fairly trivial to build a little socket server that returns
   timestamps from a single source if no other source is available.
   See http://www.python.org/doc/lib/socket-example.html )

- If the clock-resetting is actually warranted because the system
   clocks lag so much, make sure this resetting is made more often,
   so that it never gets so much off track.

Unless hardware is broken, or the clocks are changed so that they
get more and more off track with time as the rest of us perceives
it, there ought to be "negative sleeps" as well as sleeps much
longer than 2 seconds. Of course, if you only look for longer sleeps
than 2 secs, you won't see them.

BTW, finding "negative sleeps" pretty much proves that it's the
clocks, not actual delays, that cause problems...

I guess a typical cause of clock setting problems is that one has
two disagreeing time sources that both try to set the system times
of the computers...

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


Re: ls files --> list packer

2006-02-27 Thread Magnus Lycka
kpp9c wrote:
> that is nice but the little further wrinkle, which i have no idea
> how to do, would be to have the contents of each directory packed into
> a different list since you have no idea before hand how many lists
> you will need (how many subdirs you will enounter)  ... well that is
> where the hairy part comes in...

What's the problem? If you'll get an unknown bundle of objects in a
program, you just put them in a container. A list or a dict will do
fine. Have a look at the Python tutorial.

You get a file list for each directory from os.walk. You either keep
a list called "directories" and for each turn in the loop, you do
"directories.append((dir, sound_files))", or you have a dict called
"directories", and do "directories[dir] = sound_files" in the loop.

Something like this untested code:

def isSoundFile(x):
# home work

dirs = {}
root = raw_input('start directory')
for dir, dummy, files in os.walk(root):
 dirs[dir] = [x for x in files if isSoundFile(x)]

for dir in sorted(dirs):
 print dir
 for fn in dirs[dir]:
 print "\t", fn
 print
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ''.join() with encoded strings

2006-02-27 Thread Diez B. Roggisch
Sandra-24 wrote:

> I'd love to know why calling ''.join() on a list of encoded strings
> automatically results in converting to the default encoding. First of
> all, it's undocumented, so If I didn't have non-ascii characters in my
> utf-8 data, I'd never have known until one day I did, and then the code
> would break. Secondly you can't override (for valid reasons) the
> default encoding, so that's not a way around it. So ''.join becomes
> pretty useless when dealing with the real (non-ascii) world.
> 
> I won't miss the str class when it finally goes (in v3?).
> 
> How can I join my encoded strings effeciently?

By not mixing unicode objects with ordinary byte strings. Use

u''.join(some_unicode_objects)

to get a joined unicode object.

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


Re: making 'utf-8' default codec

2006-02-27 Thread Jorge Godoy
Jarek Zgoda <[EMAIL PROTECTED]> writes:

> Bad idea. You may accidentally break some libraries that depend on ASCII
> being default & standard.

And what would those produce as output when fed with unicode data?  How would
they handle this input?  IMVHO nothing should rely on having a standard
charset as input.  If it is required, then the library should set it up by
itself: explicit is better than implicit.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode question

2006-02-27 Thread Walter Dörwald
Edward Loper wrote:

> [...]
> Surely there's a better way than converting back and forth 3 times?  Is
> there a reason that the 'backslashreplace' error mode can't be used with 
> codecs.decode?
> 
>  >>> 'abc \xff\xe8 def'.decode('ascii', 'backslashreplace')
> Traceback (most recent call last):
>File "", line 1, in ?
> TypeError: don't know how to handle UnicodeDecodeError in error callback

The backslashreplace error handler is an *error* *handler*, i.e. it 
gives you a replacement text if an input character can't be encoded. But 
a backslash character in an 8bit string is no error, so it won't get 
replaced on decoding.

What you want is a different codec (try e.g. "string-escape" or 
"unicode-escape").

Bye,
Walter Dörwald

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


''.join() with encoded strings

2006-02-27 Thread Sandra-24
I'd love to know why calling ''.join() on a list of encoded strings
automatically results in converting to the default encoding. First of
all, it's undocumented, so If I didn't have non-ascii characters in my
utf-8 data, I'd never have known until one day I did, and then the code
would break. Secondly you can't override (for valid reasons) the
default encoding, so that's not a way around it. So ''.join becomes
pretty useless when dealing with the real (non-ascii) world.

I won't miss the str class when it finally goes (in v3?).

How can I join my encoded strings effeciently?

Thanks,
-Sandra

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


Re: Unicode and MoinMoin

2006-02-27 Thread Fredrik Lundh
Neil Hodgson wrote:

> > The only issue I'm having relates to Unicode. MoinMoin and python are
> > pretty unforgiving about files that contain Unicode characters that
> > aren't included in the coding properly. I've spent hours reading about
> > Unicode, and playing with different encoding/decoding commands, but at
> > this point, I just want a hacky solution that will ignore the
> > improperly coded characters or replace them with placeholders.
>
> Call the codec with the errors argument set to "ignore" or "replace".
>
>  >>> unicode('AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G.
> A. \x96 For references see blahblah.\n\n\n-\n\n', 'utf8')
> Traceback (most recent call last):
>File "", line 1, in ?
>File "c:\python24\lib\encodings\utf_8.py", line 16, in decode
>  return codecs.utf_8_decode(input, errors, True)
> UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 58:
> unexpected code byte
>  >>> unicode('AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G.
> A. \x96 For references see blahblah.\n\n\n-\n\n', 'utf8', 'replace')
> u'AUTHOR: blahblah\n\nTITLE: Reading Course Readings... G. A. \ufffd For
> references see blahblah.\n\n\n-\n\n'
>
> BTW, its probably in Windows-1252 where it would be a dash.
> Depending on your context it may pay to handle the exception instead of
> using "replace" and attempt interpreting as Windows-1252.

here's one way to explicitly deal with 1252 gremlins:

http://effbot.org/zone/unicode-gremlins.htm





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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-27 Thread Magnus Lycka
Peter Hansen wrote:
> Magnus Lycka wrote:
> 
>> With an operating system such as Windows, this is
>> probably something you can expect to happen, although
>> I'm surprised if such long lag times as 200 s are typical.
> 
> No way.  I mean, I'm the biggest critic of Windows operating systems 
> when used in realtime environments (at least with my customers), but 
> there's no way you should "probably expect a 200s delay to happen".

You know Peter, quotations are typically used when you actually
quote someone, not when you make your own interpretation of what
they meant.

If I write that it would surprise me if you are often hit by
meteorites, would the quote then be "you'll probably get hit
by meteorites"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Firebird and Python

2006-02-27 Thread Magnus Lycka
Jarek Zgoda wrote:

> They just hired Jim Starkey. Perhaps MySQL AB hopes he will write a
> transactional engine for MySQL, as he previously wrote one for Interbase
> (which is known to be one of the best a man could imagine).
> 
> Anyway, we got far off topic, so we better go somewhere else.

Ok, to bring us a bit back on track again, I'm
curious about Firbird, since we want an embedded
SQL engine for some automated testing tasks, and
SQLite is a bit too lite for our needs.

We use our own DB API, so we won't really need any
Python DB-API adapter, but I'm still interested
in experiences from Pythonistas using Firebird--
especially embedded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ls files --> list packer

2006-02-27 Thread Scott David Daniels
kpp9c wrote:
> Thank you... i was looking in the wrong place cause all i found was
> this relatively useless doc:
> http://docs.python.org/lib/module-os.html
> which says almost nothing.
> 
In one of its subsections, cleverly named "Files and Directories",
I see a nice description of listdir.

 http://docs.python.org/lib/os-file-dir.html

You also might want to read about os.walk in the same page.
In the os.path module you can see more path name manipulations.
If you intend to know a language, you should read its manuals
fast; what you want is a vague impression where information
lives and what information is there.  Maybe half a year later
do it again.  After that every couple of years often suffices.
At the very least, go through the full tutorial, read docs on
the "obvious" modules for everyone and for your particular
area of endeavor, and then on a snacking basis get yourself
through the rest unless you decide that you never want to deal
with, for example, unix-specific services or internet protocols.

Don't expect to acquire _any_ language with "just in time" (JIT)
techniques.  Perhaps JIT works for magic.  When you acquire a
language with JIT, you miss the subtleties of the language.
You will be doomed to writing the same kinds of programs in every
language you touch ("writing Fortran in Algol" is what we used to
call it).  I've worked on code that was Java-in-Python, and it was
frustratingly hard to understand.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Waiting for Connection

2006-02-27 Thread Kent Johnson
D wrote:
> I am trying to do the following using Python and Tkinter:
> 
> 1)  Display a window with 1 button
> 2)  When user clicks the button, Python attempts to call a function
> that opens a socket and listens for a connection - what I want to do
> is, if the socket has been successfully opened and the system is
> waiting for a connection, to turn the button green.
> 
> The problem I'm having is when the button is clicked, the color never
> changes and the application "locks up" until the remote end connects
> and disconnects.  Where can I put the button configuration statement so
> that it will turn green to indicate the socket was opened successfully?

You need to give some time to the GUI so it can draw. A minimal solution 
is to call root.update_idletasks() after you set the button to green. If 
you want the GUI to be responsive you have to run the socket in a 
separate thread; this recipe may give you some help though it may be 
more complex than you need:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

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


Re: Use of __slots__

2006-02-27 Thread Don Taylor
Alex Martelli wrote:


> meant for extremely RARE use, and only by very advanced programmers who
> fully know what they're doing

Yea, from the table of my memory I ’ll wipe away all trivial fond 
records of __slots__

(Bet you wish Mark Lutz had not mentioned it in Learning Python ...)

Don.

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


  1   2   >