Re: No matter what I do, IDLE will not work...

2011-11-10 Thread Ned Deily
In article 
<415ed0ec-65a5-41df-b81e-d74786c74...@s5g2000vbe.googlegroups.com>,
 CAMERON ALLEY  wrote:
> IT WORKS I didn't change my activestate, but I downloaded python
> 3.2.2 with the 32 bit installer and it works! Perfectally!!
> 
> Sir you're my savior, thank you so much.
> 
> I don't know how you did it but you just made my day :)

The 32-bit-installer links to the older Carbon-based Tcl/Tk 8.4 which is 
very different under the covers from the Tcl/Tk 8.5 used by the 
Apple-supplied Pythons and the python.org 64-bit installer.  So there's 
*something* on your system that interferes with the Cocoa Tcl/Tk 8.5.  
If you want to pursue it, you might ask on the OS X Tcl mailing list.  
Good luck!

http://dir.gmane.org/gmane.comp.lang.tcl.mac

-- 
 Ned Deily,
 n...@acm.org

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


Re: property decorator and inheritance

2011-11-10 Thread Chris Rebert
On Thu, Nov 10, 2011 at 9:17 PM, Laurent  wrote:
> Yes using a separate class variable would transfer the problem to the class 
> level. But adding 10 class variables if I have 10 properties would be ugly. 
> Maybe I should reformulate the subject of this thread to "is there some 
> python magic to pass parameters to decorator-declared properties ?"

Apparently, yes:

>>> class Foo(object):
... @property
... def bar(self, arg1='baz', arg2='qux'):
... return arg1, arg2
...
>>> Foo.bar.fget(Foo(), 'spam', 'eggs')
('spam', 'eggs')
>>>

Though I do not like this trick at all.

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-10 Thread OKB (not okblacke)
Laurent wrote:

> Yes using a separate class variable would transfer the problem to
> the class level. But adding 10 class variables if I have 10
> properties would be ugly. Maybe I should reformulate the subject of
> this thread to "is there some python magic to pass parameters to
> decorator-declared properties ?" 

You can't have it both ways.  If you want

myObj.greeting2 # No parentheses

To evaluate to a string (which it will if it's a property as you 
set it up), then it is necessarily true that myObj.greeting2(somearg) is 
going to try to call that string, which isn't going to work.  If you 
need to be able to pass in parameters, then you need greeting2 to be a 
real method, not a property, and you need to get the greeting string 
with

myObj.greeting2() # Parentheses

All this is as it should be.  The whole point of properties is that 
outside functions accessing them don't "know" that a getter function is 
called behind the scenes.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-10 Thread OKB (not okblacke)
Devin Jeanpierre wrote:

>> '--' not being allowed for a name has *nothing* to do with exec, and
>> everything to do with `--` not being a valid Python identifier. 
> 
> The only reason valid python identifiers come into it at all is
> because they get pasted into a string where identifiers would go, and
> that string is passed to exec().

The whole point of named tuples is to be able to access the members 
via attribute access as in "obj.attr".  Things like "obj.--" are not 
valid Python syntax, so you can't use "--" as the name of a namedtuple 
field.  Yes, you can do "getattr(obj, '--')" if you want, but it's quite 
reasonable for namedtuple to refrain from catering to that sort of 
perverse usage.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-10 Thread Laurent
Yes using a separate class variable would transfer the problem to the class 
level. But adding 10 class variables if I have 10 properties would be ugly. 
Maybe I should reformulate the subject of this thread to "is there some python 
magic to pass parameters to decorator-declared properties ?"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: property decorator and inheritance

2011-11-10 Thread alex23
On Nov 11, 2:03 pm, Laurent  wrote:
> Hi. I couldn't find a way to overwrite a property declared using a decorator 
> in a parent class.

> class Polite:
>     @property
>     def greeting2(self, suffix=", my dear."):
>         return self._greeting + suffix

Here you set up greeting2 as a property.

> class Rude(Polite):
>     @property
>     def greeting2(self):
>         return super().greeting2(suffix=", stupid.")

Here you call Polite.greeting2 as a function.

> print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable

And here it's telling you that you're trying to treat a string - the
output of Polite.greeting2 - as a function.

The problem isn't that you cannot override greeting2 on Rude, it's
that you can't treat properties as functions, so you can't pass in a
new suffix. Instead, break the suffix out as a class attribute, then
each descendent just needs to override that attribute:

  class Polite(object):
suffix = ', my dear'

@property
def greeting(self):
  return 'Hello' + self.suffix

  class Rude(Polite):
suffix = ', stupid'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread CAMERON ALLEY
IT WORKS I didn't change my activestate, but I downloaded python
3.2.2 with the 32 bit installer and it works! Perfectally!!

Sir you're my savior, thank you so much.

I don't know how you did it but you just made my day :)

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


Re: all() is slow?

2011-11-10 Thread Devin Jeanpierre
> You will notice both of them keep the field name validation.

There are lots of reasons for that to be the case. To me, the most
likely one just seems to be that you don't want to remove more than
necessary when changing the way something works under the hood -- both
for compatibility reasons, and because you want the patch to get
accepted and want the least number of objectionable changes. I guess
you disagree.

> That is patently untrue. If you were implementing namedtuple without
> exec, you would still (or at least you *should*) prevent the user from
> passing invalid identifiers as attribute names. What's the point of
> allowing attribute names you can't actually *use* as attribute names?

Then why doesn't Python do this anywhere else? e.g. why can I
setattr(obj, 'a#b') when obj is any other mutable type?

I just don't believe this reasoning is what happened, I suppose. And
there's no way for you to convince me, or me to convince you, without
R. Hettinger stepping in here and verifying one side of the story.
This is subjective supposition, and that was supposed to be my most
objective opposition.

To go off on another tangent, though, I don't really understand how
you guys can think this is reasonable, though. I don't get this
philosophy of restricting inputs that would otherwise be perfectly
valid, just for concerns that you have that users might not share --
especially when it's valid everywhere else that the concept shows up.
It seems totally inconsistent with the attitude expressed above (by
you!) towards exec, which is that it's ok to be cautious of something,
but something else to forbid it outright.

Of course, as I said before, I don't agree with core python developers
on lots of things. I guess this is just another thing I just don't
understand.

Devin

On Thu, Nov 10, 2011 at 6:07 PM, Steven D'Aprano
 wrote:
> On Thu, 10 Nov 2011 15:37:05 -0500, Devin Jeanpierre wrote:
>
>>> '--' not being allowed for a name has *nothing* to do with exec, and
>>> everything to do with `--` not being a valid Python identifier.
>>
>> The only reason valid python identifiers come into it at all is because
>> they get pasted into a string where identifiers would go, and that
>> string is passed to exec().
>
> That is patently untrue. If you were implementing namedtuple without
> exec, you would still (or at least you *should*) prevent the user from
> passing invalid identifiers as attribute names. What's the point of
> allowing attribute names you can't actually *use* as attribute names?
>
> You could remove the validation, allowing users to pass invalid field
> names, but that would be a lousy API. If you want field names that aren't
> valid identifiers, the right solution is a dict, not attributes.
>
> Here's a re-implementation using a metaclass:
>
> http://pastebin.com/AkG1gbGC
>
> and a diff from the Python bug tracker removing exec from namedtuple:
>
> http://bugs.python.org/file11608/new_namedtuples.diff
>
>
> You will notice both of them keep the field name validation.
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread CAMERON ALLEY
On Nov 10, 7:27 pm, Ned Deily  wrote:
> That's an odd one; I've not seen a crash like that before.  From the
> crash dump, it is clear that the crash is happening inside of Tk, not
> Python, and, judging from the symbol names, it has something to do with
> menu initialization and colors.
>
> Try running the same Turtle test using the Apple-supplied Python 2.6
>
>   /usr/bin/python2.6
>
> The Apple-supplied Tcl/Tk that it uses is known to have a number of
> serious problems and should not be used for serious work but, for me, it
> will bring up the turtle window in Tk without crashing.  If it crashes
> the same way that 2.7.2 does, then that would be pretty solid
> corroboration that the problem is not in Python and more likely an issue
> with Tk.
>
> My first question would be do you have some third-party OS X app or
> extension installed that alters or colors menus?  I know there used to
> be some popular ones out there in the past.  If not, try opening System
> Preferences, select Displays, select Color, and check which display
> profile is selected.  Perhaps try selecting another.  And are you using
> a specific language in System Preferences -> Languages & Text ->
> Language?
>
> If that doesn't help, try running the following commands in a terminal
> window:
>
>   source /Library/Frameworks/Tk.framework/Versions/8.5/tkConfig.sh
>   echo $TK_VERSION $TK_PATCH_LEVEL
>
> You should see something like:
>
>   8.5 .11
>
> If not, double check that you really are using the latest ActiveState
> Tcl/Tk 8.5 installer from here:
>
>  http://www.activestate.com/activetcl/downloads
>
> Then try the failing turtle commads again and in the crash report,
> verify that  /Library/Frameworks/Tk.framework/Versions/8.5/ appear as
> framework paths and *not*
> /System/Library/Frameworks/Tk.framework/Versions/8.5/.
>
> Try the following command which may not work if you don't have Xcode
> tools installed:
>
>   otool -L $(python2.7 -c 'import _tkinter; print(_tkinter.__file__)')
>
> The paths reported again should start with
> /Library/Frameworks/Tk.framework and not
> /System/Library/Frameworks/Tk.framework.
>
> If none of that works, you could try installing the other python.org
> 2.7.2 installer, the 32-bit-only one, which is linked to the older
> Tcl/Tk 8.4, which uses Carbon interfaces rather than Cocoa, and see what
> happens with it.
>
> In any case, please report back what you find and, if necessary, open an
> issue on the Python bug tracker:
>  http://bugs.python.org/
>
> Thanks!
>
> --
>  Ned Deily,
>  n...@acm.org
Thanks so much for your incredibly in-depth response Ned!

I've tried everything you've suggested and here's what I've found:

The error occurs with the old python as well, but this MIGHT be
because at some point during my many attempts at fixing this issue I
could have deleted an old tk framework.

It's funny you mention the theming - before snow leapord, I had
leapord installed and used magnifique to theme my computer. I then
upgraded to snow leapord and (like a novice) tried to use magnifique
again only to find it crashed my system because it's not compatible
with snow leapord. I did a reinstall of the OS though, and everything
was fine. (this was about 2 years ago). I also recently installed
Crystal Black on here, however I've been having this issue since
before that. Other than that, no specific theming or color changing
schemes come to mind... Oh actually there is something called Nocturne
I used to use... Not sure if any of these could be affecting this.

There's only one color profile, and no bizarre language being used.

When I typed that in terminal, I saw 8.5.11 - this was the recommended
activestate by python.org. Should I get 8.5.11?

I tried the failing turtle commands, and in the crash report /Library/
Frameworks/Tk.framework/Versions/8.5/ only appears once (when doing a
cmd+f search) and does not have /System/ in front of it.

I'm going to try installing the 32 bit 2.7.2 installer next, and I'll
be back to let you know how it goes.

Thanks a lot!

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


property decorator and inheritance

2011-11-10 Thread Laurent
Hi. I couldn't find a way to overwrite a property declared using a decorator in 
a parent class. I can only do this if I use the "classic" property() method 
along with a getter function. Here's an example:

#!/usr/bin/python3

class Polite:

def __init__(self):
self._greeting = "Hello"

def get_greeting(self, suffix=", my dear."):
return self._greeting + suffix
greeting1 = property(get_greeting)

@property
def greeting2(self, suffix=", my dear."):
return self._greeting + suffix


class Rude(Polite):

@property
def greeting1(self):
return self.get_greeting(suffix=", stupid.")

@property
def greeting2(self):
return super().greeting2(suffix=", stupid.")


p = Polite()
r = Rude()

print("p.greeting1 =", p.greeting1)
print("p.greeting2 =", p.greeting2)
print("r.greeting1 =", r.greeting1)
print("r.greeting2 =", r.greeting2) # TypeError: 'str' object is not callable



In this example I can easily overwrite the greeting1 property. But the 
inherited greeting2 doesn't seem to be a property but a mere string.

I use a lot of properties decorators for simple properties in a project and I 
hate mixing them with a couple of "undecorated" properties that have to be 
overwritten in child classes. I tried using @greeting2.getter decorator and 
tricks like this but inheritance overwriting failed every time I used 
decorators.
 Can someone tell me a way to use decorator-declared properties that can be 
overwritten in child classes?? That would be nice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
A general description of my issue.

To my understand, python's feature such as "name-reference-object" and
"garbage collection" system did some of work for you, it makes your life
easier, but you still need to add your explicit application in your code.

For example,
Composition implementation: you may need to do 5 job with C++, but only 2
job with python, the other 3 job is done by python implicitly.
association implementation: You need 3 job with C++, but 1 with python. it
seems python's object's lifecycle handling has reached this level, all you
should do is just "associating and de-association".

Here is exactly of my question, for composition,
 the best code may be you do 2 job explicitly, 3 job done by python
implicitly.
Code_Zero. 1 job(by you) + 4(by python) does NOT work.
Code_one. 2 job(by you) + 3(by python) works. That is the best one.
Code_two. 3 job( by you) + 2 (by python) works too,
Code_three. 4 job(by you) + 1(by python) works too.

Since i am not familiar with python yet, my code most likely would gets
into Code_two or Code_three(Code_Zero is also possible for new guys like
me), though they also work, they are bad code.
What i am looking for is the Code_one example, i thought many OOP
application designer may have met this issue, so a good Code_one reference
is the best choice to start this project.

2011/11/11 Jerry Zhang 

>
>
> 2011/11/11 Chris Angelico 
>
>> On Fri, Nov 11, 2011 at 10:14 AM, Chris Kaynor 
>> wrote:
>> > Continuing this OT discussion, would it be a brain transplant, or a
>> > full body transplant?
>>
>> It's just a rebinding. You don't move the body, you just bind your
>> name to a new body. It's perfectly legal to have two names bound to
>> one body (cf Dr Jekyll and Mr Hyde); if you murder Mr Hyde, you can
>> still access the body through the other name.
>>
>> This is association, not aggregation or composition. You already realized
> that there is difference between these relationship(depending on your
> application requirement). and you are trying to tell me to code a
> aggregation and the composition with the same code.
>
>
>
>> ChrisA
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with databases (ODBC and ORMs) in Python 3.2

2011-11-10 Thread Jerry Zhang
2011/11/11 tkp...@hotmail.com 

> We are in the process of trying to decide between Python 2.7 and 3.2
> with a view to making a 5-10 year commitment to the right platform,
> and would appreciate some guidance on how best to connect to SQL
> databases in 3.2. ceODBC 2.01 provides an ODBC driver for Python 3.2,
> does anyone have experience using it? Also, are there any ORMs (object
> relational mapper)s that work well with 3,2?
>
I am in the similar situation as you. I abandon the MySQL + python3.x
solution, since translate between fields of tables(SQL table) and objects
attributes is destroying my OOP world.
I choose the ZODB + python2.x solution, python3.x does not support ZODB yet.


>
> Thanks in advance
>
> Thomas Philips
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/11 Chris Angelico 

> On Fri, Nov 11, 2011 at 10:14 AM, Chris Kaynor 
> wrote:
> > Continuing this OT discussion, would it be a brain transplant, or a
> > full body transplant?
>
> It's just a rebinding. You don't move the body, you just bind your
> name to a new body. It's perfectly legal to have two names bound to
> one body (cf Dr Jekyll and Mr Hyde); if you murder Mr Hyde, you can
> still access the body through the other name.
>
> This is association, not aggregation or composition. You already realized
that there is difference between these relationship(depending on your
application requirement). and you are trying to tell me to code a
aggregation and the composition with the same code.



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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/11 Terry Reedy 

> On 11/10/2011 9:31 AM, Jerry Zhang wrote:
>
> Unfortunately there is a difference between composition and
>>aggregation in my real word, and my application really care this
>>since it is trying to simulate this real world model, so my system
>>should track this difference accurately, otherwise the system may
>>not work well.
>>
>>For example,
>>a. the Cls_arm and Cls_body may be composition, but not aggregation.
>>My app must ensure that " one arm instance only live with one body
>>instance, if the body instance die, the arm instance must die.
>>
>
> Create the arm as a private member '_arm' of body and make sure that no
> method of body passes out a reference to the arm. (In Python, outside code
> can still grab a reference to the private attribute, but that is a coding
> bug.)
>
> I will point out that in the real world, dead donor transplants are based
> on the fact the parts of the body do NOT have to die when the composition
> does. I will not be surprised if we someday see arm transplants.

Thanks for your comment.
Actually you are mixing the concept. That is aggregation implementation,
which also points out there is difference between aggregation and
composition implementation. You already know that.

>
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/11 Benjamin Kaplan 

> On Thu, Nov 10, 2011 at 1:06 PM, Jerry Zhang 
> wrote:
> >
> >
> > I just did an example code to describe what i am looking for.
> >
> /**/
> > # ...
> >
> > class Head:
> > def __init__(self):
> > self.size = 5
> >
> > class Hat:
> > def __init__(self):
> > self.color = red
> > def took_on(self, body):
> > self.body = body
> > def took_off(self, body):
> > del self.body
> >
> > class Body:
> > def __init__(self):
> > self.head = Head()
> > def take_on_hat(self, hat):
> > self.hat = hat
> > hat.take_on(self)
> > def take_off_hat(self):
> > hat.take_off(self)
> > del self.hat
> > def go_to_heaven(self):
> > take_off_hat(self)
> > del self.head
> >
> /*--*/
> >
> > In this example, Head and body are COMPOSITION, which means
> > a. A head only live with one body, it can not live with other body. It
> can
> > not even live without body
> > b. If the body go to die, the head also go to die.
> >
> > Body and Hat are aggregation, which means
> > a. A hat live isolate with body, its life circle is isolate
> > b. A hat only live with one body at a specific time, it can not live with
> > two body(association would be more than one)
> >
> > So when the body die, the clean dead should include take_off Hat and del
> > Head, otherwise, the code definition is not prciselly describing the
> > relationship, which may cause a mess system, for example, a body has
> dead,
> > but one hat is still associated with a unreferenced body.
> > A point on this issue, maybe python is smart that the take_off_hat(self)
> is
> > not needed in go_to_heaven() method(i am not sure yet), but the del
> > self.head is sure needed, otherwise, we will have a no_body_head in our
> > ZODB, that is extremely horrible, right?
> >
> > All of these points one, the four kinds of class relationship in UML
> > precisely describe the real word, if the implementation is not precisely,
> > you will have unexpected results.
> > Of course, python may be smart to achieve such goal with less effort,
> that
> > is why i am asking for a code example for all of the four relationships.
>
> You're still misunderstanding Python's object model. del does NOT
> delete an object. It deletes a name. The only way for an object to be
> deleted is for it to be inaccessible (there are no references to it,
> or there are no reachable references to it).
> >>> foo = object()
> >>> bar = foo
> >>> foo
> 
> >>> bar
> 
> >>> del foo
> >>> bar
> 
> >>> foo
>
> Traceback (most recent call last):
>  File "", line 1, in 
>foo
> NameError: name 'foo' is not defined
>
>
> There is no way to force the go_to_heaven method to delete the head
> unless you can make sure that all other references to the head are
> weak references. If you need strictly-enforced relationships, Python
> is probably not the right language for the job- you'll be better off
> with C++ or Java.
>

Thanks for your reply, but i know your point on this before post this
issue. "doing the the job of python's garbage collecting" system is not i
want.
What i am trying to do is a python implementation of the real "composition
implementation".

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


Solution

2011-11-10 Thread Gagou Final Fantasy
A common problem when you generate executable on Windows 7 and deploy
on Windows XP.

According with the py2exe tutorial, you need include the MVC DLL. But
the tutorial is old and the script given search only in one directory.
Before, the directory contained all DLL and the manifest, but nowadays
it contains only the DLL. You need to specify another directory for
the manifest file. If you don't do that, you will have this kind of
error:

"this application has failed to start because the application
configuration is incorrect"

If you are on Windows 7 64 bits, you need the Microsoft Visual C
runtime DLL. Don't forget the manifest that isn't in the same
directory in Windows 7. You need to adapt the script like this:

data_files = [("VC90", glob(r'C:\Windows\winsxs
\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91\*.*')),
("VC90", glob(r'C:\Windows\winsxs\Manifests
\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91.manifest'))
]
setup(
data_files=data_files,
console = [{'script': "C:\test\my_program.py"}],
zipfile = None,
)


Now you can deploy the "dist" directory that contains all files and
dependencies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread Ned Deily
In article 
<3c2688bd-4f87-4eb1-9b40-3cb536a2d...@e3g2000vbs.googlegroups.com>,
 CAMERON ALLEY  wrote:
> Lemme preface this post by saying the following - I've taken my
> computer to the local IT office on RIT campus, asked a Computer
> Science professor specializing in Python, and posted my question on
> answers.yahoo.com (I don't know why I expected that to work...). I've
> also googled my problem multiple times and have not come up with
> anything newer than about 4 years ago.
> 
> Okay, so the problem. I tried to install Python 2.7 about two months
> ago on both my laptop and iMac. Both are running up-to-date Mac OS X
> 10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My
> laptop installed python 2.7 and ran it perfectly, first time. My
> desktop... not so much.
> 
> How to recreate the issue on iMac - try to open IDLE, or in terminal,
> type the following:
> python
> import turtle
> turtle.up()
> 
> This is what's displayed in terminal:
> 
> COMPUTERNAME:~ USER$ python
> Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import turtle
> >>> turtle.up()
> CGColor with 1 components
> Abort trap
> COMPUTERNAME:~ USER$

That's an odd one; I've not seen a crash like that before.  From the 
crash dump, it is clear that the crash is happening inside of Tk, not 
Python, and, judging from the symbol names, it has something to do with 
menu initialization and colors.

Try running the same Turtle test using the Apple-supplied Python 2.6

  /usr/bin/python2.6

The Apple-supplied Tcl/Tk that it uses is known to have a number of 
serious problems and should not be used for serious work but, for me, it 
will bring up the turtle window in Tk without crashing.  If it crashes 
the same way that 2.7.2 does, then that would be pretty solid 
corroboration that the problem is not in Python and more likely an issue 
with Tk.

My first question would be do you have some third-party OS X app or 
extension installed that alters or colors menus?  I know there used to 
be some popular ones out there in the past.  If not, try opening System 
Preferences, select Displays, select Color, and check which display 
profile is selected.  Perhaps try selecting another.  And are you using 
a specific language in System Preferences -> Languages & Text -> 
Language?

If that doesn't help, try running the following commands in a terminal 
window:

  source /Library/Frameworks/Tk.framework/Versions/8.5/tkConfig.sh
  echo $TK_VERSION $TK_PATCH_LEVEL

You should see something like:

  8.5 .11

If not, double check that you really are using the latest ActiveState 
Tcl/Tk 8.5 installer from here:

  http://www.activestate.com/activetcl/downloads

Then try the failing turtle commads again and in the crash report, 
verify that  /Library/Frameworks/Tk.framework/Versions/8.5/ appear as 
framework paths and *not*  
/System/Library/Frameworks/Tk.framework/Versions/8.5/.

Try the following command which may not work if you don't have Xcode 
tools installed:

  otool -L $(python2.7 -c 'import _tkinter; print(_tkinter.__file__)')

The paths reported again should start with  
/Library/Frameworks/Tk.framework and not 
/System/Library/Frameworks/Tk.framework.

If none of that works, you could try installing the other python.org 
2.7.2 installer, the 32-bit-only one, which is linked to the older 
Tcl/Tk 8.4, which uses Carbon interfaces rather than Cocoa, and see what 
happens with it.

In any case, please report back what you find and, if necessary, open an 
issue on the Python bug tracker:
  http://bugs.python.org/

Thanks!

-- 
 Ned Deily,
 n...@acm.org

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


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread Terry Reedy

On 11/10/2011 5:40 PM, CAMERON ALLEY wrote:


Okay, so the problem. I tried to install Python 2.7 about two months
ago on both my laptop and iMac. Both are running up-to-date Mac OS X
10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My
laptop installed python 2.7 and ran it perfectly, first time. My
desktop... not so much.


You issue has nothing to do with IDLE and perhaps all to do with the 
buggy tcl/tk that comes with OSX 10.6. The Python module tkinter is the 
tk interface for Python (hence the name). The turtle module and IDLE 
both use tkinter. Searching all tracker issues (open and closed) for 
'max tcl' turns up (among several others)

http://bugs.python.org/issue10907
http://bugs.python.org/issue10969
http://bugs.python.org/issue12269
The latter 2, especially, might tell you what to do.

--
Terry Jan Reedy

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Chris Angelico
On Fri, Nov 11, 2011 at 10:14 AM, Chris Kaynor  wrote:
> Continuing this OT discussion, would it be a brain transplant, or a
> full body transplant?

It's just a rebinding. You don't move the body, you just bind your
name to a new body. It's perfectly legal to have two names bound to
one body (cf Dr Jekyll and Mr Hyde); if you murder Mr Hyde, you can
still access the body through the other name.

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


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread CAMERON ALLEY
On Nov 10, 6:11 pm, John Gordon  wrote:
> In <3c2688bd-4f87-4eb1-9b40-3cb536a2d...@e3g2000vbs.googlegroups.com> CAMERON 
> ALLEY  writes:
>
> > Okay, so the problem. I tried to install Python 2.7 about two months
> > ago on both my laptop and iMac. Both are running up-to-date Mac OS X
> > 10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My
> > laptop installed python 2.7 and ran it perfectly, first time. My
> > desktop... not so much.
>
> IDLE is a separate program from Python itself, right?  It's a GUI, or an
> IDE, or a shell or something.
>
> (Your session output doesn't seem to involve IDLE at all, so I am
> wondering why you mentioned it.)
>
> By typing "python" on your desktop, are you running plain Python, or
> are you running IDLE?
>
> Did you install Python and IDLE on the desktop machine separately?
> Did both installations succeed?
>
> --
> John Gordon                   A is for Amy, who fell down the stairs
> gor...@panix.com              B is for Basil, assaulted by bears
>                                 -- Edward Gorey, "The Gashlycrumb Tinies"

Thanks for the prompt response - yes, IDLE is a seperate program from
python, however included in the Python 2.7.2 folder when downloaded
from python.org. It's an IDE. I mentioned it, because when I try to
open it, I also get an error report, so I figured it wouldn't be
coincidence.

I'm not typing "python" on my desktop, I'm typing it in terminal with
no change of default directory. It runs plain python THROUGH terminal,
and when I import turtle, and call turtle.up() it should in theory
display an image of whatever I asked turtle to draw (in this case
nothing, but the window should still pop up.)

I installed two things on the desktop - python2.7.2 from python.org
and the respective ActiveTK. Both succeeded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: No matter what I do, IDLE will not work...

2011-11-10 Thread John Gordon
In <3c2688bd-4f87-4eb1-9b40-3cb536a2d...@e3g2000vbs.googlegroups.com> CAMERON 
ALLEY  writes:

> Okay, so the problem. I tried to install Python 2.7 about two months
> ago on both my laptop and iMac. Both are running up-to-date Mac OS X
> 10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My
> laptop installed python 2.7 and ran it perfectly, first time. My
> desktop... not so much.

IDLE is a separate program from Python itself, right?  It's a GUI, or an
IDE, or a shell or something.

(Your session output doesn't seem to involve IDLE at all, so I am
wondering why you mentioned it.)

By typing "python" on your desktop, are you running plain Python, or
are you running IDLE?

Did you install Python and IDLE on the desktop machine separately?
Did both installations succeed?

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Chris Kaynor
On Thu, Nov 10, 2011 at 2:48 PM, Steven D'Aprano
 wrote:
> On Thu, 10 Nov 2011 14:38:58 -0500, Terry Reedy wrote:
>
>> I will point out that in the real world, dead donor transplants are
>> based on the fact the parts of the body do NOT have to die when the
>> composition does. I will not be surprised if we someday see arm
>> transplants.
>
> And Guido's Time Machine strikes again... not only have there been arm
> transplants, but the first DOUBLE arm transplant was three years ago:
>
> http://www.dailymail.co.uk/health/article-1039587/Worlds-double-arm-transplant-man-gets-teenagers-limbs.html
>
>
> There have been successful *face* transplants. Nothing will surprise me
> now until they do a brain or head transplant.
>

Continuing this OT discussion, would it be a brain transplant, or a
full body transplant?

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


Re: all() is slow?

2011-11-10 Thread Steven D'Aprano
On Thu, 10 Nov 2011 15:37:05 -0500, Devin Jeanpierre wrote:

>> '--' not being allowed for a name has *nothing* to do with exec, and
>> everything to do with `--` not being a valid Python identifier.
> 
> The only reason valid python identifiers come into it at all is because
> they get pasted into a string where identifiers would go, and that
> string is passed to exec().

That is patently untrue. If you were implementing namedtuple without 
exec, you would still (or at least you *should*) prevent the user from 
passing invalid identifiers as attribute names. What's the point of 
allowing attribute names you can't actually *use* as attribute names?

You could remove the validation, allowing users to pass invalid field 
names, but that would be a lousy API. If you want field names that aren't 
valid identifiers, the right solution is a dict, not attributes.

Here's a re-implementation using a metaclass:

http://pastebin.com/AkG1gbGC

and a diff from the Python bug tracker removing exec from namedtuple:

http://bugs.python.org/file11608/new_namedtuples.diff


You will notice both of them keep the field name validation.


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


Re: all() is slow?

2011-11-10 Thread Steven D'Aprano
On Thu, 10 Nov 2011 14:19:18 -0700, Ian Kelly wrote:

> On Thu, Nov 10, 2011 at 1:37 PM, Devin Jeanpierre
>  wrote:
>> Of course not. I do, however, think that it's conceivable that I'd want
>> to key a namedtuple by an invalid identifier, and to do that, yes, I'd
>> need to use getattr().
> 
> Care to give a real use case?  

A common use-case is for accessing fields from an external data source, 
using the same field names. For example, you might have a database with a 
field called "class", or a CSV file with columns "0-10", "11-20", etc.

Personally, I wouldn't bother using attributes to access fields, I'd use 
a dict, but some people think it's important to use attribute access.


> You could even go a step further and use,
> say, arbitrary ints as names if you're willing to give up getattr() and
> use "ob.__class__.__dict__[42].__get__(ob, ob.__class__)" everywhere
> instead.  The fact that somebody might conceivably want to do this
> doesn't make it a good idea, though.

Obviously you would write a helper function rather than repeat that mess 
in-line everywhere.


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


Re: all() is slow?

2011-11-10 Thread Ethan Furman

Devin Jeanpierre wrote:

The only reason valid python identifiers come into it at all is
because they get pasted into a string where identifiers would go, and
that string is passed to exec().

So really, does it have "nothing" to do with exec? Or does your
argument eventually boil down to the use of exec?


As I recall the big reason for namedtuples was things like

sys.version_info[1]  # behind door number one is...

being much more readable as

sys.version_info.minor

In other words, the tuple offsets are named -- hence, namedtuples.  And 
only valid identifiers will work.


So, no, it has nothing to do with 'exec', and everything to do with the 
problem namedtuple was designed to solve.


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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Steven D'Aprano
On Thu, 10 Nov 2011 14:38:58 -0500, Terry Reedy wrote:

> I will point out that in the real world, dead donor transplants are
> based on the fact the parts of the body do NOT have to die when the
> composition does. I will not be surprised if we someday see arm
> transplants.

And Guido's Time Machine strikes again... not only have there been arm 
transplants, but the first DOUBLE arm transplant was three years ago:

http://www.dailymail.co.uk/health/article-1039587/Worlds-double-arm-transplant-man-gets-teenagers-limbs.html


There have been successful *face* transplants. Nothing will surprise me 
now until they do a brain or head transplant.



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


No matter what I do, IDLE will not work...

2011-11-10 Thread CAMERON ALLEY
Lemme preface this post by saying the following - I've taken my
computer to the local IT office on RIT campus, asked a Computer
Science professor specializing in Python, and posted my question on
answers.yahoo.com (I don't know why I expected that to work...). I've
also googled my problem multiple times and have not come up with
anything newer than about 4 years ago.

Okay, so the problem. I tried to install Python 2.7 about two months
ago on both my laptop and iMac. Both are running up-to-date Mac OS X
10.6, with 64-bit processors and around 2.4GHz speed and 2G of RAM. My
laptop installed python 2.7 and ran it perfectly, first time. My
desktop... not so much.

How to recreate the issue on iMac - try to open IDLE, or in terminal,
type the following:
python
import turtle
turtle.up()

This is what's displayed in terminal:

COMPUTERNAME:~ USER$ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
>>> turtle.up()
CGColor with 1 components
Abort trap
COMPUTERNAME:~ USER$

It also pops up a Problem Report for Python
Python quit unexpectedly.
Click Reopen to open the application again. This report will be sent
to Apple automatically.
Problem Details and System Configuration

Process: Python [33535]
Path:/Library/Frameworks/Python.framework/Versions/2.7/
Resources/Python.app/Contents/MacOS/Python
Identifier:  org.python.python
Version: 2.7.2 (2.7.2)
Code Type:   X86-64 (Native)
Parent Process:  bash [33532]

Date/Time:   2011-11-10 17:31:58.424 -0500
OS Version:  Mac OS X 10.6.8 (10K549)
Report Version:  6

Interval Since Last Report:  1141508 sec
Crashes Since Last Report:   2
Per-App Interval Since Last Report:  2 sec
Per-App Crashes Since Last Report:   2
Anonymous UUID:  C667A2E4-5530-4A3E-B6E3-
B38E970458E5

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x, 0x
Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Application Specific Information:
abort() called

Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
0   libSystem.B.dylib   0x7fff89bd40b6 __kill + 10
1   libSystem.B.dylib   0x7fff89c749f6 abort + 83
2   Tcl 0x00010067f9ef Tcl_Panic + 0
3   Tcl 0x00010067fa91 Tcl_Panic + 162
4   Tk  0x0001010ac5a7 TkpGetColor +
383
5   Tk  0x0001010b9a2a TkpMenuInit +
156
6   Tk  0x00010103c36c TkMenuInit + 88
7   Tk  0x0001010bc68b -
[TKApplication(TKMenus) _setupMenus] + 53
8   Tk  0x0001010b6d27 -
[TKApplication(TKInit) _setup:] + 56
9   Tk  0x0001010b7260 TkpInit + 545
10  Tk  0x00010102da26 Initialize +
1678
11  _tkinter.so 0x0001005fccfb Tcl_AppInit + 75
12  _tkinter.so 0x0001005fa153 Tkinter_Create +
915
13  org.python.python   0x0001000c102d
PyEval_EvalFrameEx + 22397
14  org.python.python   0x0001000c2d29
PyEval_EvalCodeEx + 2137
15  org.python.python   0x00010003da80 function_call +
176
16  org.python.python   0x0001c5e2 PyObject_Call +
98
17  org.python.python   0x00010001ebcb
instancemethod_call + 363
18  org.python.python   0x0001c5e2 PyObject_Call +
98
19  org.python.python   0x0001000be5f3
PyEval_EvalFrameEx + 11587
20  org.python.python   0x0001000c2d29
PyEval_EvalCodeEx + 2137
21  org.python.python   0x00010003da80 function_call +
176
22  org.python.python   0x0001c5e2 PyObject_Call +
98
23  org.python.python   0x00010001ebcb
instancemethod_call + 363
24  org.python.python   0x0001c5e2 PyObject_Call +
98
25  org.python.python   0x0001000ba5f7
PyEval_CallObjectWithKeywords + 87
26  org.python.python   0x000100021e5e PyInstance_New +
126
27  org.python.python   0x0001c5e2 PyObject_Call +
98
28  org.python.python   0x0001000be5f3
PyEval_EvalFrameEx + 11587
29  org.python.python   0x0001000c2d29
PyEval_EvalCodeEx + 2137
30  org.python.python   0x00010003da80 function_call +
176
31  org.python.python   0x0001c5e2 PyObject_Call +
98
32  org.python.python   0x00010001ebcb
instancemethod_call + 363
33  org.python.python   0x0001c5e2 PyObject_Call +
98
34  org.python.python  

Re: Decorator question: prefer class, but only function works

2011-11-10 Thread Ian Kelly
On Thu, Nov 10, 2011 at 2:52 PM, Russell E. Owen  wrote:
> I am trying to write a decorator that times an instance method and
> writes the results to a class member variable. For example:
>
> def timeMethod(func):
>    def wrapper(self, *args, **keyArgs):
>        t1 = time.time()
>        res = func(self, *args, **keyArgs)
>        duration = time.time() - t1
>        self.timings[func.__name__] = duration
>        return res
>    return wrapper
>
> This works, but I'm not very happy with the way self.timings is obtained.

What do you feel is wrong with it?  You probably should use
sum(os.times()[:2]) instead, which (assuming your script is
single-threaded) will more accurately count the actual CPU time spent
in the function rather than real time, which could be quite different
if the CPU is busy.

Also, why do you need this?  If you're just trying to evaluate the
speed of your code, you should consider using a proper profiler or the
timeit module.  The former will tell you how much time is spent in
each function, while the latter runs the code a large number of times
in a loop, which gives you better precision for quick methods.

> I first tried to write this as a class (for readability), and this did
> NOT work:
>
> class timeMethod(object):
>    def __init__(self, func):
>        self.func = func
>    def __call__(self, *args, **keyArgs):
>        t1 = time.time()
>        res = self.func(*args, **keyArgs)
>        duration = time.time() - t1
>        args[0].timings.set(self.func.__name__, duration)
>        return res
>
> In the first case the wrapper is called as an unbound function, so it
> works. But in the second case the wrapper is called as a bound method --
> thus args[0] is not func's class instance, and I can't get to the
> timings attribute.

I prefer the function version myself, but to make this work you could
add something like this (untested) to make your wrapper class a
descriptor that tacks on the self argument:

def __get__(self, instance, owner):
from functools import partial
if instance is None:
return self
return partial(self, instance)

HTH,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Decorator question: prefer class, but only function works

2011-11-10 Thread Russell E. Owen
I am trying to write a decorator that times an instance method and 
writes the results to a class member variable. For example:

def timeMethod(func):
def wrapper(self, *args, **keyArgs):
t1 = time.time()
res = func(self, *args, **keyArgs)
duration = time.time() - t1
self.timings[func.__name__] = duration
return res
return wrapper

This works, but I'm not very happy with the way self.timings is obtained.


I first tried to write this as a class (for readability), and this did 
NOT work:

class timeMethod(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **keyArgs):
t1 = time.time()
res = self.func(*args, **keyArgs)
duration = time.time() - t1
args[0].timings.set(self.func.__name__, duration)
return res

In the first case the wrapper is called as an unbound function, so it 
works. But in the second case the wrapper is called as a bound method -- 
thus args[0] is not func's class instance, and I can't get to the 
timings attribute.

Unfortunately they are both pretty ugly. Is there a cleaner way to 
access the the instance of which func is a member? I was very 
disappointed it was not available when timeMethod was 
called/instantiated.

-- Russell

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


[ANN] pyKook 0.7.1 - task automation tool for Python, similar to Rake or Ant

2011-11-10 Thread Makoto Kuwata
I have released pyKook
0.7.1.http://pypi.python.org/pypi/Kook/http://www.kuwata-lab.com/kook/http://www.kuwata-lab.com/kook/pykook-users-guide.html
pyKook is a task automation tool for Python, similar to Rake or Ant.
Bugfix in this release--
* Fixed to include 'kook/books/*.py' into .egg file

--regads,makoto kuwata

On Sat, Nov 5, 2011 at 3:06 PM, Makoto Kuwata  wrote:
> Hi,
>
> I have released pyKook 0.7.0.
> http://pypi.python.org/pypi/Kook/
> http://www.kuwata-lab.com/kook/
> http://www.kuwata-lab.com/kook/pykook-users-guide.html
>
> In this release, you can run commands on remote machines using ssh.
> This is very useful to deploy your application.
>
>
> pyKook Overview
> ---
>
> pyKook is a task automation tool for Python, similar to Rake or Ant.
>
> (Kookbook.py):
>
>    kookbook.default = 'build'
>
>    ## task
>    @recipe(None, ['hello'])
>    def build(c):
>        """build all"""
>        pass
>
>    ## file
>    @recipe('hello', ['hello.o'])
>    def file_hello(c):
>        """build 'hello' from 'hello.o'"""
>        system(c%'gcc -o $(product) $(ingred)')
>
>    ## rule
>    @recipe('*.o', ['$(1).c', '$(1).h'])
>    def file_o(c):
>        system(c%'gcc -c $(ingred)')
>
>
> Command-line:
>
>    bash> kk     # or pykook
>    $ gcc -c hello.c
>    ### *** hello.o (recipe=file_o)
>    $ gcc -c hello.c
>    ### ** hello (recipe=file_hello)
>    $ gcc -o hello hello.o
>    ### * build (recipe=build)
>
> See http://www.kuwata-lab.com/kook/pykook-users-guide.html for details.
>
>
> Enhancements in this release
> 
>
> * (EXPERIMENTAL!!) Remote command execution (ssh and sftp) is available.
>  This is very useful to deploy your application into servers.
>
>  Ex (Kookbook.py)::
>
>        from kook.remote import Remote
>        remote = Remote(
>            hosts    = ['www1', 'www2', 'user3@www3:10022'],
>            port     = 22,
>            user     = 'user1',
>            #password = None,      # for login, '~/.ssh/id_rsa' and sudo
>            passphrase = None,     # only for '~/.ssh/id_rsa'
>            sudo_password = 'xxx', # only for sudo command
>        )
>
>        @recipe
>        @remotes(remote)
>        def hostinfo(c):
>            """show hostname"""
>            ssh = c.ssh
>            ssh('hostname')        # run command with ssh
>            ssh('whomai')          # run command with ssh
>            ssh.sudo('whoami')     # run command with sudo
>
>        @recipe
>        @remotes(remote)
>        def exchange(c):
>            """upload and download files"""
>            ssh = c.ssh
>            with ssh.pushd('work/apps'):
>                ssh.get('file.remote')    # download a file
>                ssh.put('file.local')     # upload a file
>                ssh.mget('remote.*')      # download files
>                ssh.mput('local.*')       # upload files
>
>  Notice that you must configure ssh at first and confirm that
>  you can log into servers without typing password::
>
>        bash> ssh user1@www1
>        bash> ssh user1@www2
>        bash> ssh -p 10022 user3@www3
>        bash> kk hostinfo
>        ### * showinfo (recipe=showinfo)
>        [user1@www1]$ hostame
>        www1
>        [user1@www1]$ whoami
>        user1
>        [user1@www1]$ sudo whoami
>        root
>        [user2@www2]$ hostame
>        www2
>        [user2@www2]$ whoami
>        user2
>        [user2@www2]$ sudo whoami
>        root
>        [user3@www3]$ hostame
>        www3
>        [user3@www3]$ whami
>        user3
>        [user3@www3]$ sudo whoami
>        root
>
>  Currently commands are executed sequencially (not in parallel).
>
> * (EXPERIMENTAL!!) Password object supported.
>  Password object asks you to enter password in prompt when necessary.
>
>  Ex (Kookbook.py)::
>
>        from kook.remote import Remote, Password
>        remote = Remote(
>            hosts         = ['user1@www1:22'],
>            #password     = Password('login'),
>            passphrase    = Password('~/.ssh/id_rsa'),
>            sudo_password = Password('sudo command')
>        )
>        #
>        @recipe
>        @remotes(remote)
>        def remote_test(c):
>            ssh = c.ssh
>            ssh.sudo('whoami')
>
>  Output example::
>
>        bash> kk remote_test
>        ### * remote_test (recipe=remote_test)
>        Password for ~/.ssh/id_rsa:
>        Password for sudo command:
>        [user1@www1]$ sudo whoami
>        root
>
>  It is easy to share password object.
>
>  Ex (Kookbook.py)::
>
>        from kook.remote import Remote, Password
>        passwd = Password()
>        remote = Remote(
>            hosts         = ['user1@www1:22'],
>            password      = passwd,
>            passphrase    = passwd,
>            sudo_password = passwd,
>        )
>
>
> Changes in this release
> ---
>
> * Category class is changed to convers all instance methods into 
> staticmethods.
>
>  Ex (Kookbook.py):
>
>        c

Re: all() is slow?

2011-11-10 Thread Ian Kelly
On Thu, Nov 10, 2011 at 1:37 PM, Devin Jeanpierre
 wrote:
> Of course not. I do, however, think that it's conceivable that I'd
> want to key a namedtuple by an invalid identifier, and to do that,
> yes, I'd need to use getattr().

Care to give a real use case?  You could even go a step further and
use, say, arbitrary ints as names if you're willing to give up
getattr() and use "ob.__class__.__dict__[42].__get__(ob,
ob.__class__)" everywhere instead.  The fact that somebody might
conceivably want to do this doesn't make it a good idea, though.

I do find it a bit funny that you're criticizing a somewhat smelly
implementation detail by complaining that it doesn't support an
equally smelly feature.

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Ethan Furman

Benjamin Kaplan wrote:

You're still misunderstanding Python's object model. del does NOT
delete an object. It deletes a name. The only way for an object to be
deleted is for it to be inaccessible (there are no references to it,
or there are no reachable references to it).

foo = object()
bar = foo
foo



bar



del foo
bar



foo


Traceback (most recent call last):
  File "", line 1, in 
foo
NameError: name 'foo' is not defined


There is no way to force the go_to_heaven method to delete the head
unless you can make sure that all other references to the head are
weak references. If you need strictly-enforced relationships, Python
is probably not the right language for the job- you'll be better off
with C++ or Java.


Having said all that, you could do something like:

class BodyPart(object):
_alive = True
def __nonzero__(self):
return self._alive
def die(self):
self._alive = False

class Head(BodyPart):
"will contain things like Brain, Eyes, etc"
size = 5

class Body(BodyPart):
def __init__(self):
self._head = Head()
def go_to_heaven(self):
self._head.die()
self.die()

John_Doe = Body()

if John_Doe:
print "John Doe is alive!"
John_Doe.go_to_heaven()
if John_Doe:
print "uh oh - something wrong"
else:
print "John Doe is no longer with us"
print "and his head is %s" % ('alive' if John_Doe._head else 'dead')
--
http://mail.python.org/mailman/listinfo/python-list


Re: easy_install doesn't install non-package *.py file

2011-11-10 Thread Makoto Kuwata
On Thu, Nov 10, 2011 at 6:08 PM, Jonathan Hartley  wrote:
> Hey. I don't know the details, but your setup.py needs to use either the 
> 'package_data' or the 'data_files' entry in the dict you pass to setup. These 
> can specify files you want included in the sdist which aren't package files.
>
> There are many complications with using them though. One of them in 
> particular (I don't remember which one) installs the files you specify in a 
> different place depending on whether the user is installing the sdist from 
> local files (python setup.py install) or using pip, so be sure to test both 
> ways.

'package_data' is the solution for my trouble.
Thank you very much, Jonathan.

--
regards,
makoto kuwata
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-10 Thread Devin Jeanpierre
> '--' not being allowed for a name has *nothing* to do with exec, and
> everything to do with `--` not being a valid Python identifier.

The only reason valid python identifiers come into it at all is
because they get pasted into a string where identifiers would go, and
that string is passed to exec().

So really, does it have "nothing" to do with exec? Or does your
argument eventually boil down to the use of exec?

> is more readable than

Of course not. I do, however, think that it's conceivable that I'd
want to key a namedtuple by an invalid identifier, and to do that,
yes, I'd need to use getattr().

Devin

On Thu, Nov 10, 2011 at 1:43 PM, Ethan Furman  wrote:
> Devin Jeanpierre wrote:
>>
>> Well. It reads fine in a certain sense, in that I can figure out
>> what's going on (although I have some troubles figuring out why the
>> heck certain things are in the code). The issue is that what's going
>> on is otherworldly: this is not a Python pattern, this is not a normal
>> approach. To me, that means it does not read fine.
>
> Certainly it's a Python pattern -- it's what you do to dynamically generate
> code.
>
>
>> The use of exec also results in (seemingly) arbitrary constraints on
>> the input. Like, why can't "--" be a name? Because exec? Is there some
>> other reason?
>
> '--' not being allowed for a name has *nothing* to do with exec, and
> everything to do with `--` not being a valid Python identifier.
>
>
>> '--' is a valid attribute name on virtually any object that supports
>> attribute setting (e.g. function objects). Of course, you need to use
>> setattr() and getattr(). Is this really the reason, or is it a
>> limitation caused primarily by the usage of exec and the need to
>> prevent code injection? If somebody added this feature later on, would
>> this create a security vulnerability in certain projects that used
>> namedtuple in certain ways?
>
> So you think
>
>    somevar = getattr(my_named_tuple, '--')
>
> is more readable than
>
>    somevar = my_named_tuple.spam
>
> ?
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with databases (ODBC and ORMs) in Python 3.2

2011-11-10 Thread Nathan Rice
For now, get started in Python 2.7.  Write code with an eye to 3.x
portability, and you will be fine.  You probably won't see 3.x
overtake 2.x for at least 3-4 years, and a decent amount of stuff is
still 2.x only.  Since it sounds like you are a windows/net shop, go
ahead and use Iron Python.

SQL Alchemy is your one stop shop.  It is basically 3.x compatible,
but see my previous statement about 3.x.  I haven't used SQL Alchemy
with SQL Server but honestly, SQL Alchemy is THE showcase python
library -- I doubt you will run into any issues.  Just google
"sqlalchemy sql server", I'm sure there's a blog post explaining the
specifics in detail.

Nathan

On Thu, Nov 10, 2011 at 1:56 PM, tkp...@hotmail.com  wrote:
> We are in the process of trying to decide between Python 2.7 and 3.2
> with a view to making a 5-10 year commitment to the right platform,
> and would appreciate some guidance on how best to connect to SQL
> databases in 3.2. ceODBC 2.01 provides an ODBC driver for Python 3.2,
> does anyone have experience using it? Also, are there any ORMs (object
> relational mapper)s that work well with 3,2?
>
> Thanks in advance
>
> Thomas Philips
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-10 Thread OKB (not okblacke)
John Nagle wrote:

> On 11/7/2011 1:00 PM, OKB (not okblacke) wrote:
>>   I noticed this (Python 2.6.5 on Windows XP):
> 
>  CPython is slow. It's a naive interpreter.  There's
> almost no optimization during compilation.  Try PyPy
> or Shed Skin.

PyPy is interesting, but I use various libraries that make use of C 
extension modules.  I'm not going to compile them all myself, which is 
apparently what I would need to do for PyPy.  PyPy or other 
implementations won't work for me unless they're completely drop-in 
replacements for the interpreter.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Terry Reedy

On 11/10/2011 9:31 AM, Jerry Zhang wrote:


Unfortunately there is a difference between composition and
aggregation in my real word, and my application really care this
since it is trying to simulate this real world model, so my system
should track this difference accurately, otherwise the system may
not work well.

For example,
a. the Cls_arm and Cls_body may be composition, but not aggregation.
My app must ensure that " one arm instance only live with one body
instance, if the body instance die, the arm instance must die.


Create the arm as a private member '_arm' of body and make sure that no 
method of body passes out a reference to the arm. (In Python, outside 
code can still grab a reference to the private attribute, but that is a 
coding bug.)


I will point out that in the real world, dead donor transplants are 
based on the fact the parts of the body do NOT have to die when the 
composition does. I will not be surprised if we someday see arm transplants.


--
Terry Jan Reedy

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Benjamin Kaplan
On Thu, Nov 10, 2011 at 1:06 PM, Jerry Zhang  wrote:
>
>
> I just did an example code to describe what i am looking for.
> /**/
> # ...
>
> class Head:
>     def __init__(self):
>     self.size = 5
>
> class Hat:
>     def __init__(self):
>     self.color = red
>     def took_on(self, body):
>     self.body = body
>     def took_off(self, body):
>     del self.body
>
> class Body:
>     def __init__(self):
>     self.head = Head()
>     def take_on_hat(self, hat):
>     self.hat = hat
>     hat.take_on(self)
>     def take_off_hat(self):
>     hat.take_off(self)
>     del self.hat
>     def go_to_heaven(self):
>     take_off_hat(self)
>     del self.head
> /*--*/
>
> In this example, Head and body are COMPOSITION, which means
> a. A head only live with one body, it can not live with other body. It can
> not even live without body
> b. If the body go to die, the head also go to die.
>
> Body and Hat are aggregation, which means
> a. A hat live isolate with body, its life circle is isolate
> b. A hat only live with one body at a specific time, it can not live with
> two body(association would be more than one)
>
> So when the body die, the clean dead should include take_off Hat and del
> Head, otherwise, the code definition is not prciselly describing the
> relationship, which may cause a mess system, for example, a body has dead,
> but one hat is still associated with a unreferenced body.
> A point on this issue, maybe python is smart that the take_off_hat(self) is
> not needed in go_to_heaven() method(i am not sure yet), but the del
> self.head is sure needed, otherwise, we will have a no_body_head in our
> ZODB, that is extremely horrible, right?
>
> All of these points one, the four kinds of class relationship in UML
> precisely describe the real word, if the implementation is not precisely,
> you will have unexpected results.
> Of course, python may be smart to achieve such goal with less effort, that
> is why i am asking for a code example for all of the four relationships.

You're still misunderstanding Python's object model. del does NOT
delete an object. It deletes a name. The only way for an object to be
deleted is for it to be inaccessible (there are no references to it,
or there are no reachable references to it).
>>> foo = object()
>>> bar = foo
>>> foo

>>> bar

>>> del foo
>>> bar

>>> foo

Traceback (most recent call last):
  File "", line 1, in 
foo
NameError: name 'foo' is not defined


There is no way to force the go_to_heaven method to delete the head
unless you can make sure that all other references to the head are
weak references. If you need strictly-enforced relationships, Python
is probably not the right language for the job- you'll be better off
with C++ or Java.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-10 Thread Terry Reedy

On 11/10/2011 3:51 AM, Devin Jeanpierre wrote:


Because Python doesn't allow "--" to be an attribute name, and so
namedtuple doesn't let you try:

t = namedtuple("T", "foo -- bar")(1, 2, 3)
print(t.foo)
print(t.--)
print(t.bar)


'--' is a valid attribute name on virtually any object that supports
attribute setting (e.g. function objects).


ob.-- is not valid Python because '--' is not a name.

> Of course, you need to use setattr() and getattr().

I consider the fact that CPython's setattr accepts non-name strings to 
be a bit of a bug. Or if you will, leniency for speed. (A unicode name 
check in Py3 would be much more expensive than an ascii name check in 
Py2.) I would consider it legitimate for another implementation to only 
accept names and to use a specialized name_dict for attribute dictionaries.


So I consider it quite legitimate for namedtuple to requires real names 
for the fields. The whole point is to allow ob.name access to tuple 
members. Someone who plans to use set/getattr with arbitrary strings 
should just use a dict instead of a tuple.


--
Terry Jan Reedy

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


Re: all() is slow?

2011-11-10 Thread Ethan Furman

Devin Jeanpierre wrote:

Well. It reads fine in a certain sense, in that I can figure out
what's going on (although I have some troubles figuring out why the
heck certain things are in the code). The issue is that what's going
on is otherworldly: this is not a Python pattern, this is not a normal
approach. To me, that means it does not read fine.


Certainly it's a Python pattern -- it's what you do to dynamically 
generate code.




The use of exec also results in (seemingly) arbitrary constraints on
the input. Like, why can't "--" be a name? Because exec? Is there some
other reason?


'--' not being allowed for a name has *nothing* to do with exec, and 
everything to do with `--` not being a valid Python identifier.



> '--' is a valid attribute name on virtually any object that supports
> attribute setting (e.g. function objects). Of course, you need to use
> setattr() and getattr(). Is this really the reason, or is it a
> limitation caused primarily by the usage of exec and the need to
> prevent code injection? If somebody added this feature later on, would
> this create a security vulnerability in certain projects that used
> namedtuple in certain ways?

So you think

somevar = getattr(my_named_tuple, '--')

is more readable than

somevar = my_named_tuple.spam

?

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


Working with databases (ODBC and ORMs) in Python 3.2

2011-11-10 Thread tkp...@hotmail.com
We are in the process of trying to decide between Python 2.7 and 3.2
with a view to making a 5-10 year commitment to the right platform,
and would appreciate some guidance on how best to connect to SQL
databases in 3.2. ceODBC 2.01 provides an ODBC driver for Python 3.2,
does anyone have experience using it? Also, are there any ORMs (object
relational mapper)s that work well with 3,2?

Thanks in advance

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/11 Christian Heimes 

> Am 10.11.2011 17:09, schrieb Tim Wintle:
> >> Meanwhile, I have a ZODB running, which stores all the living
> >> objects.
> >
> > The ZODB is append only and stores all objects. Deleting references to
> > an object (which would causes deletion of standard python objects) won't
> > delete it from the zodb, it'll just delete the references.
>
> That's not entirely correct. In fact you *CAN* delete references to
> objects that are stored in ZODB. An unreferenced object is no longer
> accessible from future transactions. The object is only available from
> the transaction history log and thus still stored in the database file
> until the ZODB is packed. Once the ZODB is packed, all unreferenced
> objects are gone for good.
>
> ZODB is much more than a simple pickle jar. It's a transparent and
> poweful object database that behaves like an ordinary tree of Python
> objects.
>
>
I am verifying the ZODB solution, not clear yet, anyway, your points
regarding this sounds reasonable to me.
i am almost sure the python and ZODB designer has already did a good job to
make us handle such case easily, all i am trying to do is find the right
path.

Thanks a lot.


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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/11 Tim Wintle 

> On Thu, 2011-11-10 at 22:25 +0800, Jerry Zhang wrote:
> >
> >
> > 2011/11/10 Chris Angelico 
> > On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang
> >  wrote:
> > > Cls_a:
> > > def __init__(self):
> > > self.at1 = 1
> > > Cls_b:
> > > def __init__(self):
> > > self.com1 = Cls_a()
> > > def __del__(self):
> > > del self.com1
> > > Is it a right implementation for composition?
> >
> >
> > Yes, except that you don't need to explicitly del it. Python
> > (at
> > least, CPython) is reference-counted; your Cls_b object owns a
> > reference to the Cls_a object, so (assuming nothing else has a
> > reference) that Cls_a will be happily cleaned up when the
> > Cls_b is.
> >
> > Python doesn't really talk about "composition" etc. It's much
> > simpler:
> > everything's an object, and you have references to that
> > object. A
> > named variable is a reference to some object. A member on an
> > object
> > is, too. Whenever an object is expired, all objects that it
> > references
> > lose one reference, and if that was the sole reference, those
> > objects
> > get expired too. It's a change of thinking, perhaps, but not a
> > difficult one in my opinion; and it's so easy to work with
> > when you
> > grok it.
> >
> >
> > Unfortunately there is a difference between composition and
> > aggregation in my real word, and my application really care this since
> > it is trying to simulate this real world model, so my system should
> > track this difference accurately, otherwise the system may not work
> > well.
>
> You might want to look into weak references:
> http://docs.python.org/library/weakref.html
>
> Although I agree with Chris that it sounds like your code might be
> easier with a change of perspective (I've not done much UML, but the way
> you're describing things sounds like a java-ish way of looking at it to
> me)
>
> > For example,
> > a. the Cls_arm and Cls_body may be composition, but not aggregation.
> > My app must ensure that " one arm instance only live with one body
> > instance, if the body instance die, the arm instance must die.
> >  b. the Cls_auto and the Cls_tyre may be aggregation. "One tyre still
> > can live even the auto is dead."
>
> That behaviour isn't really hard-coded as part of the language in
> python, as it's not required for memory management in the same way it
> would be in C++ or langauges without GCs.
>
> As long as no objects other than body objects hold a reference to arm
> objects then the arm object will be deleted.
>
> For The tyre object to be deleted when the auto object is deleted, there
> would have to be no references left to the tyre object. If there aren't
> any references then you can't know if it exists or not anyway, so the
> distinction isn't useful.
>

I just did an example code to describe what i am looking for.
/**/
# ...

class Head:
def __init__(self):
self.size = 5

class Hat:
def __init__(self):
self.color = red
def took_on(self, body):
self.body = body
def took_off(self, body):
del self.body

class Body:
def __init__(self):
self.head = Head()
def take_on_hat(self, hat):
self.hat = hat
hat.take_on(self)
def take_off_hat(self):
hat.take_off(self)
del self.hat
def go_to_heaven(self):
take_off_hat(self)
del self.head
/*--*/

In this example, Head and body are COMPOSITION, which means
a. A head only live with one body, it can not live with other body. It can
not even live without body
b. If the body go to die, the head also go to die.

Body and Hat are aggregation, which means
a. A hat live isolate with body, its life circle is isolate
b. A hat only live with one body at a specific time, it can not live with
two body(association would be more than one)

So when the body die, the clean dead should include take_off Hat and del
Head, otherwise, the code definition is not prciselly describing the
relationship, which may cause a mess system, for example, a body has dead,
but one hat is still associated with a unreferenced body.
A point on this issue, maybe python is smart that the take_off_hat(self) is
not needed in go_to_heaven() method(i am not sure yet), but the del
self.head is sure needed, otherwise, we will have a no_body_head in our
ZODB, that is extremely horrible, right?

All of these points one, the four kinds of class relationship in UML
precisely describe the real word, if the implementation is not precisely,
you will have unexpected results.
Of

Re: simple import hook

2011-11-10 Thread Andrea Crotti

On 11/10/2011 05:02 PM, Eric Snow wrote:


Yeah, I'm working on a reference for imports in Python.  They're just
a little too mysterious relative to the rest of the language.  But
it's not too helpful yet.  In the meantime...

Yes it's quite mysterious, and it's actually not as hard as it looks..
Anyway I'm glad to say that I reached what I basically wanted.

This script actually compiles the code and runs it, reporting the 
imports done in the end.

Any suggestion is still welcome :)

"""
This script is used to analyse the imports which are actually being done
"""
import argparse
import os
import sys

class CollectImports(object):
"""
Loader object
"""

def __init__(self):
self.loaded = set()

def __str__(self):
return str(self.loaded)

def find_module(self, module_name, package=None):
print("requesting %s" % module_name)
self.loaded.add(module_name)


if __name__ == '__main__':
parser = argparse.ArgumentParser(description='analyse the imports 
made')

parser.add_argument('script')
parser.add_argument('arguments', nargs='*')

ns = parser.parse_args()

progname = ns.script
sys.path.insert(0, os.path.dirname(progname))

cl = CollectImports()
# TODO: maybe we can create a with clause also for this thing
sys.meta_path.append(cl)

# TODO: catch the exit signal and present the output
code = compile(open(progname).read(), progname, 'exec')
exec(code)
print("imports done: %s" % str(cl))


That _is_ pretty strange.

After what I recommended above, are you still getting the wierdness?
It could just be a side-effect of your use of the imp functions. in
load_module(), so getting rid of it would help.

What version of Python are you using?  If not 2.7 or 3.2, do you get
the same problem when you run the code under one of those latest
versions?

Even when the number of imports is different, are they always in the
same order?  Highly unlikely, but if you say no then this is extra
fishy.



It was python 2.7 on Arch-linux, but thanks to your suggestions 
everything was actually fixed..

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


Re: Agent-based modeling

2011-11-10 Thread Virgil Stokes

On 10-Nov-2011 16:16, Jerry Zhang wrote:



2011/11/10 Virgil Stokes mailto:v...@it.uu.se>>

Python seems like a good language to use for agent-based modeling.
However, before starting to work on a Python package for this, I would be
very interested in knowing about any existing Python code for agent-based
modeling.


I am assuming you are talking about the pattern design -- agent pattern, right?



--V

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



Sorry Jerry if my email was unclear.

I am referring to agent-based modeling as defined at

http://en.wikipedia.org/wiki/Agent-based_model
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Christian Heimes
Am 10.11.2011 17:09, schrieb Tim Wintle:
>> Meanwhile, I have a ZODB running, which stores all the living
>> objects. 
> 
> The ZODB is append only and stores all objects. Deleting references to
> an object (which would causes deletion of standard python objects) won't
> delete it from the zodb, it'll just delete the references.

That's not entirely correct. In fact you *CAN* delete references to
objects that are stored in ZODB. An unreferenced object is no longer
accessible from future transactions. The object is only available from
the transaction history log and thus still stored in the database file
until the ZODB is packed. Once the ZODB is packed, all unreferenced
objects are gone for good.

ZODB is much more than a simple pickle jar. It's a transparent and
poweful object database that behaves like an ordinary tree of Python
objects.

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Tim Wintle
On Thu, 2011-11-10 at 22:25 +0800, Jerry Zhang wrote:
> 
> 
> 2011/11/10 Chris Angelico 
> On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang
>  wrote:
> > Cls_a:
> > def __init__(self):
> > self.at1 = 1
> > Cls_b:
> > def __init__(self):
> > self.com1 = Cls_a()
> > def __del__(self):
> > del self.com1
> > Is it a right implementation for composition?
> 
> 
> Yes, except that you don't need to explicitly del it. Python
> (at
> least, CPython) is reference-counted; your Cls_b object owns a
> reference to the Cls_a object, so (assuming nothing else has a
> reference) that Cls_a will be happily cleaned up when the
> Cls_b is.
> 
> Python doesn't really talk about "composition" etc. It's much
> simpler:
> everything's an object, and you have references to that
> object. A
> named variable is a reference to some object. A member on an
> object
> is, too. Whenever an object is expired, all objects that it
> references
> lose one reference, and if that was the sole reference, those
> objects
> get expired too. It's a change of thinking, perhaps, but not a
> difficult one in my opinion; and it's so easy to work with
> when you
> grok it.
> 
> 
> Unfortunately there is a difference between composition and
> aggregation in my real word, and my application really care this since
> it is trying to simulate this real world model, so my system should
> track this difference accurately, otherwise the system may not work
> well. 

You might want to look into weak references:
http://docs.python.org/library/weakref.html

Although I agree with Chris that it sounds like your code might be
easier with a change of perspective (I've not done much UML, but the way
you're describing things sounds like a java-ish way of looking at it to
me)

> For example, 
> a. the Cls_arm and Cls_body may be composition, but not aggregation.
> My app must ensure that " one arm instance only live with one body
> instance, if the body instance die, the arm instance must die.
>  b. the Cls_auto and the Cls_tyre may be aggregation. "One tyre still
> can live even the auto is dead."

That behaviour isn't really hard-coded as part of the language in
python, as it's not required for memory management in the same way it
would be in C++ or langauges without GCs.

As long as no objects other than body objects hold a reference to arm
objects then the arm object will be deleted.

For The tyre object to be deleted when the auto object is deleted, there
would have to be no references left to the tyre object. If there aren't
any references then you can't know if it exists or not anyway, so the
distinction isn't useful.

> Meanwhile, I have a ZODB running, which stores all the living
> objects. 

The ZODB is append only and stores all objects. Deleting references to
an object (which would causes deletion of standard python objects) won't
delete it from the zodb, it'll just delete the references.


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


simple import hook

2011-11-10 Thread Andrea Crotti

So I would really like to accomplish the following:
run a program normally and keep track of all the imports that were 
actually done.


I studied the PEP 302, but I'm still a bit confused about how to do it.

I thought that instead of implementing everything I could just record 
the request

and then delegate to the "imp" module, so I did this:

class MyLoader(object):
"""
Loader object
"""

def __init__(self):
self.loaded = set()

def find_module(self, module_name, package=None):
print("requesting %s" % module_name)
self.loaded.add(module_name)
return self

def load_module(self, fullname):
#XXX: the find_module is actually doing nothing, since
# everything is delegated to the "imp" module
fp, pathname, stuff = imp.find_module(fullname)
imp.load_module(fullname, fp, pathname, stuff)

myl = MyLoader()
sys.meta_path.append(myl)
try:
import random
import os
print(random.random())



Which doesn't work, and very strangely it doesn't even look deterministic!
Sometimes it stops at first import sometimes it's able to do a few of them.
How can that be?

And how could I do solve my problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Agent-based modeling

2011-11-10 Thread Jerry Zhang
2011/11/10 Virgil Stokes 

>  Python seems like a good language to use for agent-based modeling.
> However, before starting to work on a Python package for this, I would be
> very interested in knowing about any existing Python code for agent-based
> modeling.
>

I am assuming you are talking about the pattern design -- agent pattern,
right?


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


Agent-based modeling

2011-11-10 Thread Virgil Stokes
Python seems like a good language to use for agent-based modeling. However, 
before starting to work on a Python package for this, I would be very interested 
in knowing about any existing Python code for agent-based modeling.


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


she want a boy friend for dating

2011-11-10 Thread sweet girl
she want a boy friend for dating

http://alturl.com/b5ikf

http://alturl.com/b5ikf

http://alturl.com/b5ikf

http://alturl.com/b5ikf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/10 Jerry Zhang 

>
>
> 2011/11/10 Chris Angelico 
>
>> On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang 
>> wrote:
>> > Cls_a:
>> > def __init__(self):
>> > self.at1 = 1
>> > Cls_b:
>> > def __init__(self):
>> > self.com1 = Cls_a()
>> > def __del__(self):
>> > del self.com1
>> > Is it a right implementation for composition?
>>
>> Yes, except that you don't need to explicitly del it. Python (at
>> least, CPython) is reference-counted; your Cls_b object owns a
>> reference to the Cls_a object, so (assuming nothing else has a
>> reference) that Cls_a will be happily cleaned up when the Cls_b is.
>>
>> Python doesn't really talk about "composition" etc. It's much simpler:
>> everything's an object, and you have references to that object. A
>> named variable is a reference to some object. A member on an object
>> is, too. Whenever an object is expired, all objects that it references
>> lose one reference, and if that was the sole reference, those objects
>> get expired too. It's a change of thinking, perhaps, but not a
>> difficult one in my opinion; and it's so easy to work with when you
>> grok it.
>>
>
> Unfortunately there is a difference between composition and aggregation in
> my real word, and my application really care this since it is trying to
> simulate this real world model, so my system should track this difference 
> accurately,
> otherwise the system may not work well.
>
> For example,
> a. the Cls_arm and Cls_body may be composition, but not aggregation. My
> app must ensure that " one arm instance only live with one body instance,
> if the body instance die, the arm instance must die.
>  b. the Cls_auto and the Cls_tyre may be aggregation. "One tyre still can
> live even the auto is dead."
>
> Meanwhile, I have a ZODB running, which stores all the living objects.
>
So lifecycle should be ensured by class definition. I originally thought
this topic would be talked somewhere since many python OOP designer should
have met this, or am i wrong on some point?


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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
2011/11/10 Chris Angelico 

> On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang 
> wrote:
> > Cls_a:
> > def __init__(self):
> > self.at1 = 1
> > Cls_b:
> > def __init__(self):
> > self.com1 = Cls_a()
> > def __del__(self):
> > del self.com1
> > Is it a right implementation for composition?
>
> Yes, except that you don't need to explicitly del it. Python (at
> least, CPython) is reference-counted; your Cls_b object owns a
> reference to the Cls_a object, so (assuming nothing else has a
> reference) that Cls_a will be happily cleaned up when the Cls_b is.
>
> Python doesn't really talk about "composition" etc. It's much simpler:
> everything's an object, and you have references to that object. A
> named variable is a reference to some object. A member on an object
> is, too. Whenever an object is expired, all objects that it references
> lose one reference, and if that was the sole reference, those objects
> get expired too. It's a change of thinking, perhaps, but not a
> difficult one in my opinion; and it's so easy to work with when you
> grok it.
>

Unfortunately there is a difference between composition and aggregation in
my real word, and my application really care this since it is trying to
simulate this real world model, so my system should track this
difference accurately,
otherwise the system may not work well.

For example,
a. the Cls_arm and Cls_body may be composition, but not aggregation. My app
must ensure that " one arm instance only live with one body instance, if
the body instance die, the arm instance must die.
 b. the Cls_auto and the Cls_tyre may be aggregation. "One tyre still can
live even the auto is dead."

Meanwhile, I have a ZODB running, which stores all the living objects.



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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Chris Angelico
On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang  wrote:
> Cls_a:
>     def __init__(self):
>         self.at1 = 1
> Cls_b:
>     def __init__(self):
>         self.com1 = Cls_a()
>     def __del__(self):
>         del self.com1
> Is it a right implementation for composition?

Yes, except that you don't need to explicitly del it. Python (at
least, CPython) is reference-counted; your Cls_b object owns a
reference to the Cls_a object, so (assuming nothing else has a
reference) that Cls_a will be happily cleaned up when the Cls_b is.

Python doesn't really talk about "composition" etc. It's much simpler:
everything's an object, and you have references to that object. A
named variable is a reference to some object. A member on an object
is, too. Whenever an object is expired, all objects that it references
lose one reference, and if that was the sole reference, those objects
get expired too. It's a change of thinking, perhaps, but not a
difficult one in my opinion; and it's so easy to work with when you
grok it.

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


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
Hi Chris,

Firstly thanks for your quick reply.

1. Your code example gives a point, but i may not reach my question yet,
maybe because i did not make myself understood yet. Here is a more detail
example question.

I have a classes sets described by UML, which could be refered as Cls_A,
Cls_B, CLs_C, Cls_D, Cls_E. There are four relationship between
them--dependency, association, aggregation, composition. What i need to do
is define all of the classes by python, and,of course, the class definition
should describe there relationship correctly.
For example, implement composition relationship between Cls_A and Cls_B,
which may means a instance of Cls_B is created and destroyed by a Cls_A
instance, My code may be like this(not sure since i am not quite familiar
with python yet):

Cls_a:
def __init__(self):
self.at1 = 1

Cls_b:
def __init__(self):
self.com1 = Cls_a()
def __del__(self):
del self.com1
Is it a right implementation for composition?

and i need also do other relationship definition into class, like
dependency, association, aggregation...

Is there any article or code example on the relationships implementation?


Thanks!
Biao


2011/11/10 Chris Angelico 

> On Fri, Nov 11, 2011 at 12:15 AM, Jerry Zhang 
> wrote:
> > For example, in composition model, the container object may be
> responsible
> > for the handling of embedded objects' lifecycle. What is the python
> pattern
> > of such implementation?
>
> Here's an example:
>
> class Test(object):
>  def __init__(self):
>self.lst=[1,2,3]
>self.map={"foo":12,"bar":34}
>
> This is a container that has a list and a dictionary in it. When an
> instance of the container is destroyed, its list and dictionary will
> be destroyed too (assuming nobody's made other references to them).
> You don't need to code anything explicitly for that.
>
> Chris Angelico
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The python implementation of the "relationships between classes".

2011-11-10 Thread Chris Angelico
On Fri, Nov 11, 2011 at 12:15 AM, Jerry Zhang  wrote:
> For example, in composition model, the container object may be responsible
> for the handling of embedded objects' lifecycle. What is the python pattern
> of such implementation?

Here's an example:

class Test(object):
  def __init__(self):
self.lst=[1,2,3]
self.map={"foo":12,"bar":34}

This is a container that has a list and a dictionary in it. When an
instance of the container is destroyed, its list and dictionary will
be destroyed too (assuming nobody's made other references to them).
You don't need to code anything explicitly for that.

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


Re: all() is slow?

2011-11-10 Thread gene heskett
On Thursday, November 10, 2011 08:13:13 AM Devin Jeanpierre did opine:

> > I don't expect you to take my word on it (and why should you, I could
> > be an idiot or a sock-puppet), but you could always try googling for
> > "Raymond Hettinger python" and see what comes up. He is not some
> > fly-by Python coder who snuck some dubious n00b code into the
> > standard library when no-one was looking :)
> 
> Alright, I know *something* about him. I knew he was a core developer,
> and that he was responsible for namedtuple. I also discovered (when I
> looked up his activestate profile) some other stuff he wrote. I don't
> really know anything about him outside of that -- i.e. I have no idea
> what parts of Python he's contributed things to in the past that could
> make me go, "oh, wow, _he_ did that?" and so on. I don't really feel
> like a few minutes research would give me the right feel, it generally
> has to come up organically.
> 
> Anyway, if we step back, for a trustworthy developer who wrote
> something seemingly-crazy, I should be willing to suspend judgement
> until I see the relevant facts about something that the developer
> might have and I don't. But he did give the facts,
> ( http://bugs.python.org/issue3974 again) , and I'm not convinced.
> 
> Things can go terribly wrong when abusing exec e.g.
> http://www.gossamer-threads.com/lists/python/bugs/568206 . That
> shouldn't ever happen with a function such as this. exec opens doors
> that should not be opened without a really good reason, and those
> reasons don't strike me that way.
 
If, in the sense that this python 'exec' essentially duplicates the bash 
version, then I have found it quite useful, it was taught to me several 
years ago by another teacher who was a long time Solaris fan, and if it 
were to go away, I have several bash scripts running here right now that 
would require major re-writes.

> > The mere fact that it was accepted into the standard library should
> > tell you that core Python developers consider it an acceptable
> > technique.

Well, its certainly not a new concept.  All the major 'shell interpreters' 
have it, why not python?

> I've seen core developers rail against the namedtuple source code. In
> fairness, I don't believe exec was the subject of the rant --
> nonetheless its presence isn't evidence of general support, and even
> if it were, my tastes have always differed from that of the core
> developers.
> 
> > That's not to say the technique is uncontroversial. But there are
> > still people who dislike "x if flag else y" and @decorator syntax --
> > controversy, in and of itself, isn't necessarily a reason to avoid
> > certain idioms.
> 
> I think there's somewhat a difference in magnitude of objections
> between using exec as a hacked-together macro system, and using "x if
> flag else y" when if statements would do.
> 
> If the exec trick is reasonable, we should normalize it in the form of
> a real, useful macro system, that can protect us against exec's many
> flaws (code injection, accidental syntax errors, etc.) and tell future
> programmers how to do this safely and in a semi-approvable way.
> 
> > I would agree that the use of exec is a code smell. But that doesn't
> > mean it is wrong or bad, merely that it needs a second look before
> > accepting it. There's a world of difference between "You MUST NOT use
> > exec" and "You SHOULD NOT use exec".
> 
> Do I really need a second look? I see exec, I wonder what it's doing.
> It isn't doing anything that couldn't be done subjectively better with
> e.g. a dict, so I disapprove of the usage of exec.
> 
> > There's nothing inside the template being exec'ed that couldn't be
> > found in non-exec code. So if you're having trouble figuring out
> > parts of the code, the presence of the exec is not the problem.
> 
> There's more overhead going back and forth to the template, and
> there's related things that I can't be sure are because of exec or
> because of design decisions, etc.  It makes code reading more
> challenging, even if it's still possible. That said, sure, some of
> these are problems with whatever else he's done.
> 
> > Having said that, dynamic code generation is well known for often
> > being harder to read than "ordinary" code. But then, pointers are
> > hard too.
> 
> And on the other other hand, Python lacks explicit support for both
> pointers and code generation (unless you count strings and ctypes).
> 
> > Because Python doesn't allow "--" to be an attribute name, and so
> > namedtuple doesn't let you try:
> > 
> > t = namedtuple("T", "foo -- bar")(1, 2, 3)
> > print(t.foo)
> > print(t.--)
> > print(t.bar)
> 
> '--' is a valid attribute name on virtually any object that supports
> attribute setting (e.g. function objects). Of course, you need to use
> setattr() and getattr(). Is this really the reason, or is it a
> limitation caused primarily by the usage of exec and the need to
> prevent code injection? If somebody added this feature later on

The python implementation of the "relationships between classes".

2011-11-10 Thread Jerry Zhang
Greetings:

As you know, there are several kinds of relationships between classes in
the UML -- dependency, association, aggregation, composition.
Q1. Is there any article or code example on its implementation in python?
Q2. For example, in composition model, the container object may be
responsible for the handling of embedded objects' lifecycle. What is the
python pattern of such implementation?
would it be adding __del__ to the container class to del embedded objects
or something else?

Thanks!
Biao
-- 
http://mail.python.org/mailman/listinfo/python-list


How to derive from datetime.timezone class?

2011-11-10 Thread Baptiste Lepilleur
Hi,
I want to sub-class the datetime.timezone class, but when I derive from
datetime.timezone I get an error message "TypeError: type
'datetime.timezone' is not an acceptable base type".

Why do I get this error? Is there something specific to do to avoid it?

Below is an example of code:

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.timezone

>>> class Utc(datetime.timezone):
... pass
...
Traceback (most recent call last):
  File "", line 1, in 
TypeError: type 'datetime.timezone' is not an acceptable base type

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


dao 0.7.4 released

2011-11-10 Thread Simeon Chaos

What's new in dao 0.7.4?


*Release date:  2011-11-10

* new in code:
  * quasiquote, unquote, unquote_slicing is implemented.
  * directly evaluate sexpression in solver
  * some builtins for define, set and get global, outer and local var
  * lisp style macro: expand and eval on UserMacro
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: easy_install doesn't install non-package *.py file

2011-11-10 Thread Jonathan Hartley
Hey. I don't know the details, but your setup.py needs to use either the 
'package_data' or the 'data_files' entry in the dict you pass to setup. These 
can specify files you want included in the sdist which aren't package files.

There are many complications with using them though. One of them in particular 
(I don't remember which one) installs the files you specify in a different 
place depending on whether the user is installing the sdist from local files 
(python setup.py install) or using pip, so be sure to test both ways. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: all() is slow?

2011-11-10 Thread Devin Jeanpierre
> I don't expect you to take my word on it (and why should you, I could be
> an idiot or a sock-puppet), but you could always try googling for
> "Raymond Hettinger python" and see what comes up. He is not some fly-by
> Python coder who snuck some dubious n00b code into the standard library
> when no-one was looking :)

Alright, I know *something* about him. I knew he was a core developer,
and that he was responsible for namedtuple. I also discovered (when I
looked up his activestate profile) some other stuff he wrote. I don't
really know anything about him outside of that -- i.e. I have no idea
what parts of Python he's contributed things to in the past that could
make me go, "oh, wow, _he_ did that?" and so on. I don't really feel
like a few minutes research would give me the right feel, it generally
has to come up organically.

Anyway, if we step back, for a trustworthy developer who wrote
something seemingly-crazy, I should be willing to suspend judgement
until I see the relevant facts about something that the developer
might have and I don't. But he did give the facts,
( http://bugs.python.org/issue3974 again) , and I'm not convinced.

Things can go terribly wrong when abusing exec e.g.
http://www.gossamer-threads.com/lists/python/bugs/568206 . That
shouldn't ever happen with a function such as this. exec opens doors
that should not be opened without a really good reason, and those
reasons don't strike me that way.

> The mere fact that it was accepted into the standard library should tell
> you that core Python developers consider it an acceptable technique.

I've seen core developers rail against the namedtuple source code. In
fairness, I don't believe exec was the subject of the rant --
nonetheless its presence isn't evidence of general support, and even
if it were, my tastes have always differed from that of the core
developers.

> That's not to say the technique is uncontroversial. But there are still
> people who dislike "x if flag else y" and @decorator syntax --
> controversy, in and of itself, isn't necessarily a reason to avoid
> certain idioms.

I think there's somewhat a difference in magnitude of objections
between using exec as a hacked-together macro system, and using "x if
flag else y" when if statements would do.

If the exec trick is reasonable, we should normalize it in the form of
a real, useful macro system, that can protect us against exec's many
flaws (code injection, accidental syntax errors, etc.) and tell future
programmers how to do this safely and in a semi-approvable way.

> I would agree that the use of exec is a code smell. But that doesn't mean
> it is wrong or bad, merely that it needs a second look before accepting
> it. There's a world of difference between "You MUST NOT use exec" and
> "You SHOULD NOT use exec".

Do I really need a second look? I see exec, I wonder what it's doing.
It isn't doing anything that couldn't be done subjectively better with
e.g. a dict, so I disapprove of the usage of exec.

> There's nothing inside the template being exec'ed that couldn't be found
> in non-exec code. So if you're having trouble figuring out parts of the
> code, the presence of the exec is not the problem.

There's more overhead going back and forth to the template, and
there's related things that I can't be sure are because of exec or
because of design decisions, etc.  It makes code reading more
challenging, even if it's still possible. That said, sure, some of
these are problems with whatever else he's done.

> Having said that, dynamic code generation is well known for often being
> harder to read than "ordinary" code. But then, pointers are hard too.

And on the other other hand, Python lacks explicit support for both
pointers and code generation (unless you count strings and ctypes).

> Because Python doesn't allow "--" to be an attribute name, and so
> namedtuple doesn't let you try:
>
> t = namedtuple("T", "foo -- bar")(1, 2, 3)
> print(t.foo)
> print(t.--)
> print(t.bar)

'--' is a valid attribute name on virtually any object that supports
attribute setting (e.g. function objects). Of course, you need to use
setattr() and getattr(). Is this really the reason, or is it a
limitation caused primarily by the usage of exec and the need to
prevent code injection? If somebody added this feature later on, would
this create a security vulnerability in certain projects that used
namedtuple in certain ways?

Devin

On Thu, Nov 10, 2011 at 2:48 AM, Steven D'Aprano
 wrote:
> On Wed, 09 Nov 2011 20:26:56 -0500, Devin Jeanpierre wrote:
>
>>> Neither am I. I am less suspicious based on a reputation. Raymond is a
>>> well-known, trusted senior Python developer who knows what he is doing.
>>
>> I don't really know anything about him or why people respect him, so I
>> have no reason to share your faith.
>
> That's fine.
>
> I don't expect you to take my word on it (and why should you, I could be
> an idiot or a sock-puppet), but you could always try googling for
> "Raymond Hettinger