Re: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and...

2009-12-04 Thread Steven D'Aprano
On Thu, 03 Dec 2009 19:59:30 -0500, David Robinow wrote:


> I've never heard of mbox. Is it written in Python?

It is a file format used for storing email. Wikipedia is your friend:

http://en.wikipedia.org/wiki/Mbox


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


Manyfile Processing

2009-12-04 Thread user
Hey,

 sorry if i bother you with a beginners question but i have an issue
with processing a bunch of files. They are some arithmetic lists the
processing of one file is an easy task but how do i process many files?
I tried reading that files in to a list and looping over the list
elements but the function won't accept any arguments other than a string.

I would appreciate if you could help me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-12-04 Thread Steven D'Aprano
On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote:

> Brad Harms  writes:
...
>> 1.) "Regular" attributes, ie. those that are shortcuts to items in the
>> directly associated object's __dict__,
> 
> I don't know what you mean by “shortcuts to items”. The names are looked
> up in dictionaries; where do shortcuts play a part?
> 
> Try “instance attribute”, as distinct from “class attribute”.

Not all such attributes are actually found in instance.__dict__.


>>> class Example(object):
... __slots__ = 'spam'
...
>>> x = Example()
>>> y = Example()
>>> x.spam = 23
>>>
>>> x.__dict__['spam']
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Example' object has no attribute '__dict__'
>>> x.spam
23
>>> y.spam
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: spam


So it is possible to have per-instance attributes that don't live inside 
the instance __dict__.



>> 2.) Attributes whose values are determined or assigned dynamically by
>> indirectly calling a function (like properties and instancemethods)
> 
> Yes, the term “property” seems to do what you want.

Or dynamic attributes returned by __getattr__ or __getattribute__.



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


Re: Feature request: String-inferred names

2009-12-04 Thread Brad Harms
On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote:

> Brad Harms  writes:
> 
>> Anyway, it looks like the docs agree with you
>> (http://docs.python.org/glossary.html#term-attribute), so I'm not going
>> to argue.
> 
> That's good, because the terms are quite well established in Python
> terminology.

I'm just saying, if the official documentation defines the term 
"attribute" thusly, it would be silly of me to continue using my own made-
up term that means pretty much the same thing.

> 
>> However, for the purpose of clean communication, I'd still like to have
>> terms that refer specifically to:
>>
>> 1.) "Regular" attributes, ie. those that are shortcuts to items in the
>> directly associated object's __dict__,
> 
> I don't know what you mean by “shortcuts to items”. The names are looked
> up in dictionaries; where do shortcuts play a part?
> 
> Try “instance attribute”, as distinct from “class attribute”.
> 
>> 2.) Attributes whose values are determined or assigned dynamically by
>> indirectly calling a function (like properties and instancemethods)
> 
> Yes, the term “property” seems to do what you want.

I wasn't asking what you call any object or any /kind/ of object. I was 
asking for a term (noun?) that describes the WAY the object is accessed 
as an attribute of an instance, with the connotation that the value of 
the attribute would be calculated dynamically (by calling a function) at 
the time the attribute was accessed. Note that the value does not have to 
exist in ANY __dict__ anywhere, it could, for example, be calculated by 
object.__getattribute__.

Example: 

>>> obj.attr

Without knowing what "obj" is or what "attr" is as it pertains to obj, 
but knowing that "attr" does not actually a key in obj.__dict_,_ and that 
its value has to be determined by some other means, what do you call the 
thing on the code line above? That is what I'm trying to find out. (HINT: 
Don't think about how the Python interpreter parses it or how the value 
is eventually determined. That's not relevant. Just understand that the 
value does not come directly from obj.__dict__.)

By the way, a "property" is an object of type __builtin__.property. A 
property with a reference in an attribute of a class /does/ call a 
function when you try to access that property as an attribute of the 
class's instances. However, properties are not the only objects that have 
this behavior, so calling objects that behave in this way is ambiguous. I 
think the actual, general term for such an object is "data descriptor," 
or just "descriptor." (http://docs.python.org/glossary.html#term-
descriptor)

> 
> The value of an instance method is *not* determined dynamically: its
> value is a function, and that value is no more dynamic than any other
> attribute of the instance.

That is incorrect. Indirectly accessing an instancemethod of a class 
through an instance of that class will trigger the descriptor behavior of 
the instancemethod type. This produces a new object, another 
instancemethod, that is bound to the instance through which it was 
accessed. It's a mouthful to say, but it is sufficiently accurate.

Heck, just look at this:

>>> class Foo(object):
... def spam(self): pass
...
>>> foo = Foo()
>>> foo.spam
>
>>> Foo.spam

>>> foo.spam is Foo.spam
False
>>> foo.spam == Foo.spam
False
>>> Foo.spam.__get__(foo, Foo)
>
>>> Foo.__dict__["spam"].__get__(foo, Foo)
>
>>> Foo.__dict__["spam"].__get__(foo, Foo) is foo.spam
False
>>> Foo.__dict__["spam"].__get__(foo, Foo) == foo.spam
True

Also note the fact that Foo.spam is an _instancemethod_ object and not 
just a function, even though it was defined as "just a function" in the 
class body. That's because function objects are descriptors as well; it 
lets them produce unbound instancemethods. I'm not precisely sure how 
this works, though. I think it only happens when the metaclass of a class 
processes the functions in the class block.

> 
>> 3.) Attributes that are read from an object with regular .dot syntax,
>> but are actually attributes (in the sense of #1 above) of the __dict__
>> of the object's class.
> 
> This is a “class attribute” as distinct from an “instance attribute”.
>

I know it's called that, but I was talking more about the fact of it 
being accessed through an instance of the class rather than 


> The distinction isn't often worth knowing, though, so you'll probably
> still have to explain it when you use it.

I beg to differ. For one thing, it affects descriptors.


Anyway, these metadiscussions are starting to give me headaches. Let's 
talk about something more interesting...


PS. I'm truly sorry once again for using email addresses and names 
inconsistently. I really am trying to solve the problem. I'm going to try 
accessing the list via comp.lang.python and Pan (newsreader for Gnome) 
for a while. Hopefully it will help.

-- 
Brad Harms -- http://alphaios.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Manyfile Processing

2009-12-04 Thread Diez B. Roggisch

u...@domain.invalid schrieb:

Hey,

 sorry if i bother you with a beginners question but i have an issue
with processing a bunch of files. They are some arithmetic lists the
processing of one file is an easy task but how do i process many files?
I tried reading that files in to a list and looping over the list
elements but the function won't accept any arguments other than a string.

I would appreciate if you could help me.


for filename in list_of_filenames:
do_something_with_one_file(filename)

Unless you disclose more of what your actual code looks like, there 
isn't more we can do.


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


Re: Feature request: String-inferred names

2009-12-04 Thread Brad Harms
On Fri, 04 Dec 2009 09:00:42 +, Steven D'Aprano wrote:
> Not all such attributes are actually found in instance.__dict__.

...I hadn't even considered __slots__ yet. Hm...

> Or dynamic attributes returned by __getattr__ or __getattribute__.

I'm looking for a generic term, because it's too cumbersome to say 
"properties or dynamic attributes using __getattr__ or __getattribute__" 
all the time.

That will be my last message for a while...good night, c.p.l.

-- 
Brad Harms -- http://alphaios.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Alf P. Steinbach

Is this guaranteed to work in Python 3.x?


>>> def foo(): pass
...
>>> foo.blah = 222
>>> foo.blah
222
>>> _


Cheers,

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


Re: Insane Problem

2009-12-04 Thread Victor Subervi
On Thu, Dec 3, 2009 at 7:07 PM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> On Thu, 03 Dec 2009 10:13:14 -0500, Carsten Haese wrote:
>
> > Victor Subervi wrote:
> >> I believe I mentioned in my first post that the "print test" does print
> >> the exact fields being called from the referring page.
> >
> > Was any part of "What do the print statements actually print? Please
> > copy and paste their output." unclear to you in any way?
> >
> >> Perhaps this
> >> is a bug in the cgi interface?
> >
> > Unlikely.
> >
> > It's much more likely that whatever frankencode you stitched together
> > from examples you found on the internet without understanding how they
> > work is doing something unexpected, and you are unable to diagnose the
> > problem because you don't understand how your code works.
>
> Oh come on, how likely is that??? It's much more likely that the original
> poster has discovered a bug in the standard library that thousands of
> users before him never noticed!
>
> *wink*
>

Please don't be rude. I never suggested that, but only said that there may
be a possibility that there was some problem, and in the context I wrote it,
it was perfectly obvious, because I made it so, that I was pulling at
straws.

I might not be as good a programmer as you, but I'm not rude, and that makes
me a better person. You can't take your programming with you when you die,
but I can take my pure, peaceful and joy-filled soul with me. Think about
that and don't be rude.
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Marco Mariani

Alf P. Steinbach wrote:



Is this guaranteed to work in Python 3.x?


 >>> def foo(): pass

 >>> foo.blah = 222
 >>> foo.blah
222
 >>> _


I don't see why it shouldn't work.

BTW, it's a function, not a "routine"

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


Re: Manyfile Processing

2009-12-04 Thread Dan Sommers
On Fri, 04 Dec 2009 10:00:53 +0200, user wrote:

>  sorry if i bother you with a beginners question but i have an issue
> with processing a bunch of files. They are some arithmetic lists the
> processing of one file is an easy task but how do i process many files?
> I tried reading that files in to a list and looping over the list
> elements but the function won't accept any arguments other than a
> string.

Maybe the fileinput module can help.

Dan

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


Re: Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Alf P. Steinbach

* Marco Mariani:

Alf P. Steinbach wrote:



Is this guaranteed to work in Python 3.x?


 >>> def foo(): pass

 >>> foo.blah = 222
 >>> foo.blah
222
 >>> _


I don't see why it shouldn't work.


For example,

  (42).blah = 666

The question is what guarantees or absence thereof the language specification, 
PEPs, intentions, whatever gives/has.




BTW, it's a function, not a "routine"


Wikipedia is your friend, http://en.wikipedia.org/wiki/Subroutine>.


Cheers & hth.,

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


Re: Which is more pythonic?

2009-12-04 Thread Bruno Desthuilliers

Filip Gruszczyński a écrit :

I have just written a very small snippet of code and started thinking,
which version would be more pythonic. Basically, I am adding a list of
string to combo box in qt. So, the most obvious way is:

for choice in self.__choices:
choicesBox.addItem(choice)

But I could also do:

map(self.__choices, choicesBox.addItem)


this should actually be
  map(choicesBox.addItem, self.__choices)

!-)


or

[choicesBox.addItem(choice) for choice in self.__choices]

I guess map version would be fastest and explicit for is the slowest
version. 


I don't think so - there's at least the overhead of creating a useless 
list. But if you're after micro-optimization, there's an obvious one :


addItem = choicesBox.addItem
for choice in self.__choices:
addItem(choice)

Attribute lookup can be costly, specially when the attribute is a method.

Now unless you have a _very_ big choices list - which is probably not 
the case - the gain will still be marginal.



However, the first, most obvious way seems most clear to me


It is.


and I don't have to care about speed with adding elements to combo
box. Still, it's two lines instead of one, so maybe it's not the best.
So, which one is?


The first, obviously - and I'm the kind of guy that really dig obscure 
one-liners !-)

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


Connecting to the users preferred email client

2009-12-04 Thread Tuomas Vesterinen

If I want to open a html-page from Python code I can say:

>>> import webbrowser
>>> webbrowser.open('index.html')

Is there a standard way to init an email in users preferred email client 
like Thubderbird, Evolution etc.?


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


Re: python bijection

2009-12-04 Thread M.-A. Lemburg
geremy condra wrote:
> On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg  wrote:
>> geremy condra wrote:
>>> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg  wrote:
 I think the only major CS data type missing from Python is some
 form of (fast) directed graph implementation à la kjGraph:

http://gadfly.sourceforge.net/kjbuckets.html

 With these, you can easily build all sorts of relations between
 objects and apply fast operations on them. In fact, it should then
 be possible to build a complete relational database in Python
 (along the lines of Gadfly).
>>>
>>> If you're in the market for a Python graph library, you may want
>>> to check out Graphine- I'm obviously biased (I wrote most of it)
>>> but it has a few more bells and whistles than kjbuckets, and is
>>> pretty darned easy to use. It also supports undirected and
>>> bridge graphs.
>>
>> Thanks for the hint :-)
>>
>> The lib looks nice and would probably serve as a good prototype
>> for writing a new built-in type for Python.
> 
> I suspect that it would have a better chance at getting into
> collections than becoming a builtin, but who knows. I'd just
> like to have something like it in the standard library.

Integrating an easy-to-use graph library into the collections
module (and it's C companion) is good idea.

>> This would have to be written in C, though,
> 
> That's currently in the works, along with database backing.
> We'd welcome any help though... hint, hint...
> 
>> and come under a Python compatible license.
> 
> I'm willing to dual license under the Python license if
> there were a substantial interest in doing so, and I'm
> confident that the other authors and maintainers
> would feel the same way.

Great !

> The question in my mind is whether such an interest exists.

Since Python is being used more and more in CS classes,
such an addition would complete the tool-set and make Python
even more attractive for undergrad CS courses.

Finding out how much interest exists in advance is always
a bit difficult with new data-structures. People have to
get a feeling of how they can be put to good use first,
so it's a chicken-and-egg problem.

We've seen the same thing happen with sets. They were first
made available via a separate module and then became built-ins
after people realized how useful they are in practice.

With graphs, it's probably going to take a little longer
before people realize their usefulness - graph theory is
certainly a lot more complicated than set theory :-)

>> With the built-in feature moratorium
>> currently in place, there's about 1.5-2 years time to get this
>> done; perhaps a good GSoC project for next year :-)
> 
> I'd love to have Graphine be a GSoC project, although
> if the target were to get it into collections the
> moratorium wouldn't change the timeline AFAICS.

True.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 04 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Organization of GUIs

2009-12-04 Thread denis
On Dec 3, 2:44 pm, Michael Mossey  wrote:
> complete VISIBILITY and control of messages ...

is most important: being able to SEE messages (filtered on from,
to, ...)
in a running system really helps to understand it.
Hierarchy does help structure messages coarse/fine,
but visibility is orthogonal to structure
(you can have visible democracy, blind hierarchy, in real life too.)

Visibility has to be built in from the beginning --
wrap all connect() s in a visconnect() that can trace.

Dietmar's shell sounds Right; anyone know of such in PyQt ?

cheers
  -- denis



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


Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread Петров Александр
Hello All !

In my code I try to use a generic approach to work with tuples. Let
"X" be a tuple.
When I want to access a first element of a tuple, I can write: "X[0]".
And that is really working when X is a n-arity tuple, with n>1 (for
example "foo( (1,2,3) )" ).
But when I call my library function with a 1-arity tuple (for example
"foo( (1) )" ) I have an error:

TypeError: 'int' object is unsubscriptable

How could I tell Python that "(1)" is not an integer, but an one-arity tuple ?

Thank you,
Alexander Petrov
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread Andre Engels
2009/12/4 Петров Александр :
> Hello All !
>
> In my code I try to use a generic approach to work with tuples. Let
> "X" be a tuple.
> When I want to access a first element of a tuple, I can write: "X[0]".
> And that is really working when X is a n-arity tuple, with n>1 (for
> example "foo( (1,2,3) )" ).
> But when I call my library function with a 1-arity tuple (for example
> "foo( (1) )" ) I have an error:
>
> TypeError: 'int' object is unsubscriptable
>
> How could I tell Python that "(1)" is not an integer, but an one-arity tuple ?

Tuples in Python are recognized/defined not by the brackets, but by
the commas; the brackets just function to specify the exact beginning
and ending of the tuple in cases where that is not directly clear.
"(1,2,3)" is a tuple, but "1,2,3" is also the same tuple. A 1-tuple
can be created as "1," or "(1,)".

-- 
André Engels, andreeng...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread Baptiste Lepilleur
By adding a before the closing brace of the tuple. Python allow this to
disambiguate between braced expression and tuple

>>> type( (1,) )



2009/12/4 Петров Александр 

>
> How could I tell Python that "(1)" is not an integer, but an one-arity
> tuple ?
>
> Thank you,
> Alexander Petrov
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread Wolodja Wentland
On Fri, Dec 04, 2009 at 15:17 +0300, Петров Александр wrote:
> In my code I try to use a generic approach to work with tuples. Let
> "X" be a tuple.
> When I want to access a first element of a tuple, I can write: "X[0]".
> And that is really working when X is a n-arity tuple, with n>1 (for
> example "foo( (1,2,3) )" ).
> But when I call my library function with a 1-arity tuple (for example
> "foo( (1) )" ) I have an error:
> 
> TypeError: 'int' object is unsubscriptable
> 
> How could I tell Python that "(1)" is not an integer, but an one-arity tuple ?

The following might clarify the issue:

>>> t = (1)
>>> type(t)

>>> t = (1,)
>>> type(t)

>>> t = 1,
>>> type(t)


It is the ',' not the '(' and ')' ...


-- 
  .''`. Wolodja Wentland 
 : :'  :
 `. `'` 4096R/CAF14EFC 
   `-   081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread Baptiste Lepilleur
By adding a before the closing brace of the tucomma after 1. Python allow
this to disambiguate between braced expression and tuple

>>> type( (1,) )



2009/12/4 Петров Александр 

>
> How could I tell Python that "(1)" is not an integer, but an one-arity
> tuple ?
>
> Thank you,
> Alexander Petrov
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting logically nested actions -- Pythonic way?

2009-12-04 Thread sturlamolden
On 4 Des, 07:24, "Alf P. Steinbach"  wrote:

> And this leads to hierarchical code, which would be nice to indicate by
> indenting, but oops, indenting in Python is syntactically significant...

I've seen this with OpenGL as well. Intendation between glBegin and
glEnd can be achieved with a context manager that calls glBegin in
__enter__ and glEnd in __exit__. Same thing for glColor* and other
functions that set state attributes: call glPushAttrib in __enter__
(before setting new state) and glPopAttrib in __exit__.

Context managers (i.e. with statement) should be used for this, as it
guards against havoc from exceptions. If a context manager is used to
call glPushAttrib and glPopAttrib, a raised exception cannot leave
OpenGL's colour bit and colour stack in an undefined state by skipping
glPopAttrib. The with statement is not just a pritty printer for your
code.

I don't see anything wrong with using context managers for tkinter as
well. But personally I prefer to design GUIs using tools like
wxFormBuilder, GLADE or QtDesigner.









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


logging module, SMTPHandler and gmail in python 2.6

2009-12-04 Thread mynthon
You cannot use gmail account for sending emails with logging module.
It is because google requires TLS connection and logging module
doesn't support it. To use gmail you have to extend
logging.handlers.SMTPHandler class and override SMTPHandler.emit()
method. Here is source code.

(There really should be option to add user comments on pythons
documentation page!)

#--code--#

import logging
import logging.handlers

class TlsSMTPHandler(logging.handlers.SMTPHandler):
def emit(self, record):
"""
Emit a record.

Format the record and send it to the specified addressees.
"""
try:
import smtplib
import string # for tls add this line
try:
from email.utils import formatdate
except ImportError:
formatdate = self.date_time
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r
\n%s" % (
self.fromaddr,
string.join(self.toaddrs, ","),
self.getSubject(record),
formatdate(), msg)
if self.username:
smtp.ehlo() # for tls add this line
smtp.starttls() # for tls add this line
smtp.ehlo() # for tls add this line
smtp.login(self.username, self.password)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)

logger = logging.getLogger()

gm = TlsSMTPHandler(("smtp.gmail.com", 587), 'b...@my_company.com',
['ad...@my_company.com'], 'Error found!',
('my_company_acco...@gmail.com', 'top_secret_gmail_password'))
gm.setLevel(logging.ERROR)

logger.addHandler(gm)

try:
1/0
except:
logger.exception('FFFUU-')

#--/code--#


see also fortmatted version at
http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: editor with autocompletion

2009-12-04 Thread Tim Chase

So I want an editor with auto complete.
I there any such tool in Python ?(not only in python any other)
I want it for my new lang


vim?  emacs?  or do you want the editor to be written in Python?

-tkc


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


Re: Feature request: String-inferred names

2009-12-04 Thread Steven D'Aprano
On Thu, 03 Dec 2009 23:12:39 -0600, Brad Harms wrote:

> On Tue, 2009-12-01 at 14:38 +, Steven D'Aprano wrote:
[...]
>> It's just special double-underscore methods like __init__ __add__ etc
>> that have to be in the class rather than the instance. (To be precise,
>> you can add such a method to the instance, but it won't be called
>> automatically.) Likewise staticmethods and classmethods won't work
>> correctly unless they are in the class. But ordinary methods work fine:
>> the only tricky bit is creating them in the first place.
>> 
>> >>> class K(object):
>> ... pass
>> ...
>> >>> k = K()
>> >>> import types
>> >>> k.method = types.MethodType(lambda self: "I am %s" % self, k)
>> >>> k.method()
>> 'I am <__main__.K object at 0xb7cc7d4c>'
> 
> ...I'm not sure I follow your logic.
> 
> Yes, you can create an instancemethod out of a function and assign it to
> an instance after (or during) its instantiation, which is what Python's
> class/instance model provides automatically. However, to do so manually
> in this manner completely disregards the fundamentals of object-oriented
> programming, not to mention the basic guiding principles of nearly all
> Python code in existence. It totally breaks inheritance and
> polymorphism. Maybe I'm missing something, but I can't see how that line
> of thought helps anything.

I'm not recommending it as a standard technique instead of defining 
methods via the usual class statement. But it does work, and can be handy 
for the odd occasion where you want per-instance behaviour of some class. 
I'm not saying this is a common occurrence, but it does happen -- it's 
particularly handy if you have a standard behaviour which you want to 
override, e.g. monkey-patching specific instances. Instead of this:

class K:
marker = None
def method(self):
if self.marker:
return "special"
 return "normal"

k = K()
k.marker = 1

you can do this:

class K:
def method(self):
 return "normal"

k = K()
k.method = type(k.method)(lambda self: "special", k)

So although unusual, it is useful.

As for breaking inheritance and polymorphism, not at all. Inheritance 
still works, and polymorphism is irrelevant: methods are, or aren't, 
polymorphic regardless of whether they are per instance or shared. 
Fundamentally, per-instance methods are nothing more than as per-instance 
attributes which happen to be callable.

It is "magic methods" like __len__ and friends that break the usual rules 
of inheritance. The normal lookup chain for instance.name, whether name 
is a callable method or a non-callable attribute, is:

instance
class
base class(es)

but for magic methods, the chain skips the instance step. That's done as 
an optimization, and given how rare it is to have per-instance methods, 
that's quite reasonable.



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


Re: Manyfile Processing

2009-12-04 Thread km
use glob module
Krishna

On Fri, Dec 4, 2009 at 6:37 PM, Diez B. Roggisch wrote:

> u...@domain.invalid schrieb:
>
>> Hey,
>>
>>  sorry if i bother you with a beginners question but i have an issue
>> with processing a bunch of files. They are some arithmetic lists the
>> processing of one file is an easy task but how do i process many files?
>> I tried reading that files in to a list and looping over the list
>> elements but the function won't accept any arguments other than a string.
>>
>> I would appreciate if you could help me.
>>
>
> for filename in list_of_filenames:
>do_something_with_one_file(filename)
>
> Unless you disclose more of what your actual code looks like, there isn't
> more we can do.
>
> Diez
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: editor with autocompletion

2009-12-04 Thread mynthon
On 4 Gru, 13:37, Tim Chase  wrote:
> > So I want an editor with auto complete.
> > I there any such tool in Python ?(not only in python any other)
> > I want it for my new lang
>
> vim?  emacs?  or do you want the editor to be written in Python?
>
> -tkc

Try ActiveState Komodo (or free version: Komodo Edit):
http://www.activestate.com/komodo_edit/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Python as career

2009-12-04 Thread Michele Simionato
After 5 years of postdoc in Physics I decided to change career and to
move to IT. I decided to learn Object Oriented Programming first. I
chose Python since it was already installed on my Linux machine and it
was easy to tackle for a beginner. In the process of learning Python I
began posting to this newsgroup: first asking questions, then
answering them. I also wrote a few papers about Python. After a year
or so I was kind of known in the Python world, with a respectable
curriculum. Then I got my first job by answering a job offer on
comp.lang.python. My advice is to contact some local Python user
group, to go to conferences and to make yourself known in a way or
another.
It takes time. Good luck!

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


Re: Connecting to the users preferred email client

2009-12-04 Thread Mike Driscoll
On Dec 4, 5:28 am, Tuomas Vesterinen  wrote:
> If I want to open a html-page from Python code I can say:
>
>  >>> import webbrowser
>  >>> webbrowser.open('index.html')
>
> Is there a standard way to init an email in users preferred email client
> like Thubderbird, Evolution etc.?
>
> Tuomas Vesterinen

Check this thread out:

http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx

Basically, the idea is to pass the mailto url to webbrowser.

---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: memory error

2009-12-04 Thread Ahmed, Shakir
 

 

From: python-list-bounces+shahmed=sfwmd@python.org 
[mailto:python-list-bounces+shahmed=sfwmd@python.org] On Behalf Of Stephen 
Hansen
Sent: Thursday, December 03, 2009 10:22 PM
To: python-list@python.org
Subject: Re: memory error

 

On Thu, Dec 3, 2009 at 5:51 AM, Ahmed, Shakir  wrote:

I am getting a memory error while executing a script. Any idea is highly
appreciated.

Error message: " The instruction at "0x1b009032" referenced memory at
"0x0804:, The memory could not be "written"

This error is appearing and I have to exit from the script.

 

Vastly insufficient information; that basically is like saying, "Something 
broke." People can't really help you with that. You sorta need to show some 
code and/or at least describe what's going on at the time.

 

But-- the image does say Pythonwin... are you running this from the Pythonwin 
editor/IDE? Does this script crash out if you run it through the normal 
'python'(or pythonw) commands? If not, are you attempting to do any sort of GUI 
work in this script? That rarely works within Pythonwin directly.

 




--S

 

I am using python to do some gp ( geo processing ) for accuracy analysis. This 
analysis is based on application numbers. The script is going through each 
application number to process the data and looping through. The error appears 
after running few loops ( mean it process few applications). There is no 
certainty of how many loops it is going through but stopped with the error 
message and.

 

The code is attached herewith so I  hope it would make more clear to you. Any 
help is highly appreciated.

 

--sk 

 



ReverseBufferOverLay.py
Description: ReverseBufferOverLay.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: editor with autocompletion

2009-12-04 Thread Gerhard Häring
Siva B wrote:
> Hi friends,
> 
> I am writing a new language.
> So I want an editor with auto complete.
> I there any such tool in Python ?(not only in python any other)
> I want it for my new lang

IDLE, the Integrated Development Environment included with your Python
installation nowadays has autocompletion (I just check with the one
included in Python 2.6).

-- Gerhard

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


Re: Manyfile Processing

2009-12-04 Thread user
On 12/04/2009 12:58 PM, Dan Sommers wrote:
> On Fri, 04 Dec 2009 10:00:53 +0200, user wrote:
> 
>>  sorry if i bother you with a beginners question but i have an issue
>> with processing a bunch of files. They are some arithmetic lists the
>> processing of one file is an easy task but how do i process many files?
>> I tried reading that files in to a list and looping over the list
>> elements but the function won't accept any arguments other than a
>> string.
> 
> Maybe the fileinput module can help.
> 
> Dan
> 

Hi,

  seems like the fileinput module works fine for me though i am having
quite an issue with the paths.

if i do:


something = fileinput.input("/some/absolute/path/to/list/file.txt")
#the text file contains absolute paths
for line in something:
data=scipy.io.array_import.read_array(line)
print data

it claims that the paths given in the textfiles don't exist "no file or
directory" though taking one entry from the textfile and inserting it
directly to the command does its job...

Any idea?

Thanks so far
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on Python as career

2009-12-04 Thread joy99
On Dec 4, 6:53 pm, Michele Simionato 
wrote:
> After 5 years of postdoc in Physics I decided to changecareerand to
> move to IT. I decided to learn Object Oriented Programming first. I
> chosePythonsince it was already installed on my Linux machine and it
> was easy to tackle for a beginner. In the process of learningPythonI
> began posting to this newsgroup: first asking questions, then
> answering them. I also wrote a few papers aboutPython. After a year
> or so I was kind of known in thePythonworld, with a respectable
> curriculum. Then I got my first job by answering a job offer on
> comp.lang.python. My advice is to contact some localPythonuser
> group, to go to conferences and to make yourself known in a way or
> another.
> It takes time. Good luck!
>
>        Michele Simionato

Dear All,
This really came out to be a resourceful discussion. Every one tried
to help me with some nice idea(s). Now, it is my time to act. Let me
first summarize them and proceed on them suiting my need and
capability.
Wishing you all a nice day ahead,
Best Regards,
Subhabrata Banerjee.
-- 
http://mail.python.org/mailman/listinfo/python-list


Difference between mutex.mutex and threading.Lock

2009-12-04 Thread sven
Hi,

what is the difference between mutex.mutex and threading.Lock?
Neither the documentation nor a Google search gave me any clue.

Another issue: The documentation of mutex in version 2.6.4 says:

"Deprecated since version The: mutex module has been removed in Python
3.0."

Maybe it should also say what to use instead (probably
threading.Lock?).  Also the "version The" part seems a bit strange.

Greetings,
Sven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-12-04 Thread Bruno Desthuilliers

Brad Harms a écrit :

On Tue, 2009-12-01 at 16:58 +0100, Bruno Desthuilliers wrote:

The Music Guy a écrit :
(snip)

Lie Ryan, I think I see what you're saying about using __dict__ to add
members

No "members" in Python - only attributes.



to a class, but it's not quite the same. __dict__ is only for
attributes, NOT properties, methods, etc. which all come from the
class of an object rather than the object's __dict__.
properties and methods (well, functions actually) ARE attributes... of 
the class object. And you can of course access the obj.__class__.__dict__


Just for the record...


When I say "member" I am using it as a general term that describes any
value that can be accessed (get, set, del) through an object.


These are what we call "attributes".


If the
object is referenced by a variable named `foo`, then by using `foo.name`
or one of the XXXattr functions, one can access the member of `foo`
called `name`. What's important to note, though, is that the term
"member" does not make any assumption about how `foo.name` is
implemented.

>

When I say "attribute," however, I am referring specifically to a member
of an object where the member's name is a key in the object's __dict__,
and the value is the one that is paired with that key.


What if the class uses slots then ?-)

Ok, just kidding. More seriously: these are named "instance attributes".


Essentially, I just use "member" as a convenience term. I thought that
was the convention among the community, but evidently it isn't as widely
used as such as I thought. 


"members" is really C++ vocabulary.


Anyway, it looks like the docs agree with you
(http://docs.python.org/glossary.html#term-attribute),


I'd put it the other way round - I have no responsabilities wrt/ the 
usual Pythonic vocabulary !-)



so I'm not going
to argue. However, for the purpose of clean communication, I'd still
like to have terms that refer specifically to:

1.) "Regular" attributes, ie. those that are shortcuts to items in the
directly associated object's __dict__, 


instance attributes



2.) Attributes whose values are determined or assigned dynamically by
indirectly calling a function (like properties and instancemethods)


computed attributes


3.) Attributes that are read from an object with regular .dot syntax,
but are actually attributes (in the sense of #1 above) of the  __dict__
of the object's class.


class attributes.

Now things are even a bit more complex since computed attributes are 
usually handled by objects implementing the descriptor protocol 
(instance of the function or property type or any other custom 
descriptor), which are themselves class attributes. So sometimes - 
depending on the context - you may have to make clear whether you're 
talking about the descriptor object itself or the attribute as seen by 
client code.


HTH



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


Re: Feature request: String-inferred names

2009-12-04 Thread Bruno Desthuilliers

Ben Finney a écrit :

Brad Harms  writes:

(snip)


2.) Attributes whose values are determined or assigned dynamically by
indirectly calling a function (like properties and instancemethods)


Yes, the term “property” seems to do what you want.


The property type is just one possible application of the descriptor 
protocol which provides most of the support for computed attributes in 
Python, so it might be way too restrictive.



The value of an instance method is *not* determined dynamically:


It is, actually. The function type implements the protocol descriptor, 
with the __get__ method returning an instancemethod object.


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


Re: Feature request: String-inferred names

2009-12-04 Thread Bruno Desthuilliers

Brad Harms a écrit :

On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote:

(snip)

2.) Attributes whose values are determined or assigned dynamically by
indirectly calling a function (like properties and instancemethods)

Yes, the term “property” seems to do what you want.


I wasn't asking what you call any object or any /kind/ of object. I was 
asking for a term (noun?) that describes the WAY the object is accessed 
as an attribute of an instance, with the connotation that the value of 
the attribute would be calculated dynamically (by calling a function) at 
the time the attribute was accessed.


Then you definitly want "computed attribute" - which is quite standard 
OO terminology FWIW.


(snip - Ben, I think you shouldn't have tred to teach your grandmother 
how to suck eggs )


Also note the fact that Foo.spam is an _instancemethod_ object and not 
just a function, even though it was defined as "just a function" in the 
class body. That's because function objects are descriptors as well; it 
lets them produce unbound instancemethods. I'm not precisely sure how 
this works,


class function(object):
   def __get__(self, instance, cls):
   if instance:
   assert isinstance(instance, cls)
   return boundmethod(instance, cls)
   else
   return unboundmethod(cls)


though. I think it only happens when the metaclass of a class 
processes the functions in the class block.


Nope, this is totally unrelated.

class Foo(object):
def __init__(self, bar):
self.bar = 42

def baaz(obj, whatever):
 print obj.bar, whatever

Foo.baaz = baaz

f= Foo()
f.baaz("is the answer")



3.) Attributes that are read from an object with regular .dot syntax,
but are actually attributes (in the sense of #1 above) of the __dict__
of the object's class.

This is a “class attribute” as distinct from an “instance attribute”.



I know it's called that, but I was talking more about the fact of it 
being accessed through an instance of the class rather than 


Except for descriptors, this doesn't make much difference difference.


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


Re: testing command line scripts that use optparse

2009-12-04 Thread Jean-Michel Pichavant

Peter wrote:

Hi
I have a script like this:

def doit(input, output):
 parser = OptionParser()
 parser.add_option("-a", "--accounts", dest="accounts", default="all",
   help="list available accounts")
...

 (options, args) = parser.parse_args()


# main driver
if __name__ == "__main__":
 import sys
 doit(sys.stdin, sys.stdout)

that I would like to test like this:

   def test_accounts(self):
 input = """-aRoot""" output = """Results"""
 self.runtest(input, output)
   def runtest(self, input, expected):
 inputStream = cStringIO.StringIO(input)
 actual = cStringIO.StringIO()
 doit(inputStream, actual)
 assert_equal(actual.getvalue(), expected)

But when running test_accounts, I get:
...
File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1578, in 
error

   self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
 File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1568, in 
exit

   sys.exit(status)
SystemExit: 2
 >> begin captured stdout << -
stdin 

optparse expects a file object and gets a cStringIO.

What is the correct way to set up this ?
Thanks for your help.

Peter

It seems there is something wrong with the type of the paramaters given 
to the doit function. We can't say more cause cause you remove the 
related code of the doit function.


But the error seems pretty clear to me : "optparse expects a file object 
and gets a cStringIO"


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


Re: Manyfile Processing

2009-12-04 Thread Peter Otten
u...@domain.invalid wrote:

> On 12/04/2009 12:58 PM, Dan Sommers wrote:
> > On Fri, 04 Dec 2009 10:00:53 +0200, user wrote:
> > 
> >>  sorry if i bother you with a beginners question but i have an issue
> >> with processing a bunch of files. They are some arithmetic lists the
> >> processing of one file is an easy task but how do i process many files?
> >> I tried reading that files in to a list and looping over the list
> >> elements but the function won't accept any arguments other than a
> >> string.
> > 
> > Maybe the fileinput module can help.
> > 
> > Dan
> > 
> 
> Hi,
> 
>   seems like the fileinput module works fine for me though i am having
> quite an issue with the paths.
> 
> if i do:
> 
> 
> something = fileinput.input("/some/absolute/path/to/list/file.txt")
> #the text file contains absolute paths
> for line in something:
> data=scipy.io.array_import.read_array(line)
> print data
> 
> it claims that the paths given in the textfiles don't exist "no file or
> directory" though taking one entry from the textfile and inserting it
> directly to the command does its job...
> 
> Any idea?

line includes a trailing newline. You can see that if you modify your code 
to

for line in something:
print repr(line)

Use

line = line.strip()

to remove the newline (in fact all leading and trailing whitespace).

Peter


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


Re: Moving from Python 2 to Python 3: 4 page "cheat sheet" issue#3

2009-12-04 Thread Mark Summerfield
On 3 Dec, 01:17, Antoine Pitrou  wrote:
> Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a écrit :
>
> > I've produced a 4 page document that provides a very concise summary of
> > Python 2<->3 differences plus the most commonly used new Python 3
> > features. It is aimed at existing Python 2 programmers who want to start
> > writing Python 3 programs and want to use Python 3 idioms rather than
> > those from Python 2 where the idioms differ.
> [...]
>
> > It is available as a free PDF download (no registration or anything)
> > from InformIT's website. Here's the direct link:
>
> This is great!
>
> Just one thing:
>
> « Copyright © Qtrac Ltd. 2009. All rights reserved »
>
> Might I suggest that you release it under a free license instead?
> (such as the CC by, CC by-sa, or the Free Art License)
>
> Regards

OK, issue#3 of the document is now available:
http://www.informit.com/promotions/promotion.aspx?promo=137519

In the light of feedback from [these people] it now has:
- an entry for file() vs. open() [Martin P. Hellwig]
- an entry for %* vs. {:{}} syntax [John Posner, Mark Dickinson, &
Carsten Haese]
- creative commons license "CC by-sa" [Antoine Pitrou]

So I hope it will prove even more useful now:-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Killing Another Bug

2009-12-04 Thread Victor Subervi
Hi;
I have this code:

  for table in tables:
if table == 'products':
  optionsCode = optionsCodeProducts
  fromForm = prodsFromForm
try:
  fn = getattr(options, table)
  fromForm = form.getfirst('%s-options' % table)
  fromForm = string.split(fromForm[2:-2], "', '")
  optionsCode = fn(table, 'specificCode', fromForm)
except:
  if table != 'products': # We recall we must add the products table
fields to all tables.
optionsCode = optionsCodeProducts
i = 0
j = 0
oldJ = 0
try:
  y = 0
  while y < len(optionsCode):
if table == 'prescriptions':
  print len(optionsCode) # prints '2'
for inputName in optionsCode[y]:
  if table == 'prescriptions':
print len(optionsCode[y]) # prints '7'
print inputName # prints 'Extra-small', which is only the first
inputName in optionsCode[0]
  if j != oldJ:
i = 0
oldJ = j
  x = '%s-%s%d' % (table, fromForm[y], i)
  x = form.getfirst(x)
  if x is not None:
ourInputNames.append('%s-%s' % (table, inputName))
  i += 1
j += 1
y += 1
except:
  pass

As you can see in the supplied comments, when I loop through for table
'prescriptions', it only prints out the first element of each variable. When
I loop through for table 'products', it prints out all of them! Why?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slightly OT: Python BootCamp

2009-12-04 Thread Neil Cerutti
On 2009-12-04, Steven D'Aprano  wrote:
> How would I re-write this? Just get rid of the try block and
> add a close:
>
> for (exten, list) in files.iteritems():
> f=open('extensions-%s.txt' % exten,'w')
> f.write('\n'.join(list))

"\n".join is a cute shortcut, but if you use it you must remember
to write the last, trailing '\n' manually.

> That's still not quite "best practice" -- best practice would
> be to use a with block, but (to my shame) I'm not entirely
> familiar with that so I'll leave it for others.

from __future__ import with_statement

# Etc.

for (exten, list) in files.iteritems():
with open('extensions-%s.txt' % exten,'w') as f:
f.write('\n'.join(list))
f.write('\n')

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


Re: python bijection

2009-12-04 Thread MRAB

M.-A. Lemburg wrote:

geremy condra wrote:

On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg  wrote:

geremy condra wrote:

On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg  wrote:

I think the only major CS data type missing from Python is some
form of (fast) directed graph implementation à la kjGraph:

   http://gadfly.sourceforge.net/kjbuckets.html

With these, you can easily build all sorts of relations between
objects and apply fast operations on them. In fact, it should then
be possible to build a complete relational database in Python
(along the lines of Gadfly).

If you're in the market for a Python graph library, you may want
to check out Graphine- I'm obviously biased (I wrote most of it)
but it has a few more bells and whistles than kjbuckets, and is
pretty darned easy to use. It also supports undirected and
bridge graphs.

Thanks for the hint :-)

The lib looks nice and would probably serve as a good prototype
for writing a new built-in type for Python.

I suspect that it would have a better chance at getting into
collections than becoming a builtin, but who knows. I'd just
like to have something like it in the standard library.


Integrating an easy-to-use graph library into the collections
module (and it's C companion) is good idea.


This would have to be written in C, though,

That's currently in the works, along with database backing.
We'd welcome any help though... hint, hint...


and come under a Python compatible license.

I'm willing to dual license under the Python license if
there were a substantial interest in doing so, and I'm
confident that the other authors and maintainers
would feel the same way.


Great !


The question in my mind is whether such an interest exists.


Since Python is being used more and more in CS classes,
such an addition would complete the tool-set and make Python
even more attractive for undergrad CS courses.

Finding out how much interest exists in advance is always
a bit difficult with new data-structures. People have to
get a feeling of how they can be put to good use first,
so it's a chicken-and-egg problem.

We've seen the same thing happen with sets. They were first
made available via a separate module and then became built-ins
after people realized how useful they are in practice.


I'd like to add that people (myself included) were already using dicts
for sets before the module was written, so there was already a clear
demand for them.


With graphs, it's probably going to take a little longer
before people realize their usefulness - graph theory is
certainly a lot more complicated than set theory :-)


With the built-in feature moratorium
currently in place, there's about 1.5-2 years time to get this
done; perhaps a good GSoC project for next year :-)

I'd love to have Graphine be a GSoC project, although
if the target were to get it into collections the
moratorium wouldn't change the timeline AFAICS.


True.



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


Re: Why the expression "(1)" is not an one-arity tuple, but int ?

2009-12-04 Thread MRAB

Andre Engels wrote:

2009/12/4 Петров Александр :

Hello All !

In my code I try to use a generic approach to work with tuples. Let
"X" be a tuple.
When I want to access a first element of a tuple, I can write: "X[0]".
And that is really working when X is a n-arity tuple, with n>1 (for
example "foo( (1,2,3) )" ).
But when I call my library function with a 1-arity tuple (for example
"foo( (1) )" ) I have an error:

TypeError: 'int' object is unsubscriptable

How could I tell Python that "(1)" is not an integer, but an one-arity tuple ?


Tuples in Python are recognized/defined not by the brackets, but by
the commas; the brackets just function to specify the exact beginning
and ending of the tuple in cases where that is not directly clear.
"(1,2,3)" is a tuple, but "1,2,3" is also the same tuple. A 1-tuple
can be created as "1," or "(1,)".


The only exception is the 0-tuple (). No comma.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Killing Another Bug

2009-12-04 Thread MRAB

Victor Subervi wrote:

Hi;
I have this code:
 

[snip]
 
As you can see in the supplied comments, when I loop through for table 
'prescriptions', it only prints out the first element of each variable. 
When I loop through for table 'products', it prints out all of them! Why?



If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially
ones which contain only "pass"!

As for you're problem, it's not clear to me which one is behaving
correctly. You should add more print statements to tell you where it is 
in the code, and then read through the output, checking the logic. Are

the values what you expect? Is it following the route through the code
that you expect?
--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant solution for diffing two sequences

2009-12-04 Thread Ulrich Eckhardt
Lie Ryan wrote:
> On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote:
>> I'm trying to write some code to diff two fonts. What I have is every
>> character (glyph) of the two fonts in a list. I know that the list is
>> sorted by the codepoints of the characters. What I'd like to ask is
>> whether there is a more elegant solution to the loop below or whether
>> there are any rough corners in my code (see below). Note that I'm
>> targeting Python 2, not 3 yet.
>>
> 
> Use sets:
> 
> glyph_1 = set(font1.glyphs)
> glyph_2 = set(font2.glyphs)
> only_in_1 = glyph_1 - glyph_2
> only_in_2 = glyph_2 - glyph_1
> in_both = glyph_1 & glyph_2
> 
> that is assuming font1.glyphs's value are hashable.

Thinking about it, I perhaps should store the glyphs in a set from the 
beginning. Question is, can I (perhaps by providing the right hash function) 
sort them by their codepoint? I'll have to look at the docs...

Thank you for this nudge in the right direction!

Uli

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


Re: Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Rami Chowdhury
>> BTW, it's a function, not a "routine"
>
> Wikipedia is your friend, http://en.wikipedia.org/wiki/Subroutine>.
>
>

I don't think it was a problem of comprehension, more one of
appropriate terminology -- AFAIK in Python, they're called functions,
so calling them 'routines' is likely to confuse anyone in a discussion
of Python features.


Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: memory error

2009-12-04 Thread Stephen Hansen
>
> But-- the image does say Pythonwin... are you running this from the
> Pythonwin editor/IDE? Does this script crash out if you run it through the
> normal 'python'(or pythonw) commands? If not, are you attempting to do any
> sort of GUI work in this script? That rarely works within Pythonwin
> directly.
>
> I am using python to do some gp ( geo processing ) for accuracy analysis.
> This analysis is based on application numbers. The script is going through
> each application number to process the data and looping through. The error
> appears after running few loops ( mean it process few applications). There
> is no certainty of how many loops it is going through but stopped with the
> error message and.
>
>
>

You didn't answer my other questions-- have you run this with python
directly and not PythonWin? It doesn't look like it you're doing anything
GUI-ish, but I don't know anything about "arcgisscripting"... which is
almost certainly where the error is happening, its really hard to get access
violations in pure Python. You'll probably need to add a (lot) of logging
into the script to narrow down precisely where this error is happening, that
it happens 'eventually' and 'somewhere' in the loop isn't going to help. I'd
guess that eventually a certain piece of data in there gets passed to this
library and everything explodes.

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


Re: Killing Another Bug

2009-12-04 Thread Victor Subervi
On Fri, Dec 4, 2009 at 12:43 PM, MRAB  wrote:

> Victor Subervi wrote:
>
>> Hi;
>> I have this code:
>>
>>
> [snip]
>
>   As you can see in the supplied comments, when I loop through for table
>> 'prescriptions', it only prints out the first element of each variable. When
>> I loop through for table 'products', it prints out all of them! Why?
>>
>>  If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially
> ones which contain only "pass"!
>
> As for you're problem, it's not clear to me which one is behaving
> correctly. You should add more print statements to tell you where it is in
> the code, and then read through the output, checking the logic. Are
> the values what you expect? Is it following the route through the code
> that you expect?
>

Forgive me, but I believe I already addressed your question. There are two
tables: prescriptions and products, in that order, and both with (in this
case) the exact same options. For some reason, when products goes through
the loops, everything comes out exactly as expected. But when prescriptions
goes through, only optionsCode[0] passes (there are two) and only
optionsCode[0][0] goes through when there are 7. To restate that, both
optionsCode[y] and all optionsCode[y][z] get correctly processed when
'products' goes through, but only one when 'prescriptions' goes through, and
the options and options tables are identical! Here's the code again. Please
advise.
V


  for table in tables:
if table == 'products':
  optionsCode = optionsCodeProducts
  fromForm = prodsFromForm
try:
  fn = getattr(options, table)
  fromForm = form.getfirst('%s-options' % table)
  fromForm = string.split(fromForm[2:-2], "', '")
  optionsCode = fn(table, 'specificCode', fromForm)
except:
  if table != 'products': # We recall we must add the products table
fields to all tables.
optionsCode = optionsCodeProducts
i = 0
j = 0
oldJ = 0
try:
  y = 0
  while y < len(optionsCode):
if table == 'prescriptions':
  print len(optionsCode) # prints '2'
for inputName in optionsCode[y]:
  if table == 'prescriptions':
print len(optionsCode[y]) # prints '7'
print inputName # prints 'Extra-small', which is only the first
inputName in optionsCode[0]
  if j != oldJ:
i = 0
oldJ = j
  x = '%s-%s%d' % (table, fromForm[y], i)
  x = form.getfirst(x)
  if x is not None:
ourInputNames.append('%s-%s' % (table, inputName))
  i += 1
j += 1
y += 1
except:
  pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Killing Another Bug

2009-12-04 Thread Victor Subervi
On Fri, Dec 4, 2009 at 2:08 PM, Victor Subervi wrote:

> On Fri, Dec 4, 2009 at 12:43 PM, MRAB  wrote:
>
>> Victor Subervi wrote:
>>
>>> Hi;
>>> I have this code:
>>>
>>>
>> [snip]
>>
>>   As you can see in the supplied comments, when I loop through for table
>>> 'prescriptions', it only prints out the first element of each variable. When
>>> I loop through for table 'products', it prints out all of them! Why?
>>>
>>>  If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially
>> ones which contain only "pass"!
>>
>> As for you're problem, it's not clear to me which one is behaving
>> correctly. You should add more print statements to tell you where it is in
>> the code, and then read through the output, checking the logic. Are
>> the values what you expect? Is it following the route through the code
>> that you expect?
>>
>
> Forgive me, but I believe I already addressed your question. There are two
> tables: prescriptions and products, in that order, and both with (in this
> case) the exact same options. For some reason, when products goes through
> the loops, everything comes out exactly as expected. But when prescriptions
> goes through, only optionsCode[0] passes (there are two) and only
> optionsCode[0][0] goes through when there are 7. To restate that, both
> optionsCode[y] and all optionsCode[y][z] get correctly processed when
> 'products' goes through, but only one when 'prescriptions' goes through, and
> the options and options tables are identical! Here's the code again. I just
> now edited in a try statement to try to catch the bug, with no luck. Please
> advise.
>
> V
>
>
>   for table in tables:
> if table == 'products':
>   optionsCode = optionsCodeProducts
>   fromForm = prodsFromForm
> try:
>   fn = getattr(options, table)
>   fromForm = form.getfirst('%s-options' % table)
>   fromForm = string.split(fromForm[2:-2], "', '")
>   optionsCode = fn(table, 'specificCode', fromForm)
> except:
>   if table != 'products': # We recall we must add the products table
> fields to all tables.
> optionsCode = optionsCodeProducts
> i = 0
> j = 0
> oldJ = 0
> try:
>   y = 0
>   while y < len(optionsCode):
> if table == 'prescriptions':
>   print len(optionsCode) # prints '2'
> for inputName in optionsCode[y]:
>   if table == 'prescriptions':
> print len(optionsCode[y]) # prints '7'
> print inputName # prints 'Extra-small', which is only the first
> inputName in optionsCode[0]
>   if j != oldJ:
> i = 0
> oldJ = j
>   x = '%s-%s%d' % (table, fromForm[y], i)
>   try:
> x = form.getfirst(x)
> if x is not None:
>   ourInputNames.append('%s-%s' % (table, inputName))
>   except:
> print 'Oops!'
>   i += 1
> j += 1
> y += 1
> except:
>   pass
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant solution for diffing two sequences

2009-12-04 Thread Neil Cerutti
On 2009-12-04, Ulrich Eckhardt  wrote:
> Lie Ryan wrote:
> Thinking about it, I perhaps should store the glyphs in a set
> from the beginning. Question is, can I (perhaps by providing
> the right hash function) sort them by their codepoint? I'll
> have to look at the docs...

No, sets are unordered in Python.

You'll need to sort them when you need them sorted, or keep a
sorted list separately.

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


Re: More elegant solution for diffing two sequences

2009-12-04 Thread MRAB

Ulrich Eckhardt wrote:

Lie Ryan wrote:

On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote:

I'm trying to write some code to diff two fonts. What I have is every
character (glyph) of the two fonts in a list. I know that the list is
sorted by the codepoints of the characters. What I'd like to ask is
whether there is a more elegant solution to the loop below or whether
there are any rough corners in my code (see below). Note that I'm
targeting Python 2, not 3 yet.


Use sets:

glyph_1 = set(font1.glyphs)
glyph_2 = set(font2.glyphs)
only_in_1 = glyph_1 - glyph_2
only_in_2 = glyph_2 - glyph_1
in_both = glyph_1 & glyph_2

that is assuming font1.glyphs's value are hashable.


Thinking about it, I perhaps should store the glyphs in a set from the 
beginning. Question is, can I (perhaps by providing the right hash function) 
sort them by their codepoint? I'll have to look at the docs...


Thank you for this nudge in the right direction!


For sets you need __hash__ and __eq__, and for sorting you need __lt__.
Here's a simple example:

class Glyph(object):
def __init__(self, codepoint):
self.codepoint = codepoint
def __hash__(self):
return self.codepoint
def __eq__(self, other):
return self.codepoint == other.codepoint
def __lt__(self, other):
return self.codepoint < other.codepoint
def __repr__(self):
return "Glyph(%s)" % self.codepoint

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


How to tell if you're running on windows?

2009-12-04 Thread Roy Smith
I'm using 2.5.1.  How can I tell if I'm running on windows?  The
obvious answer, platform.system(), gets complicated.  On the python
that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got
a native windows build of python where it returns 'Microsoft'.

The real problem I'm trying to solve is whether to build a LIBPATH
environment variable with ';' or ':' delimiting the entries.  On the
cygwin build, os.pathsep returns ':', which isn't really correct.  If
you use that, you end up building paths that look like c:foo:c:bar.
It should be c:foo;c:bar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell if you're running on windows?

2009-12-04 Thread zeph
On Dec 4, 10:46 am, Roy Smith  wrote:
> I'm using 2.5.1.  How can I tell if I'm running on windows?  The
> obvious answer, platform.system(), gets complicated.  On the python
> that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got
> a native windows build of python where it returns 'Microsoft'.
>
> The real problem I'm trying to solve is whether to build a LIBPATH
> environment variable with ';' or ':' delimiting the entries.  On the
> cygwin build, os.pathsep returns ':', which isn't really correct.  If
> you use that, you end up building paths that look like c:foo:c:bar.
> It should be c:foo;c:bar

The Cygwin shell uses what appears to be its own pseudo-filesystem. If
you open your Cygwin shell window and type echo $PATH you will see
completely different results from the Windows command shell's PATH env
variable, and you'll see the path sep is indeed ':'.

Cygwin also seems to put drive mount points in /cygdrive/ so you will
have for example "/cygdrive/c/foo:/cygdrive/c/bar" instead of "C:
\foo;C:\bar".

For python *outside* of Cygwin, on Windows, I assume os.path.pathsep
is ';'.

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


Re: How to tell if you're running on windows?

2009-12-04 Thread Allan Davis
Try this

import sys
import os
sep = None
if sys.platform == 'cygwin':
  sep = ';'
else:
  sep = os.pathsep

# then use sep in your path statment

Hope this helps
Thanks,
--
Allan Davis
Member of NetBeans Dream Team
http://wiki.netbeans.org/NetBeansDreamTeam
Lead Developer, nbPython
http://wiki.netbeans.org/Python
http://codesnakes.blogspot.com (my blog)
Co-Chair, CajunJUG
http://www.cajunjug.org


On Fri, Dec 4, 2009 at 12:46 PM, Roy Smith  wrote:

> I'm using 2.5.1.  How can I tell if I'm running on windows?  The
> obvious answer, platform.system(), gets complicated.  On the python
> that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got
> a native windows build of python where it returns 'Microsoft'.
>
> The real problem I'm trying to solve is whether to build a LIBPATH
> environment variable with ';' or ':' delimiting the entries.  On the
> cygwin build, os.pathsep returns ':', which isn't really correct.  If
> you use that, you end up building paths that look like c:foo:c:bar.
> It should be c:foo;c:bar
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant solution for diffing two sequences

2009-12-04 Thread Lie Ryan

On 12/5/2009 4:20 AM, Ulrich Eckhardt wrote:

Thinking about it, I perhaps should store the glyphs in a set from the
beginning. Question is, can I (perhaps by providing the right hash function)
sort them by their codepoint? I'll have to look at the docs...


Python does not guarantee that a particular characteristic of the hash 
function will lead to a particular characteristic of the ordering of th 
eset. Though AFAICT, the current set's ordering is determined by the 
hash modulus the set's hashtable's real size, but if you rely on this 
you're on your own. It's better if you sorted() them when you want a 
sorted view (or turn to set just before finding the differences).


You can reduce the penalty of creating new data structure with something 
like:


a = [...]
b = [...]
s_a = set(a)
s_a -= set(b)

that only creates two new sets (instead of three) and probably might be 
faster too (though you'd need to profile to be sure).

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


Re: Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Lie Ryan

On 12/5/2009 4:56 AM, Rami Chowdhury wrote:

I don't think it was a problem of comprehension, more one of
appropriate terminology -- AFAIK in Python, they're called functions,
so calling them 'routines' is likely to confuse anyone in a discussion
of Python features.


Human language is not context-free, we can't parse human language with 
LL parser.

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


Re: python bijection

2009-12-04 Thread geremy condra
On Fri, Dec 4, 2009 at 2:52 PM, geremy condra  wrote:
> On Fri, Dec 4, 2009 at 11:17 AM, MRAB  wrote:
>> M.-A. Lemburg wrote:
>>>
>>> geremy condra wrote:

 On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg  wrote:
>
> geremy condra wrote:
>>
>> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg  wrote:
>>>
>>> I think the only major CS data type missing from Python is some
>>> form of (fast) directed graph implementation à la kjGraph:
>>>
>>>   http://gadfly.sourceforge.net/kjbuckets.html
>>>
>>> With these, you can easily build all sorts of relations between
>>> objects and apply fast operations on them. In fact, it should then
>>> be possible to build a complete relational database in Python
>>> (along the lines of Gadfly).
>>
>> If you're in the market for a Python graph library, you may want
>> to check out Graphine- I'm obviously biased (I wrote most of it)
>> but it has a few more bells and whistles than kjbuckets, and is
>> pretty darned easy to use. It also supports undirected and
>> bridge graphs.
>
> Thanks for the hint :-)
>
> The lib looks nice and would probably serve as a good prototype
> for writing a new built-in type for Python.

 I suspect that it would have a better chance at getting into
 collections than becoming a builtin, but who knows. I'd just
 like to have something like it in the standard library.
>>>
>>> Integrating an easy-to-use graph library into the collections
>>> module (and it's C companion) is good idea.
>>>
> This would have to be written in C, though,

 That's currently in the works, along with database backing.
 We'd welcome any help though... hint, hint...

> and come under a Python compatible license.

 I'm willing to dual license under the Python license if
 there were a substantial interest in doing so, and I'm
 confident that the other authors and maintainers
 would feel the same way.
>>>
>>> Great !
>>>
 The question in my mind is whether such an interest exists.
>>>
>>> Since Python is being used more and more in CS classes,
>>> such an addition would complete the tool-set and make Python
>>> even more attractive for undergrad CS courses.
>>>
>>> Finding out how much interest exists in advance is always
>>> a bit difficult with new data-structures. People have to
>>> get a feeling of how they can be put to good use first,
>>> so it's a chicken-and-egg problem.
>>>
>>> We've seen the same thing happen with sets. They were first
>>> made available via a separate module and then became built-ins
>>> after people realized how useful they are in practice.
>>>
>> I'd like to add that people (myself included) were already using dicts
>> for sets before the module was written, so there was already a clear
>> demand for them.
>>

To be fair, I don't think you'd have to look very far to find places
where a graph representation is approximated using some
combination of dicts, sets, and lists. ElementTree comes to mind
immediately, and the dict-of-dicts idea for logging recently
discussed on python-dev explicitly states that it uses that
structure to represent object graphs. To me that says that there
is at least some demand.

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


Re: How to tell if you're running on windows?

2009-12-04 Thread Ross Ridge
Roy Smith   wrote:
>The real problem I'm trying to solve is whether to build a LIBPATH
>environment variable with ';' or ':' delimiting the entries.  On the
>cygwin build, os.pathsep returns ':', which isn't really correct.  If
>you use that, you end up building paths that look like c:foo:c:bar.
>It should be c:foo;c:bar

What application is intepretting this LIBPATH environment variable?  If
it's another Cygwin app then ":" should be the correct seperator and you
should be building paths that look like "/cygdrive/c/foo:/cygdrive/c/bar".

I normally use the "os.name" variable to detect whether the script is
running on Windows, but the Cygwin version of Python sets it to "posix".
That works for me, since Cygwin tries hard to look like a Unix-type
operating system, my scripts should too.  In your case you can use
the "sys.platform" variable to distinguish between Cygwin and a real
Unix-type OS.  You may end up needing to treat Cygwin as a special case.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  rri...@csclub.uwaterloo.ca
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell if you're running on windows?

2009-12-04 Thread David Robinow
On Fri, Dec 4, 2009 at 1:46 PM, Roy Smith  wrote:
> I'm using 2.5.1.  How can I tell if I'm running on windows?  The
> obvious answer, platform.system(), gets complicated.  On the python
> that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got
> a native windows build of python where it returns 'Microsoft'.
>
> The real problem I'm trying to solve is whether to build a LIBPATH
> environment variable with ';' or ':' delimiting the entries.  On the
> cygwin build, os.pathsep returns ':', which isn't really correct.  If
> you use that, you end up building paths that look like c:foo:c:bar.
> It should be c:foo;c:bar

It's not clear to me what you're using LIBPATH for.
Are you running a cygwin executable from Python? Or a Windows
executable from cygwin?
LIBPATH should be in the format desired by the consumer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Formatting logically nested actions -- Pythonic way?

2009-12-04 Thread Lie Ryan

On 12/4/2009 5:24 PM, Alf P. Steinbach wrote:

Hi.

I discovered with tkinter the registration of widgets with layout
managers (tkinter "geometry" managers, e.g. calls to pack()) needs to be
done very hierarchically.

And this leads to hierarchical code, which would be nice to indicate by
indenting, but oops, indenting in Python is syntactically significant...

So first I thought of one routine per widget creation & layout
registration, but that was very ugly and verbose. Then thought of simply
using semicolons but I didn't even try that, because I imagined the
sheer ugliness. Then I sort of landed on the solution below, but
although using the language to define a kind of special purpose
mini-language is common in C++ and Lisp I haven't seen so much of that
in Python examples, and so I wonder whether this is Pythonic or perhaps
so extremely un-Pythonic (unconventional) that it's scary -- I mean,
calls that do nothing whatsoever, but I think of *visual structure* as
very important here and IMHO (disregarding Pythonicity issues) worth the
overhead...


maybe you can extend it a bit and make it more useful by auto-packing 
the widget when the with-block ended. As for the case when you need to 
pass arguments to the packer, perhaps the packing manager's argument 
could be turned into an attribute like so:


import tkinter as tk

root = tk.Tk()
with Place(root, tk.Frame()) as display_area:
pic = tk.PhotoImage( file = "lightbulb_off.gif" )
with Pack(display_area, tk.Label) as pic_display:
pic_display.image = pic
# or perhaps just pic_display.side = "left"
pic_display.pack_side = "left"
with Pack(display_area, tk.Frame) as interaction_area:
interaction_area.width = 500
with Pack(interaction_area, tk.Label) as status_line:
status_line.text = "The switch is OFF"
status_line.pack_anchor = "w"
with Pack(interaction_area, tk.Button) as toggle_button:
toggle_button.text = " Toggle it "
toggle_button.pack_anchor = "w"
interaction_area.pack_side = "left"
display_area.place_relx = 0.5
display_area.place_rely = 0.5
display_area.place_anchor = "center"

something like this would make working with GUI much less painful...
--
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-12-04 Thread Lie Ryan

On 12/5/2009 6:53 AM, geremy condra wrote:

To be fair, I don't think you'd have to look very far to find places
where a graph representation is approximated using some
combination of dicts, sets, and lists. ElementTree comes to mind
immediately, and the dict-of-dicts idea for logging recently
discussed on python-dev explicitly states that it uses that
structure to represent object graphs. To me that says that there
is at least some demand.


Though I've never used ElementTree extensively before, I thought it was 
supposed to use a Tree structure (though it is a subset of graph, the 
need for tree is much more common than full-blown graph package).

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


Partial list comprehensions

2009-12-04 Thread Joel Davis
Is it possible to run a list comprehension over a certain portion of
the list? My goals is to be able to run the comprehension on the
innermost elements of the list, but leaving the outermost intact.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Partial list comprehensions

2009-12-04 Thread Stephen Hansen
>
> Is it possible to run a list comprehension over a certain portion of
> the list? My goals is to be able to run the comprehension on the
> innermost elements of the list, but leaving the outermost intact.
>

Without seeing an example of what your list is, and what you want to turn it
into, its sort of hard to be certain what it is you really want to do.

Is it:

>>> a = range(100)
>>> a[2:-2] = [str(x) for x in a[2:-2]]
>>> a
[0, 1, '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14',
'15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26',
'27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38',
'39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50',
'51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62',
'63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74',
'75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86',
'87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', 98, 99]

Where I converted to a string the "inner" elements with a list comprehension
but left the outer ones alone?

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


Re: Partial list comprehensions

2009-12-04 Thread Mensanator
On Dec 4, 2:22 pm, Joel Davis  wrote:
> Is it possible to run a list comprehension over a certain portion of
> the list? My goals is to be able to run the comprehension on the
> innermost elements of the list, but leaving the outermost intact.

Something like this?

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = [i for i in a[0:5]]
>>> b
[0, 1, 2, 3, 4]
>>> c = [i for i in a if i%2==0]
>>> c
[0, 2, 4, 6, 8]
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-12-04 Thread geremy condra
On Fri, Dec 4, 2009 at 3:10 PM, Lie Ryan  wrote:
> On 12/5/2009 6:53 AM, geremy condra wrote:
>>
>> To be fair, I don't think you'd have to look very far to find places
>> where a graph representation is approximated using some
>> combination of dicts, sets, and lists. ElementTree comes to mind
>> immediately, and the dict-of-dicts idea for logging recently
>> discussed on python-dev explicitly states that it uses that
>> structure to represent object graphs. To me that says that there
>> is at least some demand.
>
> Though I've never used ElementTree extensively before, I thought it was
> supposed to use a Tree structure (though it is a subset of graph, the need
> for tree is much more common than full-blown graph package).

Sure, its a tree, which is also a graph. In this case it looks to
me more like a directed acyclic graph than anything, but its
pretty much just semantics since the interface is functionally
equivalent.

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


Re: Killing Another Bug

2009-12-04 Thread Stephen Hansen
On Fri, Dec 4, 2009 at 7:52 AM, Victor Subervi wrote:

> except:
>


> except:
>   pass
>

If you want any hope of fixing the bug, remove both of these. Really -- do
not use bare excepts.

In the first one, it looks like you're expecting sometimes there to be an
exception: that's okay. If you think an operation will produce one, its okay
to catch it if you know how to handle it.  But do NOT use bare excepts.
Catch the actual exception you are expecting-- a KeyError maybe? ValueError?
I don't know, can't tell without knowing what "fn" does.

In the second-- that bare except with a pass is doing absolutely nothing but
_destroying_ any chance you have of finding out what the bug IS and fixing
the bug. Remove that entire try/except: pass statement. Really. You
absolutely have to do it. The only reason you have not already found and
fixed this bug is that you have done this-- you can't do this and then ask
us to find the bug for you.

Bare excepts are there for a reason, and there are times to use them. But
those are the exception and not the rule; and the time to use a except: pass
construct is NOT when you're trying to fix a bug.


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


Re: Which is more pythonic?

2009-12-04 Thread nn
On Dec 3, 10:41 am, Filip Gruszczyński  wrote:
> I have just written a very small snippet of code and started thinking,
> which version would be more pythonic. Basically, I am adding a list of
> string to combo box in qt. So, the most obvious way is:
>
> for choice in self.__choices:
>         choicesBox.addItem(choice)
>
> But I could also do:
>
> map(self.__choices, choicesBox.addItem)
>
> or
>
> [choicesBox.addItem(choice) for choice in self.__choices]
>
> I guess map version would be fastest and explicit for is the slowest
> version. However, the first, most obvious way seems most clear to me
> and I don't have to care about speed with adding elements to combo
> box. Still, it's two lines instead of one, so maybe it's not the best.
> So, which one is?
>
> --
> Filip Gruszczyński

First option is the most pythonic IMO. If it HAS to be one line I
would still prefer:

for choice in self.__choices: choicesBox.addItem(choice)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to tell if you're running on windows?

2009-12-04 Thread Roy Smith
In article ,
 David Robinow  wrote:

> On Fri, Dec 4, 2009 at 1:46 PM, Roy Smith  wrote:
> > I'm using 2.5.1.  How can I tell if I'm running on windows?  The
> > obvious answer, platform.system(), gets complicated.  On the python
> > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got
> > a native windows build of python where it returns 'Microsoft'.
> >
> > The real problem I'm trying to solve is whether to build a LIBPATH
> > environment variable with ';' or ':' delimiting the entries.  On the
> > cygwin build, os.pathsep returns ':', which isn't really correct.  If
> > you use that, you end up building paths that look like c:foo:c:bar.
> > It should be c:foo;c:bar
> 
> It's not clear to me what you're using LIBPATH for.
> Are you running a cygwin executable from Python? Or a Windows
> executable from cygwin?

Our build and test environment for windows is cygwin.  This is a Python 
test script running a native windows executable using subprocess.Popen().  
The LIBPATH I'm building is for the executable's environment.

We're looking to possibly replace cygwin with MinGW at some point in the 
future.  In the past, we've always equated "cygwin" and "windows" in our 
build scripts, but now that we're thinking MinGW-ish thoughts, that's 
looking like a sub-optimal strategy.

> LIBPATH should be in the format desired by the consumer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are routine objects guaranteed mutable & with dictionary?

2009-12-04 Thread Terry Reedy

Alf P. Steinbach wrote:
 > The question is what guarantees or absence thereof the language

specification, PEPs, intentions, whatever gives/has.


The two docs backed up by PEPs. I suppose the docs could be clearer.
5.3.1 says "The primary must evaluate to an object of a type that 
supports attribute references, which most objects do." This is true for 
attribute access, but not for attribute setting. See


http://bugs.python.org/issue7436

for my suggest addition.


BTW, it's a function, not a "routine"


Wikipedia is your friend, http://en.wikipedia.org/wiki/Subroutine>.


which says "the C and C++ programming languages, subprograms are 
referred to as "functions" (or "methods" when associated with a class)."
The same is true for Python and many other languages. Some languages 
have separate statements for defining functions and (non-function) 
subroutines. If you want to be understood, use function. I thought you 
mean 'routine' as opposed to 'special'.


Terry Jan Reedy

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


Re: Insane Problem

2009-12-04 Thread Terry Reedy

Victor Subervi wrote:

I'm not rude


To me, asking for help without providing sufficient information, 
especially when requested, is a form of rudeness.



Think about that and don't be rude.


Exactly.

Terry Jan Reedy

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


Re: python bijection

2009-12-04 Thread Terry Reedy

M.-A. Lemburg wrote:


Integrating an easy-to-use graph library into the collections
module (and it's C companion) is good idea.


This would have to be written in C, though,

That's currently in the works, along with database backing.
We'd welcome any help though... hint, hint...


The current thinking among deveopers is that new modules should be 
written and maintained in Python, which all implementations can use, 
with speed-critical parts written in C for speed and imported by the 
Python code.


You can write a PEP offering Graphine. To be accepted, there would need 
to be some evidence that is the best Python graph module avaible and has 
some community support.


I would probably use it more that 90% of the stdlib.

Terry Jan Reedy

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


Re: Killing Another Bug

2009-12-04 Thread Victor Subervi
On Fri, Dec 4, 2009 at 3:46 PM, Stephen Hansen wrote:

>
> On Fri, Dec 4, 2009 at 7:52 AM, Victor Subervi wrote:
>
>> except:
>>
>
>
>> except:
>>   pass
>>
>
> If you want any hope of fixing the bug, remove both of these. Really -- do
> not use bare excepts.
>
> In the first one, it looks like you're expecting sometimes there to be an
> exception: that's okay. If you think an operation will produce one, its okay
> to catch it if you know how to handle it.  But do NOT use bare excepts.
> Catch the actual exception you are expecting-- a KeyError maybe? ValueError?
> I don't know, can't tell without knowing what "fn" does.
>
> In the second-- that bare except with a pass is doing absolutely nothing
> but _destroying_ any chance you have of finding out what the bug IS and
> fixing the bug. Remove that entire try/except: pass statement. Really. You
> absolutely have to do it. The only reason you have not already found and
> fixed this bug is that you have done this-- you can't do this and then ask
> us to find the bug for you.
>
> Bare excepts are there for a reason, and there are times to use them. But
> those are the exception and not the rule; and the time to use a except: pass
> construct is NOT when you're trying to fix a bug.
>

Right <:-}
I changed the "pass" to "raise" and discovered an error I "worked around"
while I was trying to solve another problem...then subsequently forgot about
this. You know, I'm really a poet and singer/songwriter, unfortunately that
doesn't pay the bills. When will I ever learn to think in my left hemisphere
like a programmer :-}
Thanks,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


question about subprocess and shells

2009-12-04 Thread Ross Boylan
If one uses subprocess.Popen(args, ..., shell=True, ...)

When args finishes execution, does the shell terminate?  Either way
seems problematic.

If it does not terminate, then it seems as if calls like wait and
communicate would never return.  It also seems the subprocess would
never die, and that most of the examples with the shell True would leave
processes lying around.

If it does terminate, then how can you stuff new commands down the pipe
to the subprocesses stdin?

Does this module contemplate receiving multiple commands for the shell
to execute?

I'm also unsure of the semantics of the pipes for the processes standard
file handles.  Do they need to be closed (judging from the examples,
no)?  When reads/writes to them return, and what state is the stream in
at the time?

Thanks for any wisdom you can offer.
Ross Boylan 

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


subprocess kill

2009-12-04 Thread luca72
Hello i'm using subprocess in this way:
self.luca = subprocess.Popen(['/usr/bin/
dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e )

then i kill:
self.luca.Kill()

but the process is still active and the file self.f_s_l increase it
size because the process is not killed.

How i can kill the process?
Regards

Luca

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


Specifying an API for a straeming parser

2009-12-04 Thread tyler
Howdy folks, I'm working on a JSON Python module [1] and I'm struggling with an
appropriate syntax for dealing with incrementally parsing streams of data as
they come in (off a socket or file object). 

The underlying C-level parsing library that I'm using (Yajl [2]) already uses a
callback system internally for handling such things, but I'm worried about:
  * Ease of use, simplicity
  * Python method invocation overhead going from C back into Python

One of the ideas I've had is to "iterparse" a la:

>>> for k, v in yajl.iterloads(fp):
... print ('key, value', k, v)
>>> 

Effectively building a generator for the JSON string coming off of the `fp`
object and when generator.next() is called reading more of the stream object.
This has some shortcomings however:
  * For JSON like: '''{"rc":0,"data":}''' the iterloads() 
function would block for some time when processing the value of the "data"
key.
  * Presumes the developer has prior knowledge of the kind of JSON strings
being passed in

I've searched around, following this "iterloads" notion, for a tree-generator
and I came up with nothing.

Any suggestions on how to accomplish iterloads, or perhaps a suggestion for a
more sensible syntax for incrementally parsing objects from the stream and
passing them up into Python?

Cheers,
-R. Tyler Ballance
--
 Jabber: rty...@jabber.org
 GitHub: http://github.com/rtyler
Twitter: http://twitter.com/agentdero
   Blog: http://unethicalblogger.com



[1] http://github.com/rtyler/py-yajl
[2] http://lloyd.github.com/yajl/




pgpGivehhqfe6.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Insane Problem

2009-12-04 Thread Lie Ryan

On 12/5/2009 8:27 AM, Terry Reedy wrote:

Victor Subervi wrote:

I'm not rude


To me, asking for help without providing sufficient information,
especially when requested, is a form of rudeness.


Think about that and don't be rude.


Why does this sounds familiar?
http://groups.google.com/group/comp.lang.python/msg/21e80ac383745d88
--
http://mail.python.org/mailman/listinfo/python-list


Re: Partial list comprehensions

2009-12-04 Thread Joel Davis
On Dec 4, 3:41 pm, Mensanator  wrote:
> On Dec 4, 2:22 pm, Joel Davis  wrote:
>
> > Is it possible to run a list comprehension over a certain portion of
> > the list? My goals is to be able to run the comprehension on the
> > innermost elements of the list, but leaving the outermost intact.
>
> Something like this?
>
> >>> a
>
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> >>> b = [i for i in a[0:5]]
> >>> b
> [0, 1, 2, 3, 4]
> >>> c = [i for i in a if i%2==0]
> >>> c
> [0, 2, 4, 6, 8]
>
>

Yes, sort of like that but Hansen's code is actually exactly what I
was getting at, not sure why he deleted it:

>>> a = range(100)
>>> a[2:-2] = [str(x) for x in a[2:-2]]
>>> a
[0, 1, '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',
'14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24',
'25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35',
'36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46',
'47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57',
'58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68',
'69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79',
'80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90',
'91', '92', '93', '94', '95', '96', '97', 98, 99]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Partial list comprehensions

2009-12-04 Thread Stephen Hansen
On Fri, Dec 4, 2009 at 2:11 PM, Joel Davis  wrote:

> Yes, sort of like that but Hansen's code is actually exactly what I
> was getting at, not sure why he deleted it:



Huh? I deleted it?

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


Re: Difference between mutex.mutex and threading.Lock

2009-12-04 Thread zeph
The mutex class (and module) should not be used, since it is, as you
said, deprecated for 3.0. Like the docs say, it "does not require (or
imply) threading or multi-tasking, though it could be useful for those
purposes."  The mutex class' lock() method takes a function and args
and if the mutex is unlocked, calls the function with args
immediately, or if locked, adds to a queue and waits for it to be
unlocked

The threading.Lock object is a lock shared between threads.  For
example, if you have two threads (thread1 and thread2) and thread1
does lock.acquire() and thread 2 calls lock.acquire(), thread2 will
block until thread1 calls lock.release(), then thread2 will get a
chance to run its critical code section, then call lock.release().

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


Re: subprocess kill

2009-12-04 Thread Mike Driscoll
On Dec 4, 3:50 pm, luca72  wrote:
> Hello i'm using subprocess in this way:
> self.luca = subprocess.Popen(['/usr/bin/
> dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e )
>
> then i kill:
> self.luca.Kill()
>
> but the process is still active and the file self.f_s_l increase it
> size because the process is not killed.
>
> How i can kill the process?
> Regards
>
> Luca

See http://lmgtfy.com/?q=python+kill+subprocess+linux

When I do that on my machine, the 2nd result has the answer:

http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kill-a-subprocess

---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-12-04 Thread Carl Banks
On Dec 4, 12:46 pm, geremy condra  wrote:
more common than full-blown graph package).
> Sure, its a tree, which is also a graph. In this case it looks to
> me more like a directed acyclic graph than anything, but its
> pretty much just semantics since the interface is functionally
> equivalent.

I'd have to agree with Lie, yes a tree is a graph, but it's simply not
an argument that Python community is grasping for graph structures.
It's like arguing that the Python community could benefit from a
quaternion type, because quaternions are actually heavily used in
Python, because a scalar number is a quarternion.

Carl Banks

(Would be +1 on a good graph implementation... just not because of
ElementTree.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about subprocess and shells

2009-12-04 Thread Lie Ryan

On 12/5/2009 8:38 AM, Ross Boylan wrote:

If one uses subprocess.Popen(args, ..., shell=True, ...)

When args finishes execution, does the shell terminate?  Either way
seems problematic.

If it does not terminate, then it seems as if calls like wait and
communicate would never return.  It also seems the subprocess would
never die, and that most of the examples with the shell True would leave
processes lying around.


No, p.wait() will immediately return, and p.communicate() discards 
everything new coming.



If it does terminate, then how can you stuff new commands down the pipe
to the subprocesses stdin?


start a new shell, of course.


Does this module contemplate receiving multiple commands for the shell
to execute?


yes, use several subprocess.Popen() or call a batch/shell script.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Connecting to the users preferred email client

2009-12-04 Thread Tuomas Vesterinen

Mike Driscoll wrote:

On Dec 4, 5:28 am, Tuomas Vesterinen  wrote:

If I want to open a html-page from Python code I can say:

 >>> import webbrowser
 >>> webbrowser.open('index.html')

Is there a standard way to init an email in users preferred email client
like Thubderbird, Evolution etc.?

Tuomas Vesterinen


Check this thread out:

http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx

Basically, the idea is to pass the mailto url to webbrowser.



OK, that's where we are. Thanks.

Tuomas Vesterinen


---
Mike Driscoll

Blog:   http://blog.pythonlibrary.org

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


Re: subprocess kill

2009-12-04 Thread luca72
On 4 Dic, 23:23, Mike Driscoll  wrote:
> On Dec 4, 3:50 pm, luca72  wrote:
>
> > Hello i'm using subprocess in this way:
> > self.luca = subprocess.Popen(['/usr/bin/
> > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e )
>
> > then i kill:
> > self.luca.Kill()
>
> > but the process is still active and the file self.f_s_l increase it
> > size because the process is not killed.
>
> > How i can kill the process?
> > Regards
>
> > Luca
>
> Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux
>
> When I do that on my machine, the 2nd result has the answer:
>
> http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil...
>
> ---
> Mike Driscoll
>
> Blog:  http://blog.pythonlibrary.org

Hello Mike i have also test but they never kill the process the file
(stdout=self.f_s_l) increase it's size, haveyou some idea.
also if i close the program the process is still active.

Regards

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


Question on class module import

2009-12-04 Thread monkeyboy
Hello,

I want to write a wrapper class around a windows dll. If I put the
class in a module "Refprop.py" then import the class where I want to
use it, does the whole module get read by the interpreter or just the
class code?...

For example if I say the following in "Refprop.py" does the code above
the class statement get run on an import or should the loadLibrary
call be made in the constructor...the code below appears to work OK, I
just want to be sure I understand what happens on an import call

from ctypes import *
rp = windll.LoadLibrary("refprop.dll")

   class refprop():
'''
   REFPORP class
'''
   nc = c_long(1)
   ierr = c_long(0)
   ..


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


Re: subprocess kill

2009-12-04 Thread luca72
On 5 Dic, 00:03, luca72  wrote:
> On 4 Dic, 23:23, Mike Driscoll  wrote:
>
>
>
> > On Dec 4, 3:50 pm, luca72  wrote:
>
> > > Hello i'm using subprocess in this way:
> > > self.luca = subprocess.Popen(['/usr/bin/
> > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e )
>
> > > then i kill:
> > > self.luca.Kill()
>
> > > but the process is still active and the file self.f_s_l increase it
> > > size because the process is not killed.
>
> > > How i can kill the process?
> > > Regards
>
> > > Luca
>
> > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux
>
> > When I do that on my machine, the 2nd result has the answer:
>
> >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil...
>
> > ---
> > Mike Driscoll
>
> > Blog:  http://blog.pythonlibrary.org
>
> Hello Mike i have also test but they never kill the process the file
> (stdout=self.f_s_l) increase it's size, haveyou some idea.
> also if i close the program the process is still active.
>
> Regards
>
> Luca

i'm able only to kill via shell like kill -9 process pid, Why?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difference between mutex.mutex and threading.Lock

2009-12-04 Thread Roy Smith
In article 
,
 zeph  wrote:

> The mutex class (and module) should not be used, since it is, as you
> said, deprecated for 3.0. Like the docs say, it "does not require (or
> imply) threading or multi-tasking, though it could be useful for those
> purposes."

Over the years, many things about Python have surprised, amused, and on 
occasion confused, me.  I must admit, having a mutex which isn't 
thread-safe is pretty high up on the list of "does not fit my brain" items 
:-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Redirecting stdin to a file

2009-12-04 Thread candide
How do I redirect stdin to a text file ? In C, this can be done with the
freopen() standard function, for instance

FILE *foo = freopen("in.txt", "r", stdin);


redirects stdin to the in.txt text file. Does anyone know a freopen()
Python equivalent ?

Notice that I'm not referring to shell redirection as the following
command line shows :

$ python myCode.py < in.txt

I need to hardcode the redirection inside the python source file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess kill

2009-12-04 Thread luca72
On 5 Dic, 00:14, luca72  wrote:
> On 5 Dic, 00:03, luca72  wrote:
>
>
>
> > On 4 Dic, 23:23, Mike Driscoll  wrote:
>
> > > On Dec 4, 3:50 pm, luca72  wrote:
>
> > > > Hello i'm using subprocess in this way:
> > > > self.luca = subprocess.Popen(['/usr/bin/
> > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e )
>
> > > > then i kill:
> > > > self.luca.Kill()
>
> > > > but the process is still active and the file self.f_s_l increase it
> > > > size because the process is not killed.
>
> > > > How i can kill the process?
> > > > Regards
>
> > > > Luca
>
> > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux
>
> > > When I do that on my machine, the 2nd result has the answer:
>
> > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil...
>
> > > ---
> > > Mike Driscoll
>
> > > Blog:  http://blog.pythonlibrary.org
>
> > Hello Mike i have also test but they never kill the process the file
> > (stdout=self.f_s_l) increase it's size, haveyou some idea.
> > also if i close the program the process is still active.
>
> > Regards
>
> > Luca
>
> i'm able only to kill via shell like kill -9 process pid, Why?

Now the only way to solve the problem is to call a c program that kill
the process via subprocess in other case i can't close it, i have also
try with

subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is
still active

Regards

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


Re: Question on class module import

2009-12-04 Thread MRAB

monkeyboy wrote:

Hello,

I want to write a wrapper class around a windows dll. If I put the 
class in a module "Refprop.py" then import the class where I want to 
use it, does the whole module get read by the interpreter or just the

class code?...


[snip]
The whole module will be run.

In Python 'def' and 'class' aren't declarations, but statements, which
have the side-effect of creating the function or class and binding it to
a name in the enclosing namespace.

If a module contains:

print "The start"

class Foo():
pass

print "The finished"

and then you import it, it'll print "The Start", then create a class
called "Foo" within the module's namespace, then print "The end".
--
http://mail.python.org/mailman/listinfo/python-list


How to timeout when waiting for raw_input from user ?

2009-12-04 Thread northof40
Hi - I'm writing a *very* simple program for my kids. It asks the user
to give it the answer to a maths question and says "right" or "wrong"

They now want a timed version where they would only get so long to
respond to the question.

I'm thinking of some logic where a raw_input call is executed and then
if more than X seconds elapses before the prompt is replied to the
process writes a message "Sorry too slow" (or similar).

I can't see the wood for the trees here - what's the best way to do
this given the rather simple environment it's needed within.

Regards

richard.

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


Re: Redirecting stdin to a file

2009-12-04 Thread MRAB

candide wrote:

How do I redirect stdin to a text file ? In C, this can be done with
the freopen() standard function, for instance

FILE *foo = freopen("in.txt", "r", stdin);


redirects stdin to the in.txt text file. Does anyone know a freopen()
Python equivalent ?

Notice that I'm not referring to shell redirection as the following 
command line shows :


$ python myCode.py < in.txt

I need to hardcode the redirection inside the python source file.


The standard input is sys.stdin and the standard output is sys.stdout.

sys.stdin.close()
sys.stdin = open("in.txt", "r")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question on class module import

2009-12-04 Thread Steven D'Aprano
On Fri, 04 Dec 2009 15:10:49 -0800, monkeyboy wrote:

> Hello,
> 
> I want to write a wrapper class around a windows dll. If I put the class
> in a module "Refprop.py" then import the class where I want to use it,
> does the whole module get read by the interpreter or just the class
> code?...

Every import always involves a module. You can't import a class in 
isolation. Even if you use the form "from module import object", the 
entire module gets loaded first, in order to access the object.



> For example if I say the following in "Refprop.py" does the code above
> the class statement get run on an import 

Only the first time you import it. After that, the module is cached.


> or should the loadLibrary call
> be made in the constructor...

Do you want to call loadLibrary every time you create an instance? Then 
put it in the constructor.

Do you want to call loadLibrary only once? Then leave it were it is.



> the code below appears to work OK, I just
> want to be sure I understand what happens on an import call

Python looks in sys.modules to see if the module has already been loaded. 
If it has, it returns the module.

If not, it searches for the module. If it finds it, then it executes the 
code in the module, caches the module object in sys.modules, and returns.



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


Re: How to timeout when waiting for raw_input from user ?

2009-12-04 Thread northof40
On Dec 5, 12:52 pm, northof40  wrote:
> Hi - I'm writing a *very* simple program for my kids. It asks the user
> to give it the answer to a maths question and says "right" or "wrong"
>
> They now want a timed version where they would only get so long to
> respond to the question.
>
> I'm thinking of some logic where a raw_input call is executed and then
> if more than X seconds elapses before the prompt is replied to the
> process writes a message "Sorry too slow" (or similar).
>
> I can't see the wood for the trees here - what's the best way to do
> this given the rather simple environment it's needed within.
>
> Regards
>
> richard.

Sorry I should said that based upon other answers I've seen to similar
questions this needs to run on a windows machine (other answers
suggest this is more difficult than running on *nix)

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


Re: Redirecting stdin to a file

2009-12-04 Thread Lie Ryan

On 12/5/2009 10:31 AM, candide wrote:

How do I redirect stdin to a text file ? In C, this can be done with the
freopen() standard function, for instance

FILE *foo = freopen("in.txt", "r", stdin);


redirects stdin to the in.txt text file. Does anyone know a freopen()
Python equivalent ?

Notice that I'm not referring to shell redirection as the following
command line shows :

$ python myCode.py<  in.txt

I need to hardcode the redirection inside the python source file.


I'm not sure how freopen() works in C, but perhaps you're looking for 
redirecting sys.stdin:

import sys
old_stdin = sys.stdin # save it, in case we need to restore it
sys.stdin = open('myfile')

you can also restore stdin using sys.__stdin__ instead of saving the old 
one, but in the case you or someone else is redirecting the stdin twice...

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


Re: Redirecting stdin to a file

2009-12-04 Thread candide
@MRAB
@Lie Ryan

Thanks, it works fine !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-12-04 Thread Lie Ryan

On 12/5/2009 9:41 AM, Carl Banks wrote:

On Dec 4, 12:46 pm, geremy condra  wrote:
more common than full-blown graph package).

Sure, its a tree, which is also a graph. In this case it looks to
me more like a directed acyclic graph than anything, but its
pretty much just semantics since the interface is functionally
equivalent.


I'd have to agree with Lie, yes a tree is a graph, but it's simply not
an argument that Python community is grasping for graph structures.
It's like arguing that the Python community could benefit from a
quaternion type, because quaternions are actually heavily used in
Python, because a scalar number is a quarternion.

>

Carl Banks

(Would be +1 on a good graph implementation... just not because of
ElementTree.)


I think this could be an interpretation of the Zen:

Simple is better than complex.
Complex is better than complicated.

can be read as:
List is better than Tree
Tree is better than Graph

not having Tree and Graph package in the standard library force most 
people to find List-based solution. And people that know they need 
graphs will find them in 3rd party modules. I have needed Trees a few 
times in python, but very rarely a Graph (except for playing around). 
YMDWV (your mileage definitely will vary).

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


[distutils] Install script under a different name

2009-12-04 Thread Nikolaus Rath
Hello,

All my Python files have extension .py. However, I would like to install
scripts that are meant to be called by the user without the suffix, i.e.
the file scripts/doit.py should end up as /usr/bin/doit.

Apparently the scripts= option of the setup() function does not support
this directly. Is there a clever way to get what I want?


Best,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C
-- 
http://mail.python.org/mailman/listinfo/python-list


package_data question

2009-12-04 Thread Miki
Hello All,

I'm trying to add package_data from outside the package directory.
The current project looks like:
.
|-- __init__.py
|-- a
|   `-- src
|   `-- py
|   `-- __init__.py
|-- b
|   `-- src
|   `-- py
|   `-- __init__.py
|-- c
|   `-- src
|   `-- py
|   `-- __init__.py
|-- dlls
|   `-- c.dll
`-- setup.py

I'd like to get c.dll inside the p.c directory, so I wrotefrom
setuptools import setup
setup(
   name='p',
   package_dir={
   'p' : '.',
   'p.a' : 'a/src/py',
   'p.b' : 'b/src/py',
   'p.c' : 'c/src/py',
},
packages=['p', 'p.a', 'p.b', 'p.c'],
include_package_data=True,
package_data = {
'p.c' : [ 'dlls/c.dll' ]
}
)

However c.dll is not copied.
build/lib.linux-x86_64-2.6
`-- p
|-- __init__.py
|-- a
|   `-- __init__.py
|-- b
|   `-- __init__.py
`-- c
`-- __init__.py


Any idea how to fix this?
(Changing the directory structure is not possible - not my project).

Thanks,
--
Miki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python bijection

2009-12-04 Thread geremy condra
On Fri, Dec 4, 2009 at 5:41 PM, Carl Banks  wrote:
> On Dec 4, 12:46 pm, geremy condra  wrote:
> more common than full-blown graph package).
>> Sure, its a tree, which is also a graph. In this case it looks to
>> me more like a directed acyclic graph than anything, but its
>> pretty much just semantics since the interface is functionally
>> equivalent.
>
> I'd have to agree with Lie, yes a tree is a graph, but it's simply not
> an argument that Python community is grasping for graph structures.
> It's like arguing that the Python community could benefit from a
> quaternion type, because quaternions are actually heavily used in
> Python, because a scalar number is a quarternion.

Fair enough. I suspect that other examples could be provided
easily enough that I'm not going to fight over that one.

> Carl Banks
>
> (Would be +1 on a good graph implementation... just not because of
> ElementTree.)

I'd love it if you'd take a look at Graphine and see whether
it would meet the standard for a good graph implementation.

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


  1   2   >