Re: Question About Logic In Python

2005-09-22 Thread Ron Adam
Terry Hancock wrote:
> On Thursday 22 September 2005 12:26 pm, Ron Adam wrote:
> 
>>Steve Holden wrote:
>>
>>>Ron Adam wrote:
>>>
>>>> >>> True * True
>>>>1   # Why not return True here as well?
>>>>
>>>
>>>Why not return 42? Why not return a picture of a banana?
>>
>>My question still stands.  Could it be helpful if bools were preserved 
>>in more cases than they are now?
> 
> 
> No.  "*" is "multiplication".
> The multiplication operator is undefined for boolean values. It only
> makes sense if they are interpreted as numbers. As it happens, both
> can be coerced to 1, so the result is 1*1. This makes perfect sense
> to me.

I'm not implying it doesn't make sense.  It does to me as well.  And it 
would only make sense to return bools in this case if Python supported 
boolean math.

If it did, coercion to ints (or floats) would still occur with mixed 
types are used in expressions, but there are some situations where the 
bool-bool results differ, so it's most likely an all or nothing move.

Both views are valid and there are benefits to both as well.


>>>>True and True
> 
> True
> 
> Also makes sense (and this is indeed what happens).

Only because True is the last value here. ;-)



> Cheers,
> Terry


Cheers,
Ron













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


Re: Anyone else getting posts back as email undeliverable bounces?

2005-09-22 Thread Ron Adam
Bengt Richter wrote:

> It seems lately all my posts have been coming back to me as bounced emails,
> and I haven't emailed them ;-(
> 
> I've been getting  bounce messages like (excerpt):
> ...

Yes, I get them too.  Plugging http://deimos.liage.net/ into a browser get:

 This domain is parked,  underconstruction.

Not sure if it means anything?


Doing a whois on liage.net points to:


Registrant:
Ticluse Teknologi

Registered through: GoDaddy.com
Domain Name: LIAGE.NET

Domain servers in listed order:
   NS1.GOVDEV.COM
   NS2.GOVDEV.COM

For complete domain details go to:
http://whois.godaddy.com


You can find out more by following the godaddy link or just go here and 
enter the numbers displayed to access it.

https://www.godaddy.com/gdshop/whois.asp?se=%2B&domain=LIAGE%2Enet&ci=1718


Maybe an email to them would clear it up?

Cheers,
Ron



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


Re: What is "self"?

2005-09-22 Thread Ron Adam
Wayne Sutton wrote:
> OK, I'm a newbie...
> I'm trying to learn Python & have had fun with it so far.  But I'm having 
> trouble following the many code examples with the object "self."  Can 
> someone explain this usage in plain english?
> 
> Thanks,
> Wayne 


I'll give it a try..

When you have a class definition:

 class Person(object):
 def set_name(self, name):
 self.name = name

The method "set_name", has no idea what your class instance is going to 
called at this point.  But it will need to know when it's called.  So 
for now "self" is just a argument waiting to be assigned a reference 
later just like any other function argument. You can actually call it 
anything you want but "self" is sort of a tradition.

 leader = Person()

This creates an instance of your class and stores a reference to it in 
the name "leader".  Now that that you have an instance with a name.  You 
can use your class method to do something.

 leader.set_name("John")

When you call a method of an instance, Python translates it to...

 leader.set_name(leader, "John")

So "self" in your method definition gets assigned a reference to 
"leader".  "self" can then be used to access the other values and 
methods stored in your class instance.  Or in this case store a value in 
your class instance.  Basically "self" becomes a reference to the class 
instance it is in.

 self.name = name

is the same as ...

 leader.name = name

But we didn't know it was going to be called "leader" when we wrote the 
class.  So self is a convienent place holder.


I hope this helped.

Cheers,
Ron









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


Re: Anyone else getting posts back as email undeliverable bounces?

2005-09-22 Thread Ron Adam
Terry Reedy wrote:

> "Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>It seems lately all my posts have been coming back to me as bounced 
>>emails,
>>and I haven't emailed them ;-(
> 
> 
> They are gatewayed to the general python email list.  But bouncing list 
> emails back to authors instead of the listserve is truly awful.
> 
> 
>>I've been getting  bounce messages like (excerpt):
>>...
>>This is the Postfix program at host deimos.liage.net.
> 
> 
> LOL.  since I never sent email to that address (or similar, not sure), I 
> assumed that these were viral messages disguised as fake bounces (which I 
> once got daily) or at best spam and deleted without reading further.
> 
> If they are list-bounces, the list moderators should also get a bounce and 
> unsubscribe whoever.  I'll see what happens to this.
> 
> Terry J. Reedy

It looks to me like a server was forwarding them to another network, 
possibly an internal one, and that address was disconected or expired, 
but the forwarding address wasn't removed.

---
<[EMAIL PROTECTED]>: Host or domain name not found. Name service error for
 name=lindensys.net type=A: Host not found
---


The admin on LIAGE.NET is/was probably the owner of both given the name 
of the not found host and the LIAGE.NET adminstrator.


---
Registered through: GoDaddy.com (http://www.godaddy.com)
Domain Name: LIAGE.NET
Created on: 18-Mar-05
Expires on: 18-Mar-06
Last Updated on: 20-Jun-05

Administrative Contact:
Linden, James [EMAIL PROTECTED]   <---  lindensys.net not found
---

The web site at tictek give the same exact under construction notice as 
LIAGE.NET.


Cheers,
Ron


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


Re: What is "self"?

2005-09-23 Thread Ron Adam
Erik Max Francis wrote:
> Ron Adam wrote:
> 
>> When you call a method of an instance, Python translates it to...
>>
>>  leader.set_name(leader, "John")
> 
> 
> It actually translates it to
> 
> Person.set_name(leader, "John")
> 

I thought that I might have missed something there.

Is there a paper on how python accesses and stores instance data and 
methods?  I googled but couldn't find anything that addressed this 
particular question.

 >>> class a(object):
...def x(self):
...   print 'x'
...
 >>> b = a()
 >>> b
<__main__.a object at 0x009D1890>
 >>> b.x
>

So what exactly is a bound method object?  Does it possibly translates 
to something like the following?

 def x(*args, **kwds):
 self = ?
 return __class__.self(self, *args, **kwds)

Cheers,
Ron





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


Re: Finding where to store application data portably

2005-09-23 Thread Ron Adam
Steven D'Aprano wrote:

> On Thu, 22 Sep 2005 19:09:28 +0400, en.karpachov wrote:
> 
> 
>>There is an other way around: look at your home dir as if it is your
>>"settings" dir and don't clutter it with files other than application
>>config dot-files.  Just make ~/files/, ~/bin/ ~/lib/ etc. for it.
> 
> 
> Do you put everything into /etc (/etc/bin, /etc/var, /etc/usr, /etc/mnt,
> and so forth)? If your home directory is for settings, why would you store
> files and binaries inside your settings directory?
> 
> I understand the historical reasons for why ~/ is treated as a
> structureless grab-bag of everything and anything. That made sense back in
> the distant past when users used dumb terminals and they had perhaps half
> a dozen dot files. But at the point your home directory has three times as
> many dot files as regular files, the time has come to stop doing things
> just because that's the way they have always been done.

Yes, it's all pretty much historical isn't it.  Someones needs to start 
form scratch I think as far as file storage systems go.

Personally I'd love a cross platform intelligent file storage device 
that managed security and user accounts independent of the operating 
system. (With it's own internal CPU and firmware.)

A few thoughts ...

It should be built on concepts of 'Responsibility', 'Authority', and 
'Delegation',  So you could call it.. RADOS or RAD for short, or just 
use my initials. RA.. (just kidding) ;-)

Also note that an application is just another user by proxy.  And it all 
comes down to private and shared user data. In other words, organize all 
files by who's "Responsible" for them.

You would "Delegate Authority" by using file links with private keys in 
them. Giving a file link to someone else wouldn't work since it would 
need to be ran from your user account to be valid.  These file links is 
how you would access other files in other users file space.

Anyway... such a system would mean that when an application accesses the 
Internet, (has Authority), to update it's own files, (Responsibility), 
it does so in it's own user space and can't access any other users (or 
applications) files.  Virus's would find this very limiting.

Every user account would be a complete unit which can be backed up and 
restored independently of the OS.  If something went wrong you could 
always find out which user (or application developer) was responsible.

Anyway... just wishful thinking.  I'm sure there are a lot of problems 
that would need to be worked out.  ;-)

Cheers,
Ron Adam


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


Re: Dynamically adding and removing methods

2005-09-25 Thread Ron Adam
Steven D'Aprano wrote:


> Or you could put the method in the class and have all instances recognise
> it:
> 
> py> C.eggs = new.instancemethod(eggs, None, C)
> py> C().eggs(3)
> eggs * 3

Why not just add it to the class directly?  You just have to be sure 
it's a class and not an instance of a class.


 >>> def beacon(self, x):
...print "beacon + %s" % x
...
 >>> C.beacon = beacon
 >>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
 >>> A.beacon(3)
beacon + 3
 >>> del beacon
 >>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
 >>> A.beacon(3)
beacon + 3
 >>> dir(C)
['__doc__', '__module__', 'beacon', 'ham', 'spam']


Cheers,
Ron



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


Re: What is "self"?

2005-09-25 Thread Ron Adam
Michael Spencer wrote:

> All is explained at:
> http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods
> and further at:
> http://www.python.org/pycon/2005/papers/36/pyc05_bla_dp.pdf
> 
> "For objects, the machinery is in object.__getattribute__ which 
> transforms b.x into type(b).__dict__['x'].__get__(b, type(b))."
> 
> What follows is my interpretation - hope it's correct:
> 
> # what exactly is a bound method object?
> # Illustrate b.f => type(b).__dict__['x'].__get__(b, type(b))
> 
>  >>> class B(object):
>  ... def f(self, x):
>  ... return x or 42
>  ...
>  >>> b = B()
>  >>> type(b).__dict__['f']
># a plain old function
>  >>> _.__get__(b, type(b))   # invoke the descriptor protocol
>  # to make a bound method
>  >
>  >>>

This still seems not quite right to me...  Or more likely seems to be 
missing something still.

(But it could be this migraine I've had the last couple of days 
preventing me from being able to concentrate on things with more than a 
few levels of complexity.)

Playing around with the shell a bit gives the impression that calling a 
method in a instance gives the following (approximate) result...

 try:
 leader.__dict__["set_name"]("John")
 except:
 type(leader).__dict__["set_name"].__get__(leader, "John")
 # which results in...
 #Person.set_name(leader, "John")
 except:
 raise( AttributeError,
"%s object has no attribute %s" \
  % (leader, "set_name") )


Of course this wouldn't use the object names directly... I guess I'll 
need to look in the C object code to see exactly how it works.  But the 
links you gave help.

Thanks,
Ron











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


Re: What is "self"?

2005-09-27 Thread Ron Adam
Diez B. Roggisch wrote:
>> This still seems not quite right to me...  Or more likely seems to be 
>> missing something still.
>>
>> (But it could be this migraine I've had the last couple of days 
>> preventing me from being able to concentrate on things with more than 
>> a few levels of complexity.)
>>
>> Playing around with the shell a bit gives the impression that calling 
>> a method in a instance gives the following (approximate) result...
>>
>> try:
>> leader.__dict__["set_name"]("John")
>> except:
>> type(leader).__dict__["set_name"].__get__(leader, "John")
>> # which results in...
>> #Person.set_name(leader, "John")
>> except:
>> raise( AttributeError,
>>"%s object has no attribute %s" \
>>  % (leader, "set_name") )
>>
>>
>> Of course this wouldn't use the object names directly... I guess I'll 
>> need to look in the C object code to see exactly how it works.  But 
>> the links you gave help.
> 
> 
> I guess you mean to indent the whole part after the first except and put 
> a try beforehand?

Yes,  I did.  I'm not sure why I left out the try.

  try:
  leader.__dict__["set_name"]("John")
  except:
  try:
  type(leader).__dict__["set_name"].__get__(leader, "John")
  # which results in...
  #Person.set_name(leader, "John")
  except:
  raise( AttributeError,
 "%s object has no attribute %s" \
   % (leader, "set_name") )

> Apart from that you seem to be right - there can very well be values in 
> the class dict that don't follow the descriptor-protocol. However my 
> playing around with this stuff indicates that the creation of bound 
> methods relies on the method being wrapped in a descriptor - otherwise, 
> you get the notorious TypeError
 >
> set_name() takes exactly 1 argument (0 given)
> 
> as the binding doesn't occur.
> 
> Regards,
> 
> Diez

What I've noticed is you can block the visibility of a class attribute, 
which include methods, by inserting an object in the instance with the 
same name.

Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> class a(object):
...   def b(self, value):
...  print value
...
 >>> aa = a()
 >>> def foo(value):
...print "%r" % value
...
 >>> aa.b('hello')
hello
 >>> aa.b = foo
 >>> aa.b('hello')
'hello'
 >>> del aa.b
 >>> aa.b('hi there')
hi there
 >>>

So the underlying mechanism for calling methods doesn't kick in until 
*after* an attempt to get an attribute of the same name in the instance.

 >>> a.boo = boo
 >>> def boo(self, value):
...print list(value)
...
 >>> a.boo = boo
 >>> aa.boo('hello')
['h', 'e', 'l', 'l', 'o']

The attribute aa.boo is not there, so call boo.__get__() in class a.


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


Re: Dynamically adding and removing methods

2005-09-27 Thread Ron Adam
Steven D'Aprano wrote:
> On Sun, 25 Sep 2005 14:52:56 +0000, Ron Adam wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>
>>
>>>Or you could put the method in the class and have all instances recognise
>>>it:
>>>
>>>py> C.eggs = new.instancemethod(eggs, None, C)
>>>py> C().eggs(3)
>>>eggs * 3
>>
>>Why not just add it to the class directly?  You just have to be sure 
>>it's a class and not an instance of a class.
> 
> 
> Because I started off explicitly adding functions to instances directly,
> and when I discovered that didn't work properly, I never even tried adding
> it to the class until after I discovered that instancemethod() worked.
> 
> As far as I can see, Python's treatment of functions when you dynamically
> add them to classes and instances is rather confused. See, for example:
> 
> py> class Klass:
> ... pass
> ...
> py> def eggs(self, x):
> ... print "eggs * %s" % x
> ...
> py> inst = Klass()  # Create a class instance.
> py> inst.eggs = eggs  # Dynamically add a function/method.
> py> inst.eggs(1)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: eggs() takes exactly 2 arguments (1 given)
> 
> From this, I can conclude that when you assign the function to the
> instance attribute, it gets modified to take two arguments instead of one.
> Test it by explicitly passing an instance:
> 
> py> inst.eggs(inst, 1)
> eggs * 1
> 
> My hypothesis is confirmed.

You defined it to take two arguements.. (self, x).  If it's found 
directly in the object instead of indirectly in the objects parent 
objects, it calls it just as you defined it.


>> >>> def beacon(self, x):
>>...print "beacon + %s" % x
>>...
> 
> 
> Did you mean bacon? *wink*

Of course... remembering arbitrary word letter sequences is probably my 
worst skill. ;-)  That, and I think for some reason the name Francis 
Beacon was in my mind at the time.

>> >>> C.beacon = beacon
>> >>> dir(A)
>>['__doc__', '__module__', 'beacon', 'ham', 'spam']
> 
> 
> Okay, you aren't showing all your code. What is A?

'A' is an instace of 'C' which has 'ham' and 'spam' methods in it.

Define a funciton and add it directly to class 'C'.

 >>> def beacon(self, x):
...print "beacon + %s" % x
...
 >>> C.beacon = beacon


Show that it shows up in instance 'A' and can be used.

 >>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
 >>> A.beacon(3)
beacon + 3


Delete the function.  And show it's usable as a method from instance 'A'.

 >>> del beacon
 >>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
 >>> A.beacon(3)
beacon + 3

Show it's still bound to class 'C' even thought the function was deleted.

 >>> dir(C)
['__doc__', '__module__', 'beacon', 'ham', 'spam']


Cheers,
Ron




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


Re: PEP 350: Codetags

2005-09-28 Thread Ron Adam
Micah Elliott wrote:
> Please read/comment/vote.  This circulated as a pre-PEP proposal
> submitted to c.l.py on August 10, but has changed quite a bit since
> then.  I'm reposting this since it is now "Open (under consideration)"
> at .
> 
> Thanks!

How about an approach similar to mark up language using block comments? 
   It would require adding syntax to Python, but might be worth it.

 # Current comments would stay the same.
 #
 # These won't change.
 # Even if they are on a line by them selves or
 # in a sequence of lines.


Possible multi-line comment with optional label.

 ##[label]: comment text :##


Examples:

 ##: an in line comment with no label :##

 ##:
 A multi-line
 comment with no label.

 ##:
 The ##: and :## make it possible.
 to nest comments.

 Nesting makes it easier to comment out
 sections of code without the side effects
 that occur when using triple quotes.
 :##
 :##


 ## TODO:
 A comment with a label.

 I need to do something here.
 JANE, 9/28/05
 :##


 ## FIX ME:
 Nested comments with labels.

 ## JOE:
 I noticed if this gets stuck in a loop here.
 ## date: 9/25/05 :## :##
 ## JOHN:
 I fixed it.
 ## date: 9/28/05 :## :##
 :##


 ## INFO:
 #
 #  Existing comments
 #  wrapped in a labeled
 #  block comment.
 #
 :##


The markup form might make it easy to read labeled comments into a 
dictionary where the labels become the keys.  Then special "" 
definitions wouldn't be needed.

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


Re: Dynamically adding and removing methods

2005-09-28 Thread Ron Adam
Steven D'Aprano wrote:

> On Tue, 27 Sep 2005 16:42:21 +0000, Ron Adam wrote:
> 
> 
>>>>>>>def beacon(self, x):
>>>>
>>>>...print "beacon + %s" % x
>>>>...
>>>
>>>
>>>Did you mean bacon? *wink*
>>
>>Of course... remembering arbitrary word letter sequences is probably my 
>>worst skill. ;-)  That, and I think for some reason the name Francis 
>>Beacon was in my mind at the time.
> 
> 
> I think you mean Francis Bacon *wink*

Yes, I mean him, Beacon is his fathers sirname. I'm not sure if Francis 
changed it or if his father did. (?)


> This clearly shows that assigning a function to a class attribute invokes
> whatever machinery Python uses to turn that function into a true method,
> but assigning it to an instance does not.

Actually I think I'm getting more confused.  At some point the function 
is wrapped.  Is it when it's assigned, referenced, or called?

Cheers,
Ron






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


Re: Dynamically adding and removing methods

2005-09-29 Thread Ron Adam
Terry Reedy wrote:

> "Ron Adam" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>Actually I think I'm getting more confused.  At some point the function
>>is wrapped.  Is it when it's assigned, referenced, or called?
> 
> 
> When it is referenced via the class.

Ok, that's what I suspected.  Thanks for clarifying this.

>  If you lookup in class.__dict__, the function is still a function.

Now why did I not think of doing that?  :-)


>>>>class C(object):
> 
> ...   def meth(self): pass
> ...
> 
>>>>C.__dict__['meth']
> 
> 
> 
>>>>C.meth
> 
> 
> 
>>>>C().meth
> 
> >

Ok, I got it now.  Given class 'C' below, i.m(1)  does

 >>> class C(object):
...def m(self, x):
...   return repr(x)
...
 >>> i = C()
 >>> boundmeth = i.__getattribute__('m')
 >>> boundmeth
>
 >>> boundmeth(1)
'1'

 >>> import dis
 >>> dis.dis(boundmeth)
   3   0 LOAD_GLOBAL  0 (repr)
   3 LOAD_FAST1 (x)
   6 CALL_FUNCTION1
   9 RETURN_VALUE
 >>> dis.dis(C.m)
   3   0 LOAD_GLOBAL  0 (repr)
   3 LOAD_FAST1 (x)
   6 CALL_FUNCTION1
   9 RETURN_VALUE
 >>> dis.dis(C.__dict__['m'])
   3   0 LOAD_GLOBAL  0 (repr)
   3 LOAD_FAST1 (x)
   6 CALL_FUNCTION1
   9 RETURN_VALUE

Hmm... that didn't tell me anything. (?)

 >>> boundmeth
>
 >>> C.m

 >>> C.__dict__['m']


Time to start digging around in the source code I guess.  ;-)

> I am not sure, without looking, how much of this is language definition and 
> how much CPython implementation, but I think mostly the latter, as long as 
> the inheritance tree lookup behavior is as specified.
> 
> Terry J. Reedy

Yes, it hard to tell sometimes where CPython ends and Python begins.

Cheers,
Ron

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


Re: [Info] PEP 308 accepted - new conditional expressions

2005-09-30 Thread Ron Adam
Reinhold Birkenfeld wrote:

> Rocco Moretti wrote:
> 
>>Reinhold Birkenfeld wrote:
>>
>>>Hi,
>>>
>>>after Guido's pronouncement yesterday, in one of the next versions of Python
>>>there will be a conditional expression with the following syntax:
>>>
>>>X if C else Y
>>
>>Any word on chaining?
>>
>>That is, what would happen with the following constructs:
>>
>>A if B else C if D else F
>>A if B if C else D else F
>>
>>The first one is the tricky bit - it could be either
>>
>>(A if B else C) if D else F
>>or
>>A if B else (C if D else F)
>>
>>I'd expect the former from left-> right semantics, but reading the 
>>unparenthesized form, I'd see "A if B else ..." note that B is true, and 
>>conclude the expression evaluated to A (which would be wrong if D is false).
> 
> 
> It will be
> 
> A if B else (C if D else F)

So this evaluates as if there are parentheses around each section.. Hmm?

   (A) if (B) else ( (C) if (D) else (F) )

The first 'if' divided the expr, then each succeeding 'if' divides the 
sub expressions, etc...  ?

So ...

   A if B else C + X * Y

Would evaluate as... ?

   A if B else (C + X * Y)


and...

value = X * Y + A if B else C

would be ?

value = (X * Y + A) if B else C

or ?

value = X * Y + (A if B else C)



I think I'm going to make it a habit to put parentheses around these 
things just as if they were required.

Cheers,
Ron


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


Re: [Info] PEP 308 accepted - new conditional expressions

2005-10-01 Thread Ron Adam
Reinhold Birkenfeld wrote:

> Ron Adam

>>I think I'm going to make it a habit to put parentheses around these 
>>things just as if they were required.


> Yes, that's the best way to make it readable and understandable.
> 
> Reinhold

Now that the syntax is settled, I wonder if further discussion on the 
contextual behavior could be done?  Or maybe it was already done off 
line or in private email?

To me the advantage of a if b else c form is the easy chaining to build 
up a sum of conditional parts, where each next part is dependent on the 
previous result.

The advantage of the nested form, is it can be used in place of an 
if-elif-else structure.  But I think the (a if b else c) syntax doesn't 
match that behavior very well so I was expecting the default behavior to 
be the sequential chaining and not nested evaluation.

But of course, by explicitly placing parentheses, you can do either. 


Cheers,
Ron








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


Re: Class Help

2005-10-01 Thread Ron Adam
Ivan Shevanski wrote:
> To continue with my previous problems, now I'm trying out classes.  But 
> I have a problem (which I bet is easily solveable) that I really don't 
> get.  The numerous tutorials I've looked at just confsed me.For intance:
> 
 class Xyz:
> 
> ... def y(self):
> ... q = 2
> ...
> 
 Xyz.y()
> 
> Traceback (most recent call last):
>  File "", line 1, in ?
> TypeError: unbound method y() must be called with Xyz instance as first 
> argument
> (got nothing instead)
> 
> 
> So. . .What do I have to do? I know this is an extremley noob question 
> but I think maybe if a person explained it to me I would finally get it =/
> 
> 
> thanks in advance,
> 
> -Ivan

Generally you don't use class's directly.  Think if them as templates 
for objects.  Then you can use that class (template) to create many objects.

To create an object just call the class and assign the result to a name.

xyz = Xyz()
xyz.y()


Also,

In your example 'q' is assigned the value 2, but as soon as the method 
'y' exits, it is lost.  To keep it around you want to assign it to self.y.

class Xyz(object):   #  create an class to create an object instance.
def y(self)
   self.q = 2

xyz = Xyz()
xyz.y()
print xyz.q  #  prints 2



Cheers,
Ron











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


Re: Class Help

2005-10-01 Thread Ron Adam
Ron Adam wrote:

> Also,
> 
> In your example 'q' is assigned the value 2, but as soon as the method 
> 'y' exits, it is lost.  To keep it around you want to assign it to self.y.

Ooops,  That should say ...
"To keep it around you want to assign it to self.q."   <---self.q

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


Re: "no variable or argument declarations are necessary."

2005-10-03 Thread Ron Adam
Steven D'Aprano wrote:
> On Mon, 03 Oct 2005 06:59:04 +, Antoon Pardon wrote:

> 
> x = 12.0 # feet
> # three pages of code
> y = 15.0 # metres
> # three more pages of code
> distance = x + y
> if distance < 27:
> fire_retro_rockets()
> 
> And lo, one multi-billion dollar Mars lander starts braking either too
> early or too late. Result: a new crater on Mars, named after the NASA
> employee who thought the compiler would catch errors.

Yes, and a reserved position in the unemployment line as well, I would bet.

> Declared variables have considerable labour costs, and only marginal
> gains. Since the steps you take to protect against other errors will also
> protect against mistyping variables, declarations of variables is of
> little practical benefit.

Also checking types is not the same as checking values.

In most cases where critical code is used you really want value testing 
not type checking.  This is where self validating objects are useful and 
there is nothing preventing anyone from using them in Python.

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


Re: "no variable or argument declarations are necessary."

2005-10-04 Thread Ron Adam
Antoon Pardon wrote:
> Op 2005-10-03, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
> 
>>On Mon, 03 Oct 2005 06:59:04 +, Antoon Pardon wrote:
>>
>>
>>>Well I'm a bit getting sick of those references to standard idioms.
>>>There are moments those standard idioms don't work, while the
>>>gist of the OP's remark still stands like:
>>>
>>>  egold = 0:
>>>  while egold < 10:
>>>if test():
>>>  ego1d = egold + 1
>>
>>for item in [x for x in xrange(10) if test()]:
>>
>>But it isn't about the idioms. It is about the trade-offs. Python allows
>>you to do things that you can't do in other languages because you
>>have much more flexibility than is possible with languages that
>>require you to declare variables before using them. The cost is, some
>>tiny subset of possible errors will not be caught by the compiler. But
>>since the compiler can't catch all errors anyway, you need to test for
>>errors and not rely on the compiler. No compiler will catch this error:
>>
>>x = 12.0 # feet
>># three pages of code
>>y = 15.0 # metres
>># three more pages of code
>>distance = x + y
>>if distance < 27:
>>fire_retro_rockets()
>>
>>And lo, one multi-billion dollar Mars lander starts braking either too
>>early or too late. Result: a new crater on Mars, named after the NASA
>>employee who thought the compiler would catch errors.
> 
> 
> Using (unit)tests will not guarantee that your programs is error free.
> 
> So if sooner or later a (unit)tested program causes a problem, will you
> then argue that we should abondon tests, because tests won't catch
> all errors.

Maybe you need to specify what kind of errors you want to catch. 
Different types of errors require different approaches.

* Errors that interrupt program execution.

These are Type errors and/or illegal instruction errors such as divide 
by zero.  Try-excepts and checking attributes where these are possible 
to handle them should be used.

* Human 'user' input errors.

Value testing is what is needed for these.

* Programming errors...

Nothing will replace testing here.


I think what you want is optional name and object locking in order to 
prevent certain types of errors and increase reliability and dependability.

Name locking - This will allow you to be able to depend that a 
specific name refers to a specific object.  But that object can still be 
modified if it's mutable.

Object locking - This would make a non mutable object from a mutable 
object.  A function could work here for lists. This probably isn't 
possible with many complex objects.  Names need to be rebound in many 
objects for them to work.  I think this may be much harder to do than it 
seems.

An example, (but probably not possible to do).

 Const = {}
 Const['pi'] = 3.1415926535897931

 ... add more keys/value pairs ...

 lockobject Const   # prevent object from being changed
 lockname Const # prevent name 'Const' from being rebound

 ... many pages of code ...

 print Const['pi']  # dependable result?


Is this the type of control you want?
Would it make your programs more dependable or reliable?

Name locking might be implemented with additional name spaces, but they 
would need to be checked prior to other name spaces, so it could slow 
everything down.

And there would probably be ways to unlock objects.  But maybe that's 
not a problem as I think what you want to prevent is erroneous results 
due to unintentional name changes or object changes.

I think both of these would have unexpected side effects in many cases, 
so their use would be limited.

Cheers,
Ron
















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


Re: "no variable or argument declarations are necessary."

2005-10-05 Thread Ron Adam
Antoon Pardon wrote:
> Op 2005-10-04, Ron Adam schreef <[EMAIL PROTECTED]>:
> 
>>Antoon Pardon wrote:
>>
>>>Op 2005-10-03, Steven D'Aprano schreef <[EMAIL PROTECTED]>:
>>>
>>>>And lo, one multi-billion dollar Mars lander starts braking either too
>>>>early or too late. Result: a new crater on Mars, named after the NASA
>>>>employee who thought the compiler would catch errors.
>>>
>>>
>>>Using (unit)tests will not guarantee that your programs is error free.
>>>
>>>So if sooner or later a (unit)tested program causes a problem, will you
>>>then argue that we should abondon tests, because tests won't catch
>>>all errors.
>>
>>Maybe you need to specify what kind of errors you want to catch. 
>>Different types of errors require different approaches.
> 
> 
> I want to catch all errors of course.

Yes, of course, and so do other programmers.  What I mean is to try and 
break it down into specific instances and then see what the best 
approach is for each one is.

When I first started leaning Python I looked for these features as well, 
but after a while my programming style changed and I don't depend on 
types and names to check my data near as much now.  But instead write 
better organized code and data structures with more explicit value 
checks where I need them.

My concern now is having reusable code and modules I can depend on.  And 
also separating my data and data management operations from the user 
interface.  Having functions and names that don't care what type the 
objects are, makes doing this separation easier.

Another situation where typeless names are useful is routines that 
explicitly check the type, then depending on the type does different 
things.  For example if you have a list with a lot of different type 
objects stored in it, you can sort the contents into sublists by type.

Looking at it from a different direction, how about adding a keyword to 
say,  "from this point on, in this local name space, disallow new 
names".  Then you can do...

def few(x,y):
a = 'a'
b = 'b'
i = j = k = l = None
no_new_names
# raise an error after here if a new name is used.
...
for I in range(10):   <--  error
   ...

This is more suitable to Pythons style than declaring types or variables 
I think.  Add to this explicit name-object locking to implement 
constants and I think you would have most of the features you want.

so...

 no_new_names # limit any new names
 lock_name name   # lock a name to it's current object


Since names are stored in dictionaries,  a dictionary attribute to 
disallow/allow new keys, and a way to set individual elements in a 
dictionary to read only would be needed.  Once you can do that and it 
proves useful, then maybe you can propose it as a language feature.

These might also be checked for in the compile stage and would probably 
be better as it wouldn't cause any slow down in the code or need a new 
dictionary type.

An external checker could possibly work as well if a suitable marker is 
used such as a bare string.

 ...
 x = y = z = None
 "No_New_Names"# checker looks for this
 ...
 X = y/z   # and reports this as an error
 return x,y

and..

 ...
 Author = "Fred"
 "Name_Lock Author"# checker sees this...
 ...
 Author = "John"   # then checker catches this
 ...

So there are a number of ways to possibly add these features.

Finding common use cases where these would make a real difference would 
also help.

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


Re: "no variable or argument declarations are necessary."

2005-10-06 Thread Ron Adam
Bengt Richter wrote:
> On Wed, 05 Oct 2005 11:10:58 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:

>>Looking at it from a different direction, how about adding a keyword to 
>>say,  "from this point on, in this local name space, disallow new 
>>names".  Then you can do...
>>
>>def few(x,y):
>>   a = 'a'
>>   b = 'b'
>>   i = j = k = l = None
>>   no_new_names
>>   # raise an error after here if a new name is used.
>>   ...
>>   for I in range(10):   <--  error
>>  ...
>>
>>This is more suitable to Pythons style than declaring types or variables 
>>I think.  Add to this explicit name-object locking to implement 
>>constants and I think you would have most of the features you want.
>>
> 
> You can do that now with a decorator, if you are willing to assign something
> to no_new_names (so it won't give you a name error if it doesn't exist). E.g.,

Works for me.

__lock_names__ = True

It's not too different than __name__ == '__main__'...


>  >>> def nnn(f):
>  ... names = f.func_code.co_names
>  ... assert 'no_new_names' not in names or names[-1]=='no_new_names', 
> 'Bad name:%r'%names[-1]
>  ... return f
>  ...
>  >>> @nnn
>  ... def few(x,y):
>  ... a = 'a'
>  ... b = 'b'
>  ... i = j = k = l = None
>  ... no_new_names=None
>  ... for i in range(10): print i,
>  ...
>  Traceback (most recent call last):
>File "", line 1, in ?
>File "", line 3, in nnn
>  AssertionError: Bad name:'range'

Hmm... To make it work this way, the globals and arguments need to have 
local references.

@nnn
def few(x,y):
 global range
 range = range
 x,y = x,y
 a = 'a'
 b = 'b'
 i = j = k = l = None
 L = 1
 __no_new_names__ = True
 L += 1
 for i in range(x,y):
 print I

>  >>> @nnn
>  ... def few(x,y):
>  ... a = 'a'
>  ... b = 'b'
>  ... i = j = k = l = None
>  ... no_new_names=None
>  ... return a,b,i,j,k,l
>  ...
>  >>> few(123,456)
>  ('a', 'b', None, None, None, None)
> 
> No guarantees, since this depends on the unguaranteed order of 
> f.func_code.co_names ;-)

I had the thought that collecting the names from the 'STORE FAST' lines 
of dis.dis(f) would work nicely, but...  dis.dis() doesn't return a 
string like I expected, but prints the output as it goes.  This seems 
like it would be easy to fix and it would make the dis module more 
useful.  I'd like to be able to do...

D = dis.dis(f)

An alternate option to output the disassembly to a list of of tuples. 
That would make analyzing the output really easy.  ;-)

Something like...

good_names = []
nnnames = False
for line in dis.dislist(f):
if line[2] = 'SAVE_FAST':
if not nnnames:
if line[-1] = '(__no_new_names__)':
nnnames=True
continue
good_names.append(line[-1])
else:
 assert line[-1]in good_names, 'Bad name:%r'% line[-1] 



So, I wonder what kind of errors can be found by analyzing the disassembly?


>>so...
>>
>>no_new_names # limit any new names
>>lock_name name   # lock a name to it's current object
> 
> That last one you could probably do with a decorator that imports dis and
> checks the disassembly (or does the equivalent check of the byte code) of f
> for STORE_FASTs directed to particular names after the lock_name name 
> declaration,
> which you would have to spell as a legal dummy statement like
> lock_name = 'name'
> 
> or perhaps better, indicating a locked assignment e.g. to x by
> 
> x = lock_name = expr  # lock_name is dummy target to notice in 
> disassembly, to lock x from there on

Using dis.dis it becomes two sequential 'STORE_FAST' operations.  So add 
(x) to the don't change list, and catch it on the next 'STORE_FAST' for 
(x).  ;-)

  28  12 LOAD_GLOBAL  2 (True)
  15 DUP_TOP
  16 STORE_FAST   0 (x)
  19 STORE_FAST   8 (__lock_name__)


>>Since names are stored in dictionaries,  a dictionary attribute to 
>>disallow/allow new keys, and a way to set individual elements in a 
>>dictionary to read only would be needed.  Once you can do that and it 
>>proves useful, then maybe you can propose it as a language feature.
> 
> I would want to explore how to compose functionality with exi

Re: "no variable or argument declarations are necessary."

2005-10-06 Thread Ron Adam
Fredrik Lundh wrote:

> Ron Adam wrote:
> 
> 
>>Is there a way to conditionally decorate?  For example if __debug__ is
>>True, but not if it's False?  I think I've asked this question before. (?)
> 
> 
> the decorator is a callable, so you can simply do, say
> 
> from somewhere import debugdecorator
> 
> if not __debug__:
> debugdecorator = lambda x: x

Ah... thanks.

I suppose after(if) lambda is removed it would need to be.

def nulldecorator(f):
return f

if not __debug__:
   debugdecorator = nulldecorator


> or
> 
> def debugdecorator(func):
> if __debug__:
> ...
> else:
> return func
> 
> etc.

This one came to mind right after I posted.  :-)


>  




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


Re: Why do I get an import error on this?

2005-10-07 Thread Ron Adam
Steve wrote:
> I'm trying to run a Python program on Unix and I'm encountering some
> behavior I don't understand.  I'm a Unix newbie, and I'm wondering if
> someone can help.
> 
> I have a simple program:
> 
> 
> #! /home/fergs/python/bin/python
> import sys, os
> import cx_Oracle
> 
> 
> If I run it through the Python interpreter, this way:
> 
>  >> python test.py
> 
> it runs fine.
> 
> But if I try to run it as an executable script, this way:
> 
>  >> test.py
> 
> I get an import error that says it can't find cx_Oracle.
> 
> Why does it behave differently when I run it in these two ways, and
> what do I need to do to make it run successfully either way?

I ran across something similar with using py2exe.  I think it occurs 
when there are more than one file with the same name in different 
locations in the search path.  Try renaming cx_Oracle to _cx_Oracle then 
import as...

import _cx_Oracle as cx_Oracle

Of course your problem might be entirely different. But this might help.

Cheers,
Ron





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


dis.dis question

2005-10-08 Thread Ron Adam

Can anyone show me an example of of using dis() with a traceback?

Examples of using disassemble_string() and distb() separately if 
possible would be nice also.


I'm experimenting with modifying the dis module so that it returns it's 
results instead of using 'print' it as it goes.  I want to make sure it 
works for all the current use cases (or as many as possible), but I 
haven't been able to find any examples of using dis with tracebacks 
using google.  I keep getting various copies of the current and older 
Python doc pages when I search, and not much else.

How much other python code depends on the dis() and disassembly() 
functions?  Is it used by other modules or is it meant to be a stand 
alone tool?

The changes I've made (for my own use so far) is to have disassembly() 
return a bare unformatted table, (list of list), that can easily be 
examined with python, and then to use a dis2str() function to return a 
nice formatted output-string from the table.  In order to have dis() 
display properly in an interactive shell as well as printing, I have 
dis() return a disassembly list object with a  __repr__() method to call 
dis2str().

class disobj(list):
 """ A disassembly list object """
 def __init__(self, dislist, name=None, lasti=-1):
 self[:] = dislist
 self.name = name
 self.lasti = lasti
 def __repr__(self):
 return dis2str(self, self.name, self.lasti)

That seems to work well in both the shell and with 'print'.  And it 
still allows direct table introspection without having to parse the 
output.  ;-)

For example the get_labels() function used was reduced to ...

def getlabels(dislist):
 """ Get labels from disassembly list table. """
 return [x[4] for x in dislist if type(x[4]) is str]

Another benefit, is to be able to get the results without having to 
redirect, capture, and then reset sys.stdout.

But I still need to rewrite disassemble_string() and need to test it 
with tracebacks.

Cheers,
Ron

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


Re: Weighted "random" selection from list of lists

2005-10-08 Thread Ron Adam
Jesse Noller wrote:


> 60% from list 1 (main_list[0])
> 30% from list 2 (main_list[1])
> 10% from list 3 (main_list[2])
> 
> I know how to pull a random sequence (using random()) from the lists,
> but I'm not sure how to pick it with the desired percentages.
> 
> Any help is appreciated, thanks
> 
> -jesse

Just add up the total of all lists.

 total = len(list1)+len(list2)+len(list3)
 n1 = .60 * total# number from list 1
 n2 = .30 * total# number from list 2
 n3 = .10 * total# number from list 3

You'll need to decide how to handle when a list has too few items in it.

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


Re: dis.dis question

2005-10-09 Thread Ron Adam
Ron Adam wrote:
> 
> Can anyone show me an example of of using dis() with a traceback?
> 
> Examples of using disassemble_string() and distb() separately if 
> possible would be nice also.

  [cliped]

> But I still need to rewrite disassemble_string() and need to test it 
> with tracebacks.
> 
> Cheers,
> Ron

It seems I've found a bug in dis.py, or maybe a expected non feature. 
When running dis from a program it fails to find the last traceback 
because sys.last_traceback doesn't get set.  (a bug in sys?)  It works 
ok from the shell, but not from the program.

Changing it to to get sys.exc_info()[2], fix's it in a program, but then 
it doesn't work in the shell.  So I replaced it with the following which 
works in both.

 try:
 if hasattr(sys,'last_traceback'):
 tb = sys.last_traceback
 else:
 tb = sys.exc_info()[2]
 except AttributeError:
 raise RuntimeError, "no last traceback to disassemble"

I'm still looking for info on how to use disassemble_string().

Cheers,
Ron




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


Re: Function decorator that caches function results

2005-10-09 Thread Ron Adam
Steven D'Aprano wrote:
> On Sat, 08 Oct 2005 15:20:12 +0200, Lasse Vågsæther Karlsen wrote:
> 
> 
>>Ok, so I thought, how about creating a decorator that caches the 
>>function results and retrieves them from cache if possible, otherwise it 
>>calls the function and store the value in the cache for the next invokation.
>>
>>This is what I came up with so far:
>>
>>def cache_function(fn):
>> cache = {}
>> def cached_result(*args, **kwargs):
>> if args in cache:
>> return cache[args]
>> result = fn(*args, **kwargs)
>> cache[args] = result
>> return result
>> return cached_result
> 
> 
> I'm curious... where does cache live after you use cache_function to
> memoize some function? It doesn't appear to be an attribute of the newly
> memoized function, nor does it look like a global variable.

If I understand this correctly...

 if args in cache:

Creates a local binding to the "cache" object that gets returned with 
the cashed_result function the same as...

 result = fn(*args, **kwargs)

  ... the function 'fn' does here.  So they remain local bindings to 
objects in the scope they were first referenced from even after the 
function is returned.  In effect, 'cache' and 'fn' are replaced by the 
objects they reference before the cached_result function is returned.

Is this correct?

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


Re: Function decorator that caches function results

2005-10-09 Thread Ron Adam
Fredrik Lundh wrote:
> Ron Adam wrote:
> 
> 
>>In effect, 'cache' and 'fn' are replaced by the objects they reference
>>before the cached_result function is returned.
> 
> 
> not really; accesses to "free variables" always go via special cell objects
> (rather than direct object references), and the compiler uses special byte
> codes for all accesses to such objects.
> 
> this snippet illustrates the differences:
> 
> def func1():
> return a
> 
> def func2(a):
> return a
> 
> def wrapper(a):
> def func3():
> return a
> return func3
> 
> def decode(func):
> import dis
> print func.__name__ + ":"
> dis.dis(func)
> print "co_freevars =", func.func_code.co_freevars
> print "func_closure =", func.func_closure
> print
> 
> decode(func1)
> decode(func2)
> decode(wrapper(10))
> 
> if you run this on a recent version of Python, you get something like:
> 
> func1:
>   2   0 LOAD_GLOBAL  0 (a)
>   3 RETURN_VALUE
> co_freevars = ()
> func_closure = None
> 
> func2:
>   5   0 LOAD_FAST0 (a)
>   3 RETURN_VALUE
> co_freevars = ()
> func_closure = None
> 
> func3:
>   9   0 LOAD_DEREF   0 (a)
>   3 RETURN_VALUE
> co_freevars = ('a',)
> func_closure = (,)
> 
> note the use of LOAD_DEREF for the variable access.
> 
> Other opcodes include STORE_DEREF (that updates a local variable
> through a cell, used inside the "defining" scope), and MAKE_CLOSURE
> (which sets up the function object for functions that actually uses
> nested scopes; this is where the func_closure attribute is initialized).
> 
> (now, if I weren't limited to plain text, I could have drawn a nice little
> diagram for you, but that's an entirely different thread...)
> 
> 

Thanks Fred,  That's something useful to know when working with 
decorators I think.  And it should answer Stevens question too.

Abstract terminology is great once you already know the things and 
concepts it refers to.  But if you don't, finding where the abstract 
connects to reality is sometimes not easy.  There's nothing better than 
a good example to illistrate the concept.  ;-)

Cheers,
Ron

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


Re: non descriptive error

2005-10-09 Thread Ron Adam
Timothy Smith wrote:
> i have reproduced the error in this code block
> 
> #save values in edit
> self.FinaliseTill.SaveEditControlValue()
> if 
> Decimal(self.parent.TillDetails[self.TillSelection.GetStringSelection()]['ChangeTinBalance']))
>  
> == Decimal('0'):
> #box must be checked before continuing
> if self.PlacedInSafe.GetValue() != 1:
> self.parent.Popup("You must place the till draw back in 
> the safe","Till draw")
> else:
> #finalise the till draw
> if Decimal(self.TillFloat.GetLabel().split('$')[1]) 
> != Decimal('0'):
> Prompt = wx.MessageDialog(self,"""The correct amount 
> has not been returned from the till draw float to the main float!
> If you proceed please contact your 
> manager""","Change tin doesn't balance!",wx.YES_NO)
> if Prompt.ShowModal() == wx.ID_YES:
> self.Submit()
> else:
> self.parent.Popup('You have an outstanding change tin 
> balance on this till','Change tin')
> 
> 
> i have NO idea what in there could be making it have such a strange 
> error. it just says "error" when you try run it. there nothing terribly 
> strange being done.

Look for two possibilities.  There is most likely a bare try-except in 
either one of these functions or methods, *OR* in one of the functions 
or methods that calls this bit of code.

To try and pin it down further, introduce and error in here along with a 
print statement right before it, and see what happens.  The print lets 
you know your error was actually executed. If you get the same error, 
then the bare except is in a routine that calls this one but the actual 
error is at a later point.  If you get a new error, then they are both 
after that point.  Keep moving your indicator pair till you find the 
try-except that is giving you the errror.  Once you find the try-except 
pair that has intercepted the error, you can insert a bare raise right 
after the except and see the actual python error is.  That should give 
you a better idea of what's going on.

Cheers,
Ron



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


Re: Python's Performance

2005-10-09 Thread Ron Adam
Steven D'Aprano wrote:

> For what it is worth, Python is compiled AND interpreted -- it compiles
> byte-code which is interpreted in a virtual machine. That makes it an
> compiling interpreter, or maybe an interpreting compiler, in my book.

Good points, and in addition to this, the individual byte codes and many 
builtin routines in python are compiled 'C' code.  So it's really a 
matter of how many level of indirect references are between the the 
application code and the internal cpu registers.  Even in assembly 
language you can program though indirect data structures to simplify 
overall program design.

I really think the performance differences will get narrower as Python 
is developed further.  I for one would much rather have a language I can 
program new things in a matter of days, rather than one which would 
require a few thousand pages of reference material just to figure out 
where to start.

If I was forced to go back to MS C++ again, I think I would take up 
painting instead of programing as my main hobby.

;-)

Cheers,
Ron


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


Re: non descriptive error

2005-10-12 Thread Ron Adam
Steven D'Aprano wrote:
> Timothy Smith wrote:
> 
 i have NO idea what in there could be making it have such a strange
 error. it just says "error" when you try run it. there nothing terribly
 strange being done.
> 
> 
>> i am still coming across this error it's driving me nuts. usually i 
>> can find what's wrong, but it is becoming an increasingly annoying 
>> problem. i also get the same problem on a windows machine with the 
>> same installed. this time it's nothing to do with the decimal module. 
>> help!
> 
> 
> Go back to first principles. Can you grab all the modules being used, 
> and search them for the string "error"? Ignore any hits which are in a 
> comment. One of the others is almost certainly responsible.
> 
> You can test that by changing the string to "this is a PITA" and see if 
> your mysterious error message changes or not.

Maybe there's a way he can examine the traceback to find it.

I think there's probably a better way, but it may be a start.



def seetrace():
 import inspect
 print inspect.trace()
 print ''.join(inspect.trace(5)[0][4])

try:
 try:
  suspect code block
 a = 15+'c'
 print 'hello'
 for x in range(10):
 a = x
 
 except:
 seetrace()
 raise "my error"# you never see this

# This is why bare excepts are not a good idea.
except:
 raise "Error: your error"


In this example you never see "my error" because the outer try over 
rides it. but the prints's still print and give you information about 
the actual error in this case.


[(, 'gen.py', 17, '?', ["a = 
15+'c'\n"], 0)]
 try:
  suspect code block
 a = 15+'c'
 print 'hello'
 for x in range(10):

Traceback (most recent call last):
   File "gen.py", line 26, in ?
 raise "your error"
Error: your error


Hope this helps,
Ron

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


object inheritance and default values

2005-10-14 Thread Ron Adam

I'm trying to implement simple svg style colored complex objects in 
tkinter and want to be able to inherit default values from other 
previously defined objects.

I want to something roughly similar to ...

class shape(object):
 def __init__(self, **kwds):
  # set a bunch of general defaults here.
  self.__dict__.update(kwds)
def draw(self, x=0, y=0, scale=1.0):
  # draw the object

hello = shape(text='hello')
redhello = hello(color='red')
largeredhello = redhello(size=100)
largeredhiya = largeredhello(text='Hiya!')
largeredhiya.draw(c, 20, 50)


I think this will need to require __new__ or some other way to do it. 
But I'm not use how to get this kind of behavior.  Maybe the simplest 
way is to call a method.

redhello = hello.makenew( color='red' )

But I want to be able to have all the objects access alike?

Hmmm..  I think maybe if if don't ever access shape (or Shape) directly 
in my data structure, then __new__ would work?  So my first default 
object should be an instance of shape with a __new__ method to create 
more?  Ok, off to try it.  But any comments will be welcome.

Cheers,
Ron


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


Re: object inheritance and default values

2005-10-14 Thread Ron Adam
George Sakkis wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote:
> 
> 
>>I'm trying to implement simple svg style colored complex objects in
>>tkinter and want to be able to inherit default values from other
>>previously defined objects.
>>
>>I want to something roughly similar to ...
>>
>>class shape(object):
>> def __init__(self, **kwds):
>>  # set a bunch of general defaults here.
>>  self.__dict__.update(kwds)
>>def draw(self, x=0, y=0, scale=1.0):
>>  # draw the object
>>
>>hello = shape(text='hello')
>>redhello = hello(color='red')
>>largeredhello = redhello(size=100)
>>largeredhiya = largeredhello(text='Hiya!')
>>largeredhiya.draw(c, 20, 50)
>>
>>
>>I think this will need to require __new__ or some other way to do it.
>>But I'm not use how to get this kind of behavior.  Maybe the simplest
>>way is to call a method.
>>
>>redhello = hello.makenew( color='red' )
> 
> 
> Just name it '__call__' instead of makenew and you have the syntax sugar you 
> want:
> 
> def __call__(self, **kwds):
> new = self.__class__(**self.__dict__)
> new.__dict__.update(kwds)
> return new
> 
> Personally I would prefer an explicit method name, e.g. 'copy'; hiding the 
> fact that 'shape' is a
> class while the rest are instances is likely to cause more trouble than it's 
> worth.
> 
> George

Just got it to work with __call__ as a matter of fact.  ;-)

 def __call__(self,**kwds):
 for key in self.__dict__:
 if key not in kwds:
 kwds[key] = self.__dict__[key]
 return shape(**kwds)

The purpose having the objects not call the methods explicityly in this 
case is to simplify the data structure in a way that it doesn't care. 
The point is to create as much consistancy in the data structure as 
possible without having to special case some objects as base objects, 
and some as instances.

 # Triangle
 triangle = shape( obj='regpolygon',
   points=getrpoly(3),
   fill='grey',
   size=75
   )

 # Text
 text = shape( obj='text', fill='black', size=10 )

 # CAUTION ICON
 caution = group( triangle(x=6, y=5),
  triangle(fill='yellow'),
  text( text='!',
x=39, y=32, size=35,
font='times', style='bold' )
  )

I can use a shape() in the group exactly like triangle(), or text(). 
They are all the same thing to group. It's just a matter of what the 
defaults are.  This keeps things very simple.  ;-)

Then when it needs to be drawn...

 caution.draw(canvas, x, y, scale)

I still need to work on reusing and nesting groups and having them set 
default values. Maybe I need to make group a sub shape which contains a 
list of shapes, etc...

This is another work it out as I go project. ;-)

Cheers,
Ron























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


tkinter drawing

2005-10-15 Thread Ron Adam

I want to be able to easily create reusable shapes in Tkinter and be 
able to use them in mid level dialogs.  So after some experimenting I've 
managed to get something to work.

The following does pretty much what I need, but I think it can be 
improved on. So could anyone take a look and let me know what you think?

Some of the things I want to add, but aren't exactly sure how at this time:
Nested groups
Use tags to be able to change sub items later
Have items get attribues from the group if it doesn't have them

Hope this isn't too long.

Cheers, Ron



"""
Tkinter Color Vector Objects

Just the bare minimum to create re-sizable
and re-usable color icons in tkinter.
"""

import Tkinter as Tk
import math

def getregpoly(sides):
 """ Get points for a unit regular-polygon with n sides. """
 points = []
 ang = 2*math.pi / sides
 for i in range(sides):
 deg = (i+.5)*ang
 points.append(math.sin(deg)/2.0+.5)
 points.append(math.cos(deg)/2.0+.5)
 return points

def scale(points, scale):
 return [x*scale for x in points]

def move(points, x, y):
 xy = [x,y]*(len(points)//2)
 return [xy+coord for xy, coord in zip(xy,points)]

def translate(obj, x, y, zoom):
 p = scale(obj.points, obj.size)
 p = move(p, obj.x, obj.y)
 p = scale(p, zoom)
 return move(p, x, y)

def draw(obj, c, x=0 ,y=0, zoom=1):
 p = translate(obj, x, y, zoom)
 if obj.obj=='line':
 c.create_line( p, fill=obj.fill, width=obj.width,
arrow=obj.arrow )
 elif obj.obj=='rectangle':
 c.create_line( p, fill=obj.fill, outline=obj.outline,
width=obj.width)
 elif obj.obj=='polygon':
 c.create_polygon( p, fill=obj.fill, outline=obj.outline,
   width=obj.width, smooth=obj.smooth )
 elif obj.obj=='text':
 size = int(obj.size*zoom)
 font = (obj.font,size,obj.style)
 c.create_text(p, text=obj.text, font=font, fill=obj.fill)
 elif obj.obj=='oval':
 c.create_oval( p, fill=obj.fill, outline=obj.outline,
width=obj.width )
 elif obj.obj=='arc':
 c.create_arc( p, start=obj.start, extent=obj.extent,
   style=obj.style, fill=obj.fill,
   outline=obj.outline, width=obj.width )

class Shape(object):
 size = 1
 x = y = 0
 def __init__(self, **kwds):
 self.__dict__.update(kwds)
 def __call__(self, *args, **kwds):
 for key in self.__dict__:
 if key not in kwds:
 kwds[key] = self.__dict__[key]
 return self.__class__(*args, **kwds)
 def draw(self, c, x=0, y=0, scale=1.0):
 draw(self, c, x, y, scale)

class Group(list):
 obj = 'group'
 def __init__(self, *args, **kwds):
 self[:] = args
 self.__dict__.update(kwds)
 def __call__(self, *args, **kwds):
 args = self[:]+list(args)
 for key in self.__dict__:
 if key not in kwds:
 # make copies
 kwds[key] = self.__dict__[key]()
 return self.__class__(*args, **kwds)
 def draw(self, c, x=0, y=0, scale=1.0):
 for item in self:
 item.draw(c, x, y, scale)
 for key in self.__dict__:
 self.__dict__[key].draw(c, x, y, scale)

# base shapes.
text = Shape( obj='text', text='', fill='black', width=0,
   font='', style='', points=[0,0] )
line = Shape( obj='line', arrow='none', fill='black',
   smooth='false', width=1, points=[0,0,1,0])
rectangle = Shape( obj='rectangle', fill='', outline='black',
width=1, points=[0,0,1,.5])
polygon = Shape( obj='polygon', fill='grey', outline='',
  width=0, points=[0,0], smooth='false' )
oval = Shape( obj='oval', fill='grey', outline='',
   width=0, points=[0,0,1,.75] )
arc = Shape( obj='arc', fill='grey', outline='', width=0,
  style='arc', start='0', extent='90',
  points=[0,0,1,1])

# shape variations
chord = arc(style='chord')
pie = arc(style='pieslice')
circle = oval(points=[0,0,1,1])
square = rectangle(points=[0,0,1,1])
triangle = polygon( points=getregpoly(3))
octagon = polygon( points=getregpoly(8))

# CAUTION ICON
caution = Group(
 triangle(x=6, y=5, size=75),
 triangle(size=75, fill='yellow'),
 txt = text( text='!',
 x=38, y=32, size=30,
 font='times', style='bold') )

# ERROR ICON
circlepart = chord( x=15, y=15, size=25, fill='red',
 start='140', extent='155' )
error = Group(
 octagon(x=6, y=5, size=56),
 octagon(size=56, fill='red'),
 circle(x=9, y=9, size=37, fill='white'),
 circlepart(),
 circlepart(start='320') )

# QUESTION & INFO ICONS
bubbletip = polygon(points=[34,42,60,56,50,38])
question = Group(
 bubbletip(x=6, y=5),
 oval(x=6, y=5, size=60),
 bubbletip(fill='lightblue'),
 oval(s

Re: dis.dis question

2005-10-16 Thread Ron Adam
Bengt Richter wrote:
> On Sun, 09 Oct 2005 12:10:46 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:

>>Ron Adam wrote:

>>It seems I've found a bug in dis.py, or maybe a expected non feature. 
>>When running dis from a program it fails to find the last traceback 
>>because sys.last_traceback doesn't get set.  (a bug in sys?)  It works 
>>ok from the shell, but not from the program.
>>
>>Changing it to to get sys.exc_info()[2], fix's it in a program, but then 
>>it doesn't work in the shell.  So I replaced it with the following which 
>>works in both.
>>
>>try:
>>if hasattr(sys,'last_traceback'):
>>tb = sys.last_traceback
>>else:
>>tb = sys.exc_info()[2]
>>except AttributeError:
>>raise RuntimeError, "no last traceback to disassemble"

I guess I should do a bug report on this part so you can do the 
following in a program.

 try:
(something that fails)
 except:
dis.dis()   # print a dissasembled traceback.


>>I'm still looking for info on how to use disassemble_string().
>>
> 
> 
> One way to get dis output without modufying dis is to capture stdout:
> (ancient thing I cobbled together, no guarantees ;-)
> 
>  >>> class SOCapture:
>  ... """class to capture stdout between calls to start & end methods, 
> q.v."""
>  ... import sys
>  ... def __init__(self):
>  ... self.so = self.sys.stdout
>  ... self.text = []
>  ... def start(self, starttext=None):
>  ... """Overrides sys.stdout to capture writes.
>  ... Optional starttext is immediately appended as if written to 
> stdout."""
>  ... self.sys.stdout = self
>  ... if starttext is None: return
>  ... self.text.append(starttext)
>  ... def end(self, endtext=None):
>  ... """Restores stdout to value seen at contruction time.
>  ... Optional endtext is appended as if written to stdout before 
> that."""
>  ... self.sys.stdout = self.so
>  ... if endtext is None: return
>  ... self.text.append(endtext)
>  ... def gettext(self):
>  ... """Returns captured text as single string."""
>  ... return ''.join(self.text)
>  ... def clear(self):
>  ... """Clears captured text list."""
>  ... self.text = []
>  ... def write(self, s):
>  ... """Appends written string to captured text list.
>  ... This method is what allows an instance to stand in for stdout."""
>  ... self.text.append(s)

This is useful.  But I've already rewritten it. ;-)

I tried to keep it's output as close to the original as possible.  For 
example replacing the the call "dis.dis(func)" in test_dis.py with 
"print dis.dis(func)" is all that's needed to get it to pass the test.

 s = StringIO.StringIO()
 save_stdout = sys.stdout
 sys.stdout = s
 dis.dis(func)  #<- "print dis.dis(func)" passes
 sys.stdout = save_stdout
 got = s.getvalue()

The above could be replaced with...

 got = dis.dis(func)

The same minor change needs to be made in test_peepholer.py.  It uses 
dis to check the bytecodes.  I havn't found any other dependancies yet.


>  >>> diss(foo)
>  '  1   0 LOAD_FAST0 (x)\n  3 LOAD_CONST  
>  1 (1)\
>  n  6 BINARY_ADD  \n  7 LOAD_CONST
>2 (2)\n
>  10 BINARY_POWER\n 11 RETURN_VALUE\n'
>  >>> print diss(foo)
>1   0 LOAD_FAST0 (x)
>3 LOAD_CONST   1 (1)
>6 BINARY_ADD
>7 LOAD_CONST   2 (2)
>   10 BINARY_POWER
>   11 RETURN_VALUE

This is something I fixed (or added) so it displays the same from print, 
the terminal, and the command line.

I'm not sure if it can replace dis module. It may be different enough 
that it can't.  I suspect some might not like the table class. I'm 
thinking of making a bug report for the  traceback not being found when 
distb() is used inline, and attach the altered file for consideration 
and feedback.

One possibility is to dispense with keeping it like dis and rename it to 
something different and then additional functions and capabilities can 
be added to it without worrying about breaking anything. ;-)

BTW do you know how to read the time and version stamp of the beginning 
of .pyo and .pyc files?  I added that (just too easy not to) and would 
like to put the time and version stamp at the top of the output for 
those.  It's easy to take stuff out if needed.  ;-)

I can send it to you as an attached file if you'd like to take a look.

Cheers,
Ron



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


Re: dis.dis question

2005-10-16 Thread Ron Adam
[EMAIL PROTECTED] wrote:

> >> I'm still looking for info on how to use disassemble_string().
> 
> How about this?
> 
> >>> import dis
> >>> def f():
> ...   print "hello world"
> ... 
> >>> f.func_code.co_code
> 'd\x01\x00GHd\x00\x00S'
> >>> dis.disassemble_string(f.func_code.co_code)
>   0 LOAD_CONST  1 (1)
>   3 PRINT_ITEM 
>   4 PRINT_NEWLINE  
>   5 LOAD_CONST  0 (0)
>   8 RETURN_VALUE   
> 
> Skip

Thanks Skip,  I had figured it out, but I like your example.

 >>> import dis
 >>> dis.dis('d\x01\x00GHd\x00\x00S')
   0 LOAD_CONST   1 (1)
   3 PRINT_ITEM
   4 PRINT_NEWLINE
   5 LOAD_CONST   0 (0)
   8 RETURN_VALUE

It works!  :-)

Cheers,
Ron




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


Re: Comparing lists

2005-10-16 Thread Ron Adam
Christian Stapfer wrote:

> This discussion begins to sound like the recurring
> arguments one hears between theoretical and
> experimental physicists. Experimentalists tend
> to overrate the importance of experimental data
> (setting up a useful experiment, how to interpret
> the experimental data one then gathers, and whether
> one stands any chance of detecting systematic errors
> of measurement, all depend on having a good *theory*
> in the first place). Theoreticians, on the other hand,
> tend to overrate the importance of the coherence of
> theories. In truth, *both* are needed: good theories
> *and* carefully collected experimental data.
> 
> Regards,
> Christian

An interesting parallel can be made concerning management of production 
vs management of creativity.

In general, production needs checks and feedback to insure quality, but 
will often come to a stand still if incomplete resources are available.

Where as creativity needs checks to insure production, but in many cases 
can still be productive even with incomplete or questionable resources. 
  The quality may very quite a bit in both directions, but in creative 
tasks, that is to be expected.

In many ways programmers are a mixture of these two.  I think I and 
Steven use a style that is closer to the creative approach. I get the 
feeling your background may be closer to the production style.

Both are good and needed for different types of tasks. And I think most 
programmers can switch styles to some degree if they need to.

Cheers,
Ron

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


Re: Comparing lists

2005-10-16 Thread Ron Adam
Christian Stapfer wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> 
>>Christian Stapfer wrote:
>>
>>
>>>This discussion begins to sound like the recurring
>>>arguments one hears between theoretical and
>>>experimental physicists. Experimentalists tend
>>>to overrate the importance of experimental data
>>>(setting up a useful experiment, how to interpret
>>>the experimental data one then gathers, and whether
>>>one stands any chance of detecting systematic errors
>>>of measurement, all depend on having a good *theory*
>>>in the first place). Theoreticians, on the other hand,
>>>tend to overrate the importance of the coherence of
>>>theories. In truth, *both* are needed: good theories
>>>*and* carefully collected experimental data.
>>>
>>>Regards,
>>>Christian
>>
>>An interesting parallel can be made concerning management of production vs
>>management of creativity.
>>
>>In general, production needs checks and feedback to insure quality, but
>>will often come to a stand still if incomplete resources are available.
>>
>>Where as creativity needs checks to insure production, but in many cases
>>can still be productive even with incomplete or questionable resources.
>>The quality may very quite a bit in both directions, but in creative
>>tasks, that is to be expected.
>>
>>In many ways programmers are a mixture of these two.  I think I and Steven
>>use a style that is closer to the creative approach. I get the feeling
>>your background may be closer to the production style.
> 
> 
> This diagnosis reminds me of C.G. Jung, the psychologist,
> who, after having introduced the concepts of extra- and
> introversion, came to the conclusion that Freud was
> an extravert whereas Adler an introvert. The point is
> that he got it exactly wrong...
> 
>  As to the value of complexity theory for creativity
> in programming (even though you seem to believe that
> a theoretical bent of mind can only serve to stifle
> creativity), the story of the discovery of an efficient
> string searching algorithm by D.E.Knuth provides an
> interesting case in point. Knuth based himself on
> seemingly quite "uncreatively theoretical work" (from
> *your* point of view) that gave a *better* value for
> the computuational complexity of string searching
> than any of the then known algorithms could provide.
> 
> Regards,
> Christian


> (even though you seem to believe that
>> a theoretical bent of mind can only serve to stifle
>> creativity)

No, that is not at all what I believe.  What I believe is, "The 
insistence of strict conditions can limit creative outcomes."

The lack of those limits does not prevent one from using any resources 
(including theoretical ones) if they are available.

You seem to be rejecting experimental results in your views.  And the 
level of insistence you keep in that view, leads me to believe you favor 
a more productive environment rather than a more creative one.  Both are 
good, and I may entirely wrong about you, as many people are capable of 
wearing different hats depending on the situation.

I think the gist of this thread may come down to...

In cases where it is not clear on what direction to go because the 
choices are similar enough to make the choosing difficult.  It is almost 
always better to just pick one and see what happens than to do nothing.

Cheers,
Ron

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


Re: Comparing lists - somewhat OT, but still ...

2005-10-16 Thread Ron Adam
Christian Stapfer wrote:

> It turned out that the VAX compiler had been
> clever enough to hoist his simple-minded test
> code out of the driving loop. In fact, our VAX
> calculated the body of the loop only *once*
> and thus *immediately* announced that it had finished
> the whole test - the compiler on this student's
> PC, on the other hand, had not been clever enough
> for this type of optimization: hence the difference...
> 
>   I think this is really a cautionary tale for
> experimentalists: don't *believe* in the decisiveness
> of the outcomes your experiments, but try to *understand*
> them instead (i.e. relate them to your theoretical grasp
> of the situation)...
> 
> Regards,
> Christian

True understanding is of course the ideal, but as complexity increases 
even theoretical information on a complex system becomes incomplete as 
there are often other influences that will effect the outcome.

So the you could say: don't *depend* on the completeness of your 
theoretical information, try to *verify* the validity of your results 
with experiments.

Cheers,
Ron

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


Re: Comparing lists

2005-10-16 Thread Ron Adam
Christian Stapfer wrote:
> "Ron Adam" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>Christian Stapfer wrote:
>>
>>>"Ron Adam" <[EMAIL PROTECTED]> wrote in message
>>>news:[EMAIL PROTECTED]
>>>
>>>
>>>>Christian Stapfer wrote:
>>>>
>>>>
>>>>
>>>>>This discussion begins to sound like the recurring
>>>>>arguments one hears between theoretical and
>>>>>experimental physicists. Experimentalists tend
>>>>>to overrate the importance of experimental data
>>>>>(setting up a useful experiment, how to interpret
>>>>>the experimental data one then gathers, and whether
>>>>>one stands any chance of detecting systematic errors
>>>>>of measurement, all depend on having a good *theory*
>>>>>in the first place). Theoreticians, on the other hand,
>>>>>tend to overrate the importance of the coherence of
>>>>>theories. In truth, *both* are needed: good theories
>>>>>*and* carefully collected experimental data.
>>>>>
>>>>>Regards,
>>>>>Christian
>>>>
>>>>An interesting parallel can be made concerning management of production 
>>>>vs
>>>>management of creativity.
>>>>
>>>>In general, production needs checks and feedback to insure quality, but
>>>>will often come to a stand still if incomplete resources are available.
>>>>
>>>>Where as creativity needs checks to insure production, but in many cases
>>>>can still be productive even with incomplete or questionable resources.
>>>>The quality may very quite a bit in both directions, but in creative
>>>>tasks, that is to be expected.
>>>>
>>>>In many ways programmers are a mixture of these two.  I think I and 
>>>>Steven
>>>>use a style that is closer to the creative approach. I get the feeling
>>>>your background may be closer to the production style.
>>>
>>>
>>>This diagnosis reminds me of C.G. Jung, the psychologist,
>>>who, after having introduced the concepts of extra- and
>>>introversion, came to the conclusion that Freud was
>>>an extravert whereas Adler an introvert. The point is
>>>that he got it exactly wrong...
>>>
>>> As to the value of complexity theory for creativity
>>>in programming (even though you seem to believe that
>>>a theoretical bent of mind can only serve to stifle
>>>creativity), the story of the discovery of an efficient
>>>string searching algorithm by D.E.Knuth provides an
>>>interesting case in point. Knuth based himself on
>>>seemingly quite "uncreatively theoretical work" (from
>>>*your* point of view) that gave a *better* value for
>>>the computational complexity of string searching
>>>than any of the then known algorithms could provide.
>>>
>>>Regards,
>>>Christian
>>
>>
>>>(even though you seem to believe that
>>>
>>>>a theoretical bent of mind can only serve to stifle
>>>>creativity)
>>
>>No, that is not at all what I believe.  What I believe is, "The insistence 
>>of strict conditions can limit creative outcomes."
> 
> 
> That's agreed. But going off *blindly*experimenting*
> without trying to relate the outcome of that experimenting
> back to ones theoretical grasp of the work one is doing
> is *not* a good idea. Certainly not in the long run.
> In fact, muddling-trough and avoiding the question
> of suitable theoretical support for one's work is
> perhaps more typical of production environments.
> 
> 
>>The lack of those limits does not prevent one from using any resources 
>>(including theoretical ones) if they are available.
>>
>>You seem to be rejecting experimental results in your views.
> 
> 
> Not at all. You must have mis-read (or simply not-read)
> my posts in this thread and are simply projecting wildly,
> as psychoanalysts would call it, that is all.

The term 'rejecting' was the wrong word in this case.  But I still get 
the impression you don't trust experimental methods.


> As it appears, not even my most recent post has had
> *any* recognizable effect on your thoroughly
> misapprehending my position.
> 
> Regards,
> Christian

In most cases being able to see things from different view points is 
good.  So I was offering an additional view point, not trying to 
implying your's is less correct.

On a more practical level, Python as a language is a dynamic development 
process. So the level of completeness of the documentation, and the 
language it self, will vary a bit in some areas compared to others.  So 
as a programmer, it is often much more productive for me to  try 
something first and then change it later if it needs it.  Of course I 
would test it with a suitable range of data that represents the expected 
range at some point.

In any case, this view point has already been expressed I think.  

Cheers,
Ron

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


ordered keywords?

2005-10-17 Thread Ron Adam

Is there a way to preserve or capture the order which keywords are given?

 >>> def foo(**kwds):
...print kwds
...
 >>> foo(one=1, two=2, three=3)
{'three': 3, 'two': 2, 'one': 1}


I would love to reverse the *args, and **kwds as well so I can  use kwds 
to set defaults and initiate values and args to set the order of 
expressions.


def foo(**__dict__, *args):
   print args

print foo(x=10, y=20, x, y, x+y)
[10, 20, 30]


Ok, I know there is a lot of problems with that.  The reason I would 
like it is because I think there might be a use case for it where a 
function iterates over *args in order, but uses kwds to set values.

def drawshapes(**inits, *args):
 for obj in args:
 obj.draw()

drawshapes( triangle=3, square=4, color=red,
 polygon(triangle, color),
 polygon(square, color) )

This comes close to the same pattern used in SVG and other formats where 
you have definitions before expressions.  If I use keywords only, It 
won't keep the order, and if I use args before keywords, I have to 
pre-assign temporary 'None' values to the arguments in the parent or 
global scope.

Any ideas?

Cheers,
Ron























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


Re: ordered keywords?

2005-10-17 Thread Ron Adam
Diez B. Roggisch wrote:
> Ron Adam wrote:
> 
>>
>> Is there a way to preserve or capture the order which keywords are given?
>>
>>  >>> def foo(**kwds):
>> ...print kwds
>> ...
>>  >>> foo(one=1, two=2, three=3)
>> {'three': 3, 'two': 2, 'one': 1}
>>
>>
>> I would love to reverse the *args, and **kwds as well so I can  use 
>> kwds to set defaults and initiate values and args to set the order of 
>> expressions.
>>
>>
>> def foo(**__dict__, *args):
>>   print args
>>
>> print foo(x=10, y=20, x, y, x+y)
>> [10, 20, 30]
> 
> 
> This is not simply about reversing the order of kwargs and args - this 
> would require that keyword args would create bindings to variable names 
> in the scope of the caller. Which is an enterily different beast. And a 
> major semantic change in python, so it's not possible or at least not 
> happening before Python 3K.
> 
> Regards,
> 
> Diez

Yes, I kind of thought it would be pretty major.  What I'm asking is how 
to get anything close to this behavior in the current Python 2.4 now 
either with functions or with class's.  Or a way to generalize it in a 
nested data structure.  But that runs into similar problems of self 
reference.

I think the idea of putting the initialization first fits a lot of data 
patterns.  But I really don't know how the best way to implement that 
would be.

I was hoping it just might be possible (for P3k?) to have an argument 
list look to itself before looking to the caller, and then to globals 
after that.  And not create additional binding in the caller name space. 
  I think that would mean pre-creating the callee name space so it can 
be accessed by later terms in the argument list before control and the 
name space is handed over to the function.  I think this would be 
earlier evaluation instead of the late evaluation some want.





def lamb(args):
 for v in args: print v

def feedlamb():
 print locals()
 lamb( (lambda x=10, y=20: (x,y,x+y))() )
 print locals()

feedlamb()

{}
10
20
30
{}


AND... (!?)


def lamb(args):
 for v in args: print v

def feedlamb():
 print locals()
 y = 20
 lamb( (lambda x=10: (x,y,x+y))() )
 print locals()

feedlamb()

{}
10
20
30
{'y': 20}


Cool, this is the exact behavior I was thinking of, but without the 
lambda if possible, and without all the extra parentheses.  Anyway to 
clean this up?

Maybe it wouldn't be as big a change as it seems?  ;-)

Cheers,
Ron




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


Re: ordered keywords?

2005-10-17 Thread Ron Adam
Ron Adam wrote:

> 
> def lamb(args):
> for v in args: print v
> 
> def feedlamb():
> print locals()
> y = 20
> lamb( (lambda x=10: (x,y,x+y))() )
> print locals()
> 
> feedlamb()
> 
> {}
> 10
> 20
> 30
> {'y': 20}
> 
> 
> Cool, this is the exact behavior I was thinking of, but without the 
> lambda if possible, and without all the extra parentheses.  Anyway to 
> clean this up?
> 
> Maybe it wouldn't be as big a change as it seems?  ;-)
> 
> Cheers,
>Ron


Ok, this has a problem, there's no way to pass the values as keywords 
also.  The lambda's a bit too isolated. So the following doesn't work as 
expected.

lamb( (lambda x=10: (x,y,x+y,{'x':x}))() )


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


Re: ordered keywords?

2005-10-17 Thread Ron Adam
Kent Johnson wrote:
> Ron Adam wrote:
> 
>> drawshapes( triangle=3, square=4, color=red,
>> polygon(triangle, color),
>> polygon(square, color) )
>>
>> This comes close to the same pattern used in SVG and other formats 
>> where you have definitions before expressions.
> 
> 
> Why is this better than the obvious
> triangle=3
> square=4
> color=red
> drawshapes(polygon(triangle, color),
> polygon(square, color) )
> 
> or even
> drawshapes(polygon(3, red),
> polygon(4, red) )
> 
> which is concise and readable IMO...?
> 
> Kent

That example was over simplified quite a bit.  :-)

The reason I'm trying to get named attributes is so I can change colors 
or the text items later without having to recreate the object.  The 
objects I'm using are capable inheriting from other predefined objects 
so you only have to add or modify it a tiny bit.

For example the following creates shapes that build on each other and 
they all have a .draw() method to draw on a Tk canvas.  In addition they 
can be scaled, stretched and rotated. Well, the ones based on polygons 
and lines can be rotated and stretched.  I'm still working on how to do 
that with arcs and text items.



## These are the most basic shape elements which use the
## Tkinter canvas items specified by the 'obj' attribute.

# base shapes.
text = Shape( obj='text', text='', fill='black', size=1,
   font='', style='', pos=(0,0), points=(0,0) )

line = Shape( obj='line', arrow='none', fill='black', smooth='false',
   pos=(0,0), width=.1, points=(-.5,0,.5,0), size=1,
   rotate=0, center=(0,0) )

polygon = Shape( obj='polygon', fill='grey', outline='', size=1,
  smooth='false', pos=(0,0), width=0, points=(0,0),
  rotate=0, center=(0,0), ratio=(1,1) )

arc = Shape( obj='arc', fill='grey', outline='', pos=(0,0), width=0,
  size=1, style='arc', start='0', extent='90',
  points=(-.5,-.5,.5,.5) )



## This next group inherits from the shapes above and only
## needs to change what's different.

# shape variations
chord = arc(style='chord')
pie = arc(style='pieslice')
rectangle = polygon(points=[-.5,-.5,.5,-.5,.5,.5,-.5,.5])
triangle = polygon(points=getpolygon(3))
square = polygon(points=getpolygon(4))
octagon = polygon(points=getpolygon(8))
circle = polygon(smooth='true', points=getpolygon(16))

# The oval is stretched circle, which is a smoothed polygon.
# this can be rotated, the Tkinter oval can't.
oval = circle(ratio=(1,.7))


## Grouping combines the shapes together.  Again only what is
## different needs to be changed, such as color or size and
## relative position. Any previously defined
## shapes can be combined to create complex new ones.

# CAUTION ICON
caution = Group(
 triangle(pos=(6,5), size=75),
 triangle(fill='yellow', size=75),
 txt = text( text='!', font='times', style='bold',
 pos=(0,-3), size=30,) )

# ERROR ICON
error = Group(
 octagon(pos=(6,5), size=55),
 octagon(fill='red', size=55),
 circle(fill='white', size=37),
 circle(fill='red', size=25),
 line(fill='white', width=.2, rotate=45, size=28) )


## For this next group it would be nice if the bubbletip
## shape could be in the argument list, but it would need
## to be after the other refernces to it, and they
## would not find it. I did it this way to try out
## the idea of reusing objects, it would be no trouble
## just to duplicate the bubbletip in this case.

# QUESTION & INFO ICONS
bubbletip = polygon(points=[-5,10, 20,10, 30,30])
question = Group(
 bubbletip(pos=(6,5)),
 oval(pos=(6,5), size=60),
 bubbletip(fill='lightblue'),
 oval(fill='lightblue', size=60),
 txt = text( text='?', font='times', style='bold',
 size=25 ) )


## Here I just need to change the text element to 'i' to get
## the Info icon. Since it has a name we can do that.

info = question() # get a copy of question
info.txt.text = 'i'   # change the '?' mark to 'i'


These can all be in a file ready to import and then you can use them 
anywhere in Tkinter that accepts a normal canvas commands.

 caution.draw(c, pos=(70,50), scale=.5)  # small caution icon
 error.draw(c, pos=(150,48), scale=3)# triple sized error icon


Now this all works wonderfully, but I can only have one named attribute 
because I can't depend on the order a dictionary has.  So I'm going to 
probaby

Re: Vim capable IDE?

2005-10-18 Thread Ron Adam
Chris Lasher wrote:
> Thanks for your responses, guys. I can't get the PIDA page to come up
> for me; server timeout error. I'll have to look into Eclipse more, but
> I've been warned that it's resource greedy and that the VI plugin
> doesn't provide very much functionality. Still, that's hearsay, so I'll
> have to find out for myself.
> 
> I would have figured Vim or VI editing behavior would be a lot more
> prevalent in IDEs but it seems to be quite rare. I don't understand
> that, because a lot of people seem to use IDEs, and a lot of people
> seem to use VI/Vim or Emacs. Is it the young guns that are tied to the
> IDEs, never knowing powerful text-editors exist, and old dogs sticking
> to their favorite editors, not giving in to all those "distracting"
> bells and whistles of IDEs? What's the deal? A marriage of the two
> would seem like the best of both worlds.
> 
> Chris

What features are you looking for.  I think most Vim users just add what 
they want to Vim.

Here's what I use to launch a script and capture the output into a read 
only panel.  I think it may still needs a little fine tuning.  This is 
on windows, but it should work on linux with some minor changes.

Cheers,
Ron


Add this to your python.vim file in your ftplugin directory.

" Run a python script and get the output into a window.
set switchbuf=useopen
function! RunPython(rmode)
 if a:rmode=='wnd'
 " Run in python shell and capture the
 "   output to a vim buffer window.
 execute "w!"
 if bufnr("python_stdout") >0
 exe "sb python_stdout"
 else
 exe 'split python_stdout'
 endif
 setlocal noswapfile
 set buftype=nofile
 setlocal modifiable
 normal ggdG
 silent! exe 'r!python #'
 setlocal nomodified
 set filetype=txt
 normal 1G
 elseif a:rmode=='ext'
 " Execute script in python shell
 execute "w!"
 !start python -i %
 else
 " Open an interactive shell
 !start python
 endif
endfunction

" Add keymap to run and open console
map  :call RunPython("wnd")
map  :call RunPython("ext")
map  :call RunPython("psh")
imap  :call RunPython("wnd"):star
imap  :call RunPython("ext"):star
imap  :call RunPython("psh"):star
-- 
http://mail.python.org/mailman/listinfo/python-list


multi-property groups?

2005-10-19 Thread Ron Adam


I was trying to see if I can implement property groups so I can set and 
pass arguemts as dictionaries.  I think this will simplify interfacing 
to multiple objects and funtions that use a lot of keywords as arguments.

But so far, the the following seems like it's not the most efficient way 
to do it.  So is there a better way?  Is there a way to use properties 
to do this same thing?

I'd also like a way to override the dictionary methods __getitem__, 
__setitem__, and __delitem__.  (Or an equivalent)


Cheers,
Ron


class Pobject(object):
 """ an objects class that can have property groups """
 __props__ = {}
 def Properties(self, *args):
 dct = {}
 for i in args[1:]:
 dct.setdefault(i,None)
 self.__props__[args[0]]=dct
 return dct
 def __getattr__(self, name):
 for dct in self.__props__:
 if name in self.__props__[dct]:
 return self.__props__[dct].__getitem__(name)
 return self.__dict__[name]
 def __setattr__(self, name, value):
 for dct in self.__props__:
 if name in self.__props__[dct]:
 self.__props__[dct].__setitem__(name,value)
 return
 self.__dict__[name] = value

class shapes(Pobject):
 def __init__(self):
 self.A = self.Properties('A', 'square', 'triangle', 'cube')
 self.B = self.Properties('B', 'red', 'blue', 'green')
 def show(self, it):
 if it == 'shapes':
self.pp(it, self.A)  # pass properties as groups!
 elif it == 'colors':
self.pp(it, self.B)  # have several property groups!
 else:
print "I have no %s.\n" % it
 def pp(self, it, obj):
 print '%s I have:' % it
 for item in obj.keys():
 print '  %s = %r'  % (item,obj[item])
 print

box = shapes()
box.square = 10
box.blue = 5
print box.square
print box.blue
print box.green
box.purple = 'violet'
print box.purple
print
box.show('shapes')
box.show('colors')
box.show('flowers')


10
5
None
violet

shapes I have:
   cube = None
   square = 10
   triangle = None

colors I have:
   blue = 5
   green = None
   red = None

I have no flowers.


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


Re: multi-property groups?

2005-10-19 Thread Ron Adam

This is what I like about Python, there's almost always a way to do it.  ;-)

Here's an updated version that I think works, but it could use some review.

Any way to make this better?   Should grouped properties share 
references to objects?

Cheers,
Ron


"""
Grouped properties:

This need presented it self while programming Tkinter applications where 
a lot of keywords are used, but I think it would also be good for 
general interface building. The external view is of a single object, 
while the internal mechanism keeps the attributes groups so they can be 
forwarded easily as **kwds.

 class foo(object):
 def __init__(self):
 self.__setprops__(name, item_1, item_2, ... item_n)
 name.__doc__ = 'this is the name group of properties'
 def getter():
 ...
 def setter():
 ...
 def remover():
 ...
 name.__getitem__ = getter
 name.__setitem__ = setter
 name.__delitem__ = remover


The following is as close to getting to as I am able I think.
Only somewhat tested... but it seems to work.
"""


class Pdict(dict):
 # we need this so we can override the methods.
 __doc__ = "a property dictionary"

class Pobject(object):
 """ an object with grouped properties """
 __properties__ = {}
 def __setprops__(self, *args):
 """
 Create a group property
__setprops__(name, p1, p2, p3, ... pn)

 * all arguments are strings to be made into names.
 """
 dct = Pdict()
 for i in args[1:]:
 dct.setdefault(i,None)
 self.__properties__[args[0]] = dct
 self.__dict__[args[0]] = dct
 def __getattr__(self, name):
 for dct in self.__properties__:
 if name in self.__properties__[dct]:
 return self.__properties__[dct].__getitem__(name)
 return self.__dict__[name]
 def __setattr__(self, name, value):
 for dct in self.__properties__:
 if name in self.__properties__[dct]:
 self.__properties__[dct].__setitem__(name,value)
 return
 self.__dict__[name] = value



## A simple example to test it. ##

class shapes(Pobject):
 def __init__(self):

 # init the A properties
 self.__setprops__('A', 'square', 'triangle', 'cube', 'circle')
 self.A.__doc__ = 'These are the "A" properties'
 def A_getter(name):
 return -self.A[name] # just to show it will
 self.A.__getitem__ = A_getter

 # init the B properties
 self.__setprops__('B', 'red', 'blue', 'green', 'orange')
 self.B.__doc__ = 'These are the "B" properties'

 def show(self, it):
 if it == 'shapes':
self.pprint(self.A)  # pass properties as groups!
 elif it == 'colors':
self.pprint(self.B)  # have several property groups!
 else:
print "I have no %s.\n" % it

 def pprint(self, obj):
 print obj.__doc__
 for item in obj.keys():
 print '  %s = %r'  % (item,obj[item])
 print

box = shapes()

# Set items; no need to now what group
# they are in.
box.cube = 6
box.square = 4
box.triangle = 3
box.circle = 0

# Update a whole group at once with the group name.
box.B.update(blue='blue', green='green', red='rose', orange='orange')
box.red = 'red'

# Get items
print box.square
print box.blue
print box.green

# Show the groups.
box.show('shapes')
box.show('colors')
box.show('flowers')



## outputs ##

-4
blue
green
These are the "A" properties
   cube = 6
   square = 4
   triangle = 3
   circle = 0

These are the "B" properties
   blue = 'blue'
   green = 'green'
   orange = 'orange'
   red = 'red'

I have no flowers.

## end ##

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


Re: destroy your self????

2005-10-19 Thread Ron Adam
KraftDiner wrote:
> if I create an object like...
> 
> obj = None
> ...
> obj = anObject()
> 
> can obj set itself to none in some method of the class?
> 


Do you mean like this?


 >>> def foo():
...   global foo
...   del foo
...
 >>> foo()
 >>> foo
Traceback (most recent call last):
   File "", line 1, in ?
NameError: name 'foo' is not defined


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


Re: destroy your self????

2005-10-20 Thread Ron Adam
James wrote:
> Doesn't work for classes because self has no global reference.

True.  To make it work one would need to track instances and names and 
do comparisons... and so on.  So it's not worth it.  ;-)

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


Re: classmethods, class variables and subclassing

2005-10-21 Thread Ron Adam
Andrew Jaffe wrote:

> Hi,
> 
> I have a class with various class-level variables which are used to 
> store global state information for all instances of a class. These are 
> set by a classmethod as in the following (in reality the setcvar method 
> is more complicated than this!):
> 
> class sup(object):
> cvar1 = None
> cvar2 = None
> 
> @classmethod
> def setcvar1(cls, val):
> cls.cvar1 = val
> 
> @classmethod
> def setcvar2(cls, val):
> cls.cvar2 = val
> 
> @classmethod
> def printcvars(cls):
> print cls.cvar1, cls.cvar2

How about just using a mutable list?

class sup(object):
states = [None,None]   # [s1, s2, ...]
def set_s1(self, val):
self.states[0] = val
def get_s1(self):
return self.states[0]
def set_s2(self, val):
self.states[1] = val
def get_s2(self):
return self.states[1]

It keeps the states because the list isn't ever reassigned after it's 
created, so the values in it can change and all instances and subclasses 
can see the changed values.

Cheers,
Ron


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


Re: best way to replace first word in string?

2005-10-22 Thread Ron Adam
Steven D'Aprano wrote:

> def replace_word(source, newword):
> """Replace the first word of source with newword."""
> return newword + " " + "".join(source.split(None, 1)[1:])
> 
> import time
> def test():
> t = time.time()
> for i in range(1):
> s = replace_word("aa to become", "/aa/")
> print ((time.time() - t)/1), "s"
> 
> py> test()
> 3.6199092865e-06 s
> 
> 
> Is that fast enough for you?


I agree in most cases it's premature optimization.  But little tests 
like this do help in learning to write good performing code in general.

Don't forget a string can be sliced.  In this case testing before you 
leap is a win.   ;-)


import time
def test(func, n):
 t = time.time()
 s = ''
 for i in range(n):
 s = func("aa to become", "/aa/")
 tfunc = t-time.time()
 print func.__name__,':', (tfunc/n), "s"
 print s

def replace_word1(source, newword):
 """Replace the first word of source with newword."""
 return newword + " " + "".join(source.split(None, 1)[1:])

def replace_word2(source, newword):
 """Replace the first word of source with newword."""
 if ' ' in source:
 return newword + source[source.index(' '):]
 return newword

test(replace_word1, 1)
test(replace_word2, 1)


===
replace_word1 : -3.09998989105e-006 s
/aa/ to become
replace_word2 : -1.6324249e-006 s
/aa/ to become

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


Re: Question about inheritance...

2005-10-22 Thread Ron Adam
KraftDiner wrote:

> I have a base class called Shape
> And then classes like Circle, Square, Triangle etc, that inherit from
> Shape:
> 
> My quesiton is can a method of the Shape class call a method in Circle,
> or Square etc...?


This looks familiar. :-)

Yes, it can if it has references to them.

Could you explain a little better what you are doing.

Since I'm working on the same (or similar) thing maybe we can share our 
results, (or efforts).

Cheers,
Ron


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


Re: best way to replace first word in string?

2005-10-22 Thread Ron Adam
Steven D'Aprano wrote:

> On Sat, 22 Oct 2005 21:41:58 +0000, Ron Adam wrote:
> 
> 
>>Don't forget a string can be sliced.  In this case testing before you 
>>leap is a win.   ;-)
> 
> 
> Not much of a win: only a factor of two, and unlikely to hold in all
> cases. Imagine trying it on *really long* strings with the first space
> close to the far end: the split-and-join algorithm has to walk the string
> once, while your test-then-index algorithm has to walk it twice.
> 
> So for a mere factor of two benefit on short strings, I'd vote for the
> less complex split-and-join version, although it is just a matter of
> personal preference.
> 

Guess again...  Is this the results below what you were expecting?

Notice the join adds a space to the end if the source string is a single 
word.  But I allowed for that by adding one in the same case for the 
index method.

The big win I was talking about was when no spaces are in the string. 
The index can then just return the replacement.

These are relative percentages of time to each other.  Smaller is better.

Type 1 = no spaces
Type 2 = space at 10% of length
Type 3 = space at 90% of length

Type: Length

Type 1: 10split/join: 317.38%  index: 31.51%
Type 2: 10split/join: 212.02%  index: 47.17%
Type 3: 10split/join: 186.33%  index: 53.67%
Type 1: 100   split/join: 581.75%  index: 17.19%
Type 2: 100   split/join: 306.25%  index: 32.65%
Type 3: 100   split/join: 238.81%  index: 41.87%
Type 1: 1000  split/join: 1909.40%  index: 5.24%
Type 2: 1000  split/join: 892.02%  index: 11.21%
Type 3: 1000  split/join: 515.44%  index: 19.40%
Type 1: 1 split/join: 3390.22%  index: 2.95%
Type 2: 1 split/join: 2263.21%  index: 4.42%
Type 3: 1 split/join: 650.30%  index: 15.38%
Type 1: 10split/join: 3342.08%  index: 2.99%
Type 2: 10split/join: 1175.51%  index: 8.51%
Type 3: 10split/join: 677.77%  index: 14.75%
Type 1: 100   split/join: 3159.27%  index: 3.17%
Type 2: 100   split/join: 867.39%  index: 11.53%
Type 3: 100   split/join: 679.47%  index: 14.72%




import time
def test(func, source):
 t = time.clock()
 n = 600/len(source)
 s = ''
 for i in xrange(n):
 s = func(source, "replace")
 tt = time.clock()-t
 return s, tt

def replace_word1(source, newword):
 """Replace the first word of source with newword."""
 return newword + " " + " ".join(source.split(None, 1)[1:])

def replace_word2(source, newword):
 """Replace the first word of source with newword."""
 if ' ' in source:
 return newword + source[source.index(' '):]
 return newword + ' '   # space needed to match join results


def makestrings(n):
 s1 = 'abcdefghij' * (n//10)
 i, j = n//10, n-n//10
 s2 = s1[:i] + ' ' + s1[i:] + 'd.'# space near front
 s3 = s1[:j] + ' ' + s1[j:] + 'd.'# space near end
 return [s1,s2,s3]

for n in [10,100,1000,1,10,100]:
 for sn,s in enumerate(makestrings(n)):
 r1, t1 = test(replace_word1, s)
 r2, t2 = test(replace_word2, s)
 assert r1 == r2
 print "Type %i: %-8i  split/join: %.2f%%  index: %.2f%%" \
% (sn+1, n, t1/t2*100.0, t2/t1*100.0)









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


Re: Question about inheritance...

2005-10-22 Thread Ron Adam
KraftDiner wrote:

> Well here is a rough sketch of my code...
> This is giving my two problems.
> 
> 1) TypeError: super() argument 1 must be type, not classobj
> 2) I want to be sure the the draw code calls the inherited classes
> outline and not its own...
> 
> class Shape:
>   def __init__(self):
>   pass
>   def render(self):
>   print self.__class___
>   self.outline()
>   def outline(self):
>   pass
> 
> class Rect(Shape):
>   def __init__(self):
>   super(self.__class__, self).__init__()
>   def render(self):
>   super(self.__class__, self).draw()
>   def outline(self):
>   print 'outline' + self.__class__

I think Alex probably answered your question.  I'm still trying to 
figure out how use inheritance effectively myself.


Are you using this as an way to learn Python or do you want to use 
Python to render images?


What I'm trying to do in relation to this is to build a "small" subset 
of the SVG standard in tkinter. It looks like the SVG standard is going 
to be very popular graphic format on the web, hand held devices, and as 
a general graphics format.

http://www.w3.org/TR/SVG/

Python doesn't have good SVG support built in without importing a third 
party library, and the ones that are available need other libraries, 
etc...  They don't really support using SVG directly in programs.  So 
I'm experimenting with emplimenting some of the SVG functionality in 
Tkinter for drawing icons in dialog box's.  It's an experiment at the 
moment, but I'd like to see it grow into something more.

It doesn't need to be exactly like it, but the closer it is to the way 
the SVG standard works, the better.  That would make it easier to use 
some 'simple' existing SVG images, and easier to create SVG files as 
well, as it closes the gap between the canvas object and the VGA standard.

Anyway, I'm more than willing to get involved in a group to do this if 
anyone is interested and also thinks it may be worth while.

Cheers,
Ron











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


Re: best way to replace first word in string?

2005-10-22 Thread Ron Adam
[EMAIL PROTECTED] wrote:

> interesting. seems that "if ' ' in source:" is a highly optimized code
> as it is even faster than "if str.find(' ') != -1:' when I assume they
> end up in the same C loops ?


The 'in' version doesn't call a function and has a simpler compare.  I 
would think both of those results in it being somewhat faster if it 
indeed calls the same C loop.


 >>> import dis
 >>> def foo(a):
...   if ' ' in a:
...  pass
...
 >>> dis.dis(foo)
   2   0 LOAD_CONST   1 (' ')
   3 LOAD_FAST0 (a)
   6 COMPARE_OP   6 (in)
   9 JUMP_IF_FALSE4 (to 16)
  12 POP_TOP

   3  13 JUMP_FORWARD 1 (to 17)
 >>   16 POP_TOP
 >>   17 LOAD_CONST   0 (None)
  20 RETURN_VALUE
 >>>
 >>> def bar(a):
...   if str.find(' ') != -1:
...  pass
...
 >>> dis.dis(bar)
   2   0 LOAD_GLOBAL  0 (str)
   3 LOAD_ATTR1 (find)
   6 LOAD_CONST   1 (' ')
   9 CALL_FUNCTION1
  12 LOAD_CONST   2 (-1)
  15 COMPARE_OP   3 (!=)
  18 JUMP_IF_FALSE4 (to 25)
  21 POP_TOP

   3  22 JUMP_FORWARD 1 (to 26)
 >>   25 POP_TOP
 >>   26 LOAD_CONST   0 (None)
  29 RETURN_VALUE
 >>>
-- 
http://mail.python.org/mailman/listinfo/python-list


namespace dictionaries ok?

2005-10-24 Thread Ron Adam

Hi, I found the following to be a useful way to access arguments after 
they are passed to a function that collects them with **kwds.


 class namespace(dict):
 def __getattr__(self, name):
 return self.__getitem__(name)
 def __setattr__(self, name, value):
 self.__setitem__(name, value)
 def __delattr__(self, name):
 self.__delitem__(name)

 def foo(**kwds):
kwds = namespace(kwds)
print kwds.color, kwds.size, kwds.shape  etc

 foo( color='red', size='large', shape='ball',  etc..)


It just seems awkward to have to use "string keys" in this situation. 
This is easy and still retains the dictionary so it can be modified and 
passed to another function or method as kwds again.

Any thoughts?  Any better way to do this?

Cheers, Ron

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


Re: namespace dictionaries ok?

2005-10-24 Thread Ron Adam
James Stroud wrote:
> Here it goes with a little less overhead:
> 
> 
> py> class namespace:
> ...   def __init__(self, adict):
> ... self.__dict__.update(adict)
> ...
> py> n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
> py> n.bob
> 1
> py> n.ted
> 3
> 
> James

But it's not a dictionary anymore so you can't use it in the same places 
you would use a dictionary.

   foo(**n)

Would raise an error.

So I couldn't do:

def foo(**kwds):
   kwds = namespace(kwds)
   kwds.bob = 3
   kwds.alice = 5
   ...
   bar(**kwds) #<--- do something with changed items

Ron


> On Monday 24 October 2005 19:06, Ron Adam wrote:
> 
>>Hi, I found the following to be a useful way to access arguments after
>>they are passed to a function that collects them with **kwds.
>>
>>
>> class namespace(dict):
>> def __getattr__(self, name):
>> return self.__getitem__(name)
>> def __setattr__(self, name, value):
>> self.__setitem__(name, value)
>> def __delattr__(self, name):
>> self.__delitem__(name)
>>
>> def foo(**kwds):
>>  kwds = namespace(kwds)
>>  print kwds.color, kwds.size, kwds.shape  etc
>>
>> foo( color='red', size='large', shape='ball',  etc..)
>>
>>
>>It just seems awkward to have to use "string keys" in this situation.
>>This is easy and still retains the dictionary so it can be modified and
>>passed to another function or method as kwds again.
>>
>>Any thoughts?  Any better way to do this?
>>
>>Cheers, Ron

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


Re: namespace dictionaries ok?

2005-10-24 Thread Ron Adam
Simon Burton wrote:

> Yes!
> 
> I do this a lot when i have deeply nested function calls
> a->b->c->d->e
> and need to pass args  to the deep function without changing the
> middle functions.

Yes, :-)  Which is something like what I'm doing also.  Get the 
dictionary, modify it or validate it somehow, then pass it on.  I also 
find that when I'm passing variables as keywords,

  foo(name=name, address=address, city=city)

I really don't want (or like) to have to access the names with 
dictionary key as *strings* in the function that is called and collects 
them in a single object.


> In this situation I think i would prefer this variation:
> 
> class Context(dict):
>   def __init__(self,**kwds):
> dict.__init__(self,kwds)
>   def __getattr__(self, name):
> return self.__getitem__(name)
>   def __setattr__(self, name, value):
> self.__setitem__(name, value)
>   def __delattr__(self, name):
> self.__delitem__(name)
 >
> def foo(ctx):
>print ctx.color, ctx.size, ctx.shape
> 
> foo( Context(color='red', size='large', shape='ball') )
> 
> 
> This is looking like foo should be a method of Context now,
> but in my situation foo is already a method of another class.
> 
> Simon.

I didn't see what you were referring to at first.  But yes, I see the 
similarity.

Cheers,
Ron






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


Re: namespace dictionaries ok?

2005-10-24 Thread Ron Adam
James Stroud wrote:
> Oops. Answered before I finished reading the question.
> 
> James

Well, the one bad side effect (or feature depending on the 
circumstance), is it makes a copy.  I wonder if there is a way to modify 
the dictionary in place with a function to do the same thing instead of 
creating a new object?

Cheers,
Ron


> On Monday 24 October 2005 19:53, Ron Adam wrote:
> 
>>James Stroud wrote:
>>
>>>Here it goes with a little less overhead:
>>>
>>>
>>>py> class namespace:
>>>...   def __init__(self, adict):
>>>... self.__dict__.update(adict)
>>>...
>>>py> n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
>>>py> n.bob
>>>1
>>>py> n.ted
>>>3
>>>
>>>James
>>
>>But it's not a dictionary anymore so you can't use it in the same places
>>you would use a dictionary.
>>
>>   foo(**n)
>>
>>Would raise an error.
>>
>>So I couldn't do:
>>
>>def foo(**kwds):
>>   kwds = namespace(kwds)
>>   kwds.bob = 3
>>   kwds.alice = 5
>>   ...
>>   bar(**kwds) #<--- do something with changed items
>>
>>Ron
>>
>>
>>>On Monday 24 October 2005 19:06, Ron Adam wrote:
>>>
>>>>Hi, I found the following to be a useful way to access arguments after
>>>>they are passed to a function that collects them with **kwds.
>>>>
>>>>
>>>>class namespace(dict):
>>>>def __getattr__(self, name):
>>>>return self.__getitem__(name)
>>>>def __setattr__(self, name, value):
>>>>self.__setitem__(name, value)
>>>>def __delattr__(self, name):
>>>>self.__delitem__(name)
>>>>
>>>>def foo(**kwds):
>>>>kwds = namespace(kwds)
>>>>print kwds.color, kwds.size, kwds.shape  etc
>>>>
>>>>foo( color='red', size='large', shape='ball',  etc..)
>>>>
>>>>
>>>>It just seems awkward to have to use "string keys" in this situation.
>>>>This is easy and still retains the dictionary so it can be modified and
>>>>passed to another function or method as kwds again.
>>>>
>>>>Any thoughts?  Any better way to do this?
>>>>
>>>>Cheers, Ron
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace dictionaries ok?

2005-10-25 Thread Ron Adam
James Stroud wrote:
> Here it goes with a little less overhead:
> 
> 
> py> class namespace:
> ...   def __init__(self, adict):
> ... self.__dict__.update(adict)
> ...
> py> n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
> py> n.bob
> 1
> py> n.ted
> 3
> 
> James

How about...

 class namespace(dict):
 __getattr__ = dict.__getitem__
 __setattr__ = dict.__setitem__
 __delattr__ = dict.__delitem__


This seems to work, and eliminates the indirect method calls.

Cheers,
Ron

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


Re: namespace dictionaries ok?

2005-10-25 Thread Ron Adam
Duncan Booth wrote:
> Ron Adam wrote:
> 
>>James Stroud wrote:
>>
>>>Here it goes with a little less overhead:
>>>
>>>
> 
> 
> 
>>But it's not a dictionary anymore so you can't use it in the same places 
>>you would use a dictionary.
>>
>>   foo(**n)
>>
>>Would raise an error.
>>
>>So I couldn't do:
>>
>>def foo(**kwds):
>>   kwds = namespace(kwds)
>>   kwds.bob = 3
>>   kwds.alice = 5
>>   ...
>>   bar(**kwds) #<--- do something with changed items
>>
> 
> I agree with Steven D'Aprano's reply, but if you are set on it you could 
> try this:
> 
> 
>>>>class namespace(dict):
> 
>   def __init__(self, *args, **kw):
>   dict.__init__(self, *args, **kw)
>   self.__dict__ = self
> 
>   
> 
>>>>n = namespace({'bob':1, 'carol':2, 'ted':3, 'alice':4})
>>>>n.bob
> 
> 1
> 
>>>>n.bob = 3
>>>>n['bob']
> 
> 3
> 
> The big problem of course with this sort of approach is that you cannot 
> then safely use any of the methods of the underlying dict as they could be 
> masked by values.
> 
> P.S. James, *please* could you avoid top-quoting.

Or worse, the dictionary would become not functional depending on what 
methods were masked.


And this approach reverses that, The dict values will be masked by the 
methods, so the values can't effect the dictionary methods.  But those 
specific values are only retrievable with the standard dictionary notation.

 class namespace(dict):
 __getattr__ = dict.__getitem__
 __setattr__ = dict.__setitem__
 __delattr__ = dict.__delitem__

 n = namespace()
 n.__getattr__ = 'yes'# doesn't mask __getattr__ method.

 print n['__getattr__']   -> 'yes'

The value is there and __getattr__() still works.  But n.__getattr__ 
returns the method not the value.

So is there a way to keep the functionality without loosing the methods?


BTW, I agree with Steven concerning data structures.  This really isn't 
a substitute for a data structure.  Many keys will not work with this.

 n.my name = 'Ron'
 n.(1,2) = 25
 n.John's = [ ... ]

The use case I'm thinking of is not as a shortcut for data structures, 
but instead, as a way to keep names as names, and maintaining those 
names in a group.  Thus the namespace association.

def foo(**kwds):
   kwds = namespace(kwds)
   print kwds.name
   print kwds.value
   ...

name = 'ron'
value = 25
foo( name=name, position=position )

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


Re: Missing modules '_ssl', 'ext.IsDOMString', 'ext.SplitQName'

2005-10-25 Thread Ron Adam
[EMAIL PROTECTED] wrote:

> Hi,
> 
> unfortunately the result from py2exe won't run eventhough the original
> script runs without problems. The trouble is I'm at a loss as to where
> to start looking!
> 
> Martin.

Just a guess, Make sure any your file names aren't the same as any of 
the module names you are using.

Cheers,
Ron

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


Re: namespace dictionaries ok?

2005-10-25 Thread Ron Adam


Bengt Richter wrote:
> On Tue, 25 Oct 2005 16:20:21 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:

>>Or worse, the dictionary would become not functional depending on what 
>>methods were masked.
>>
>>
>>And this approach reverses that, The dict values will be masked by the 
>>methods, so the values can't effect the dictionary methods.  But those 
>>specific values are only retrievable with the standard dictionary notation.
>>
>>class namespace(dict):
>>__getattr__ = dict.__getitem__
>>__setattr__ = dict.__setitem__
>>__delattr__ = dict.__delitem__
>>
>>n = namespace()
>>n.__getattr__ = 'yes'# doesn't mask __getattr__ method.
>>
>>print n['__getattr__']   -> 'yes'
>>
>>The value is there and __getattr__() still works.  But n.__getattr__ 
>>returns the method not the value.
>>
>>So is there a way to keep the functionality without loosing the methods?
>>
>>
>>BTW, I agree with Steven concerning data structures.  This really isn't 
>>a substitute for a data structure.  Many keys will not work with this.
>>
>>n.my name = 'Ron'
>>n.(1,2) = 25
>>n.John's = [ ... ]
>>
>>The use case I'm thinking of is not as a shortcut for data structures, 
>>but instead, as a way to keep names as names, and maintaining those 
>>names in a group.  Thus the namespace association.
>>
>>   def foo(**kwds):
>>  kwds = namespace(kwds)
>>  print kwds.name
>>  print kwds.value
>>  ...
>>
>>   name = 'ron'
>>   value = 25
>>   foo( name=name, position=position )
>>
> 
> Just had the thought that if you want to add bindings on the fly modifying the
> original object, you could use the __call__ method, e.g.,
> 
>  >>> class NameSpace(dict):
>  ... __getattr__ = dict.__getitem__
>  ... __setattr__ = dict.__setitem__
>  ... __delattr__ = dict.__delitem__
>  ... def __call__(self, **upd):
>  ... self.update(upd)
>  ... return self
>  ...
>  >>> def show(x): print '-- showing %r'%x; return x
>  ...
>  >>> ns = NameSpace(initial=1)
>  >>> show(ns)
>  -- showing {'initial': 1}
>  {'initial': 1}
> 
> And updating with a second keyword on the fly:
> 
>  >>> show(show(ns)(second=2))
>  -- showing {'initial': 1}
>  -- showing {'second': 2, 'initial': 1}
>  {'second': 2, 'initial': 1}
> 
> FWIW ;-)
> 
> Regards,
> Bengt Richter

Getting better!  ;-)

That (or something similar) might avoid copying the whole thing in some 
situations, which is something I am concerned about.  But how to change 
a dict to a namespace without copying the contents item by item?

I'm not sure where or if this is going anywhere.  It may tie back into 
the properties groups example (see below) I posted earlier and keep 
finding improvements for.  ;-)

cheers,
Ron




""" GPobject.py

Grouped Properties Object:

This need has presented itself while programming Tkinter
applications where a *LOT* of keywords are used. I think
property groups would also be good for general interface
building.  The external view is of a single cohesive
object, while the internal mechanism keeps the attributes
grouped so they can be forwarded easily as **kwds.

 class foo(GPobject):
 def __init__(self):
 self.properties(name, item_1, item_2, ... item_n)
 def getter():
 ...
 def setter():
 ...
 def remover():
 ...
 self.name.doc( __doc__ string )
 self.name.get = getter
 self.name.set = setter
 self.name.remove = remover

 * The properties() method can also accept a dictionary.
 This will set both the names and the values at the same time.

 self.properties(name, dictionary)

 class myclass(GPobject):
 def __init__(self, **kwds):
 self.properties('kwds', **kwds)

 * group.setup() allows easy initiation of get, set, remove,
 and doc group settings in one step.

 self.properties( name, *members )
 self.name.setup( get=myget, set='set', del='del',
  doc='a property group' )

 * Using string flags to indicate default values lets you
 shorten the expression further.

 self.properties( name, *members )
 self.name.setup( myget, 'set', 'del', 'a property group')


The followi

Re: Setting Class Attributes

2005-10-25 Thread Ron Adam


the.theorist wrote:

> So that it'll be easier to remember the next time I find myself in the
> same situation on a different task, I'll extend the discussion
> somewhat.
> 
> Coming from C, I had expected that I'd get a new empty dict every time
> the __init__ function ran. Guido (or some other benevolent) had decided
> to implement things a little bit differently in Python. I understand
> that most everything is a pointer in Python. (which gives us cool stuff
> like recursive data structures) So I was wondering, they could have
> made the behavior C-like, but chose not to. The decision to bind
> everything in the function to the same default args must be a
> reflection of the Python Ideology. Philosophically, why was it done
> this way, and how does it fit in with Python's design as a language.

I didn't read too closely the thread leading up to this point so I may 
be stating something already stated or that is already obvious to you.

There is a difference between a pointer and name binding that you should 
keep in mind.  When using pointers in C you can feasibly have a chain of 
pointers.  In Python, it doesn't work that way unless you explicitly 
define a pointer type object to be used in such a way.  The normal 
behavior is for an expression to bind a name with the object that is 
bound to the other name.  So...

a = 1   # a binds to 1
b = a   # b binds to 1
c = b   # c binds to 1

So if you change what 'a' is bound to, 'b' and 'c' are still each bound 
to 1.

Some of the places where you get pointer type behavior is in container 
objects.  Look at the following sequence of instructions.

a = 1   # a binds to 1
b = [a] # first item in list is bound to 1,
 b binds to list.
c = b   # c bind to same list b is bound to.
a = 2   # a binds to 2
print b[0]  ->  1   # print first item in list b is bound to.
b[0] = 3# change first item in list b is bound to to 3
print c[0]  ->  3   # print first item in list c is bound to,
#   (same list as b is bound to)

If you can follow this easily you are well on your way to understanding 
Pythons storage model and philosophy.  Notice, a name isn't bound to 
another name.

This relationship is all over Python including the name binding of 
functions and class methods.  And also in class's as well.

Keep in mind the class body is executed at the time it is defined, and 
the methods are defined but not executed until they are used.  In the 
case of the __init__ it is when the class is called after an instance 
object is created.  When instances are created they share any class 
objects that were bound to names when the class was defined.  They don't 
share any objects that get bound to instance attribute names in methods 
later.

Does this help any?

Cheers,
Ron



> (hopefully, reasons will help me remeber why things are the way they
> are, so I don't forget in the future)
> -
> I've only been using Python for a few weeks. (Chose it over Perl,
> because Python syntax is cleaner). I really like Python (over C), as it
> makes coding and debugging much faster and easier.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Top-quoting defined [was: namespace dictionaries ok?]

2005-10-26 Thread Ron Adam


Duncan Booth wrote:

> No, I didn't think it was malice which is why I just added what I 
> considered to be a polite request at the end of my message. I assumed that 
> most people either knew the phrase or could find out in a few seconds using 
> Google so there wasn't much point in rehashing the arguments. Probably I 
> should have equally lambasted Ron for the heinous crime of bottom-quoting. 

I usually try to keep things in reasonable context and or order.  I tend 
to bottom quote only when either the message is short enough to fit on a 
single page, or when I'm adding new content that isn't a direct response 
to an individual item but builds on the above ideas.  Sometimes deciding 
what to trim out of various really good replies is difficult. ;-)

In any case, I don't take offense to any suggested improvements. I 
wouldn't be surprised if many of my posts were considered hard to follow 
at times.  A chronic sleeping disorder combined with dyslexia can 
sometimes make expressing my thoughts in words rather challenging on 
some (most) days.


>>quote from James (4)
> 
> comment from Ron (5)
> 
quote from James (2)
>>>
>>>comment from Ron (3)
>>>
quote from James (2)

>quote from Ron (1)
> 
> I spent a while trying to trim that down to relevant context, and in 
> particular trying to work out in what order the original statements had 
> been made. In the end I gave up and replied to an earlier message which was 
> more easily trimmable.

I was undecided weather to trim the later (earlier) responses or not, 
but decided to leave them in.


>>Also, here is a well written synopsis of the arguments in 
>>favor of top-posting and they may even be strong enough to legitimize the 
>>practice:
 >
> The arguments are mostly sound, but I would draw slightly different 
> conclusions:
> 
> Follow the conventions of the particular newsgroup or mailing list, but 
> with that in mind, for all replies, Middle Post. Respond to each point in 
> turn with lots of snipping.

In general I find a well written top post in a friarly prompt *email* to 
be fine.  What I refer to as well written in this case, is where the 
author restates the question, points, or issues in their own word first, 
and then follow that up with their response and or conclusions. 
Especially if it's any sort of official or at least non casual 
interchange.  In that case the quotes appended to the end serves as 
history that can be referenced if needed.

But in news groups, it's best to try and keep things conversational with 
as you call middle posts.  It allows people to add to the conversation 
as if they were all present at the same time, even though they may 
actually be replying at varying different times.  I tend to try not to 
break up paragraphs if possible though, and attempt to break my posts up 
into short paragraphs to leave spaces for others to insert their 
replies.  But I wouldn't claim I'm completely consistent on these issues 
myself.


 > He's right though, its not a religious issue.

Yep, I agree with this also.  ;-)

Cheers,
Ron


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


Re: Would there be support for a more general cmp/__cmp__

2005-10-26 Thread Ron Adam


Antoon Pardon wrote:

> Op 2005-10-25, Steven D'Aprano schreef <[EMAIL PROTECTED]>:

>>Can somebody remind me, what is the problem Antoon is trying to solve here?
> 
> 
> Well there are two issues. One about correct behaviour and one about
> practicallity.
> 
> The first problem is cmp. This is what the documentation states:
> 
> cmp(x, y)
> Compare the two objects x and y and return an integer according to
> the outcome. The return value is negative if x < y, zero if x == y
> and strictly positive if x > y. 
> 
> The problem is, that if someone implements a partial ordered class,
> with the rich comparisons, cmp doesn't behave correct. It can't
> behave correct because it will always give an number as a result
> and such a number implies one of three relations between two
> elements, but with partial ordered classes, it is possible none
> of these relations exist between those two elements. So IMO cmp
> should be changed to reflect this. This can be done either by cmp
> returning None or UnequalValues.  or by cmp raising UnequalValues
> in such a case.

Instead of changing cmp, why not just have several common versions to 
choose from instead of trying to make one tool do it all?

> The second part is one of practicallity. Once you have accepted cmp,
> should reflect this possibility, it makes sense that the __cmp__
> method should get the same possibilities, so that where it is more
> pratical to do so, the programmer can implement his partial order
> through one __cmp__ method instead of having to write six.
> 
> 
> In my opinion such a change would break no existing code. This
> is because there are two possibilities.
 >
> 1) The user is using cmp on objects that form a total order.
> In such circumstances the behaviour of cmp doesn't change.
> 
> 2) The user is using cmp on objects that don't form a total
> order. In such circumstances cmp doesn't give consistent
> results, so the code is already broken.


Adding complexity to cmp may not break code, but it could probably slow 
down sorting in general.  So I would think what ever improvements or 
alternatives needs to be careful not to slow down existing sorting cases.

Cheers,
Ron

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


Re: Missing modules '_ssl', 'ext.IsDOMString', 'ext.SplitQName'

2005-10-26 Thread Ron Adam


[EMAIL PROTECTED] wrote:

> Hi,
> 
> which file names do you mean?
> 
> -Martin.


I've ran across a case where I copied a module from the python libs 
folder to my source directory, it would work fine before I built with 
py2exe, but afterwards it would give a file not found error.  I haven't 
quite figures out why in this case.

To get around it, I renamed the file in my directory, by putting an 
underscore in front of it and importing '_name as name' in my program. 
Everything worked fine after that.

Another case is where I inadvertently had a file name in the file path 
with the same name as a file I was trying to import.  In this case the 
file would import in place of the library file, but then issue errors 
for objects or sub modules not being found.

So if the modules '_ssl', 'ext.IsDOMString', 'ext.SplitQName' are in a 
package, and you have a file in your source folder (or search path) with 
the same name as the directory or file they are in, you could be 
importing the wrong file and then not be finding the sub modules.

Like I said this is a guess, but I thought it might be worth mentioning 
if nothing else to rule out file path problems like these.

Cheers,
Ron





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


Re: How best to reference parameters.

2005-10-26 Thread Ron Adam

David Poundall wrote:

> However, what I really would like is something like...
> 
> class c_y:
> def __init__(self):
> self.P1 = [0, 'OB1', 0 ]
> self.P2 = [0, 'OB1', 1 ]
> self.P3 = [0, 'OB1', 2 ]
> self.P4 = [0, 'OB1', 3 ]
> 
> Because that way I can also hold binary loadings and data register
> (this is a PLC application) references which give me full information
> for handling the pump bits.
> 
> However, this means that I have to access the pump status bits like
> this...
> 
> Y.P4[0] = 1
> Y.P3[0] = 0
> 
> Which takes me away from the clean code
> 
> Y.P4 = 1
> Y.P3 = 0
> 
> That I would like to have.
> 
> Can anyone suggets a technique for parameter storage that may be able
> to give me what I want here ?
> 
> Thanks in advance.
> 
> David

How about the following?


(not tested)

class Pump(object):
 def __init__(self, name, ptype, number):
self.status = 0
 self.name = name
 self.ptype = ptype
 self.number = number

class C_Y(object):
  def __init__(self, *plist):
   index = []
   for p in plist:
   self.__dict__[p[0]] = Pump(*p)
   index.append(p[0])
   self.index = index
  def showall(self):
   out = []
   for item in self.index:
out.append( "%s:  %r\n"
% (item, self.__dict__[item] )

Then with a list formed as 

 pumplist = [ ('p1', 'ob1', 0),
  ('p2', 'ob1', 1),
  ('p3', 'ob1', 2),
  ...
  ]

You can then do...

c_y = C_Y(pumplist)

print c_y.p1.name --> 'p1'
print c_y.p1.status   --> 0
print c_y.p1.ptype--> 'ob1'
print c_y.p1.number   --> 0


c_y.p1.status = 1 # p1 on
c_y.p1.status = 0 # p1 off

print c_y.p2.status   --> 0
print c_y.p2.ptype--> 'ob1'
print c_y.p2.number   --> 1

etc...

print c_y.showall()


Cheers,
Ron











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


Re: How best to reference parameters.

2005-10-26 Thread Ron Adam


David Poundall wrote:
> Sadly Ron,  c_y can only see index and showall in your example.

Well, don't give up!  The approach is sound and I did say it was 
untested.  Here's a tested version with a few corrections. :-)

Cheers,
Ron




class Pump(object):
 def __init__(self, name, ptype, number):
 self.status = 0
 self.name = name
 self.ptype = ptype
 self.number = number

class C_Y(object):
  def __init__(self, plist):
   index = []
   for p in plist:
   self.__dict__[p[0]] = Pump(*p)
   index.append(p[0])
   self.index = index
  def showall(self):
   out = []
   for item in self.index:
out.append( "%s: %r, %r, %r\n"
% ( self.__dict__[item].name,
self.__dict__[item].status,
self.__dict__[item].ptype,
self.__dict__[item].number ) )
   return  ''.join(out)


pumplist = [ ('p1', 'ob1', 0),
  ('p2', 'ob1', 1),
  ('p3', 'ob1', 2) ]

c_y = C_Y(pumplist)

print c_y.p1.name
print c_y.p1.status
print c_y.p1.ptype
print c_y.p1.number
print

c_y.p1.status = 1
print c_y.p1.status
print

print c_y.showall()

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


Re: namespace dictionaries ok?

2005-10-26 Thread Ron Adam


Alex Martelli wrote:

> Ron Adam <[EMAIL PROTECTED]> wrote:
>...
> 
>> class namespace(dict):
>> def __getattr__(self, name):
>> return self.__getitem__(name)
> 
>...
> 
>>Any thoughts?  Any better way to do this?
> 
> 
> If any of the keys (which become attributes through this trick) is named
> 'update', 'keys', 'get' (and so on), you're toast; it really looks like
> a nasty, hard-to-find bug just waiting to happen.  If you're really
> adamant on going this perilous way, you might try overriding
> __getattribute__ rather than __getattr__ (the latter is called only when
> an attribute is not found "in the normal way").

Thanks Alex, I was wondering what the difference between __getattr__ and 
  __getattribute__ was.


> If you think about it, you're asking for incompatible things: by saying
> that a namespace X IS-A dict, you imply that X.update (&c) is a bound
> method of X; at the same time, you also want X.update to mean just the
> same thing as X['update'].  Something's gotta give...!-)
> 
> Alex

Part of the motivation of this is to try and keep names as names and 
data as data in my programs.  I would use dictionaries for data storage, 
and namespace_dicts for strictly name/value passing.  So some 
limitations with names are expected just as they would exist anywhere 
else with object names.  Ie.. can't use keywords, and using names of 
methods can cause objects to break, etc...

This seems to be the closest to a generic namespace object so far.

class namespace(dict):
 __getattribute__ = dict.__getitem__
 __setattr__ = dict.__setitem__
 __delattr__ = dict.__delitem__

Not having any public and/or visible methods of it's own is a good thing 
here.  So you would need to use dict.update(A_namespace, A_dict) in this 
case.  I don't think thats a problem.  Maybe a namespace object, (as I 
am thinking of it), should not have it's own interface, but inherit one 
from the object it's inserted into?

Anyway... this is experimental, and not production code of any sort. ;-)

Cheers,
Ron

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


Re: Would there be support for a more general cmp/__cmp__

2005-10-28 Thread Ron Adam


Antoon Pardon wrote:
> Op 2005-10-26, Ron Adam schreef <[EMAIL PROTECTED]>:
> 
>>Adding complexity to cmp may not break code, but it could probably slow 
>>down sorting in general.  So I would think what ever improvements or 
>>alternatives needs to be careful not to slow down existing sorting cases.
> 
> As a result of Bengt's post, I rewrote my test program, this is the
> program now.

...

> These are the results.
> 
> : 1000 repeats, 1000 long, 10.061425 secs
> : 1000 repeats, 1000 long,  9.544035 secs
> : 1000 repeats, 1000 long, 10.450864 secs
> : 1000 repeats, 1000 long, 15.566061 secs
> : 1000 repeats, 1000 long, 15.776443 secs
> 
> Results on a longer sequence were:
> 
> : 1000 repeats, 1 long, 146.722443 secs
> : 1000 repeats, 1 long, 139.480863 secs
> : 1000 repeats, 1 long, 152.623424 secs
> : 1000 repeats, 1 long, 224.630926 secs
> : 1000 repeats, 1 long, 228.663825 secs
> 
> The most interesting result of this test is the difference between
> cld and cle. IMO this difference is an indication of the cost
> that my idea would have on sorting, should it be implemented.
> That would be around 2%. I think that is bearable. Especially
> since this were very simple routines. The moment the comparison
> calculation become heavier, the relative contribution of the
> try: except will diminuish.


class cle:
   def __init__(self, i):
 self.value = int(i)

   def __comp__(self, other):
 return self.value - other.value

   def __lt__(self, other):
 try:
   return self.__comp__(other) < 0
 except UnequalValues:
   return False


This would only work with numeric types. I believe that cmp is closer to 
the following.

 return ( self.value < other.value and -1
  or self.value > self.value and 1
  or 0 )

I don't think it effects the speed a great deal however.


> If you are concerned about sorting times, I think you should
> be more concerned about Guido's idea of doing away with __cmp__.
> Sure __lt__ is faster. But in a number of cases writing __cmp__
> is of the same complexity as writing __lt__. So if you then
> need a __lt__, __le__, __eq__, __ne__, __gt__ and __ge__ it
> would be a lot easier to write a __cmp__ and have all rich
> comparisons methods call this instead of duplicating the code
> about six times. So you would be more or less forced to write
> your class as class cld or cle. This would have a bigger
> impact on sorting times than my suggestion.

I haven't heard he was removing __cmp__, but I would think the sort or 
sorted functions would just use the available comparisons methods or 
equivalent C code for base types.  So I expect it would only matter if 
you need a custom or modified sort.

Although It is a thought that these cases could be improved by making 
the sort value available to the underlying C sort function.  Something 
on the order of:

 __sortvalue__ == self.value.

Cheers,
Ron





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


Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Ron Adam


Steve Holden wrote:

> Sean McIlroy wrote:
> 
>> hi all
>>
>> i recently wrote a script that implements a puzzle. the interface
>> mostly consists of a bunch of colored disks on a tkinter canvas. the
>> problem is that the disks change their colors in ways other than the
>> way they're supposed to. it certainly isn't just a bug in my script,
>> since i can sometimes change the color of certain disks just by taking
>> focus off of the window and then bringing it back again! does this
>> sound like some known bug in tkinter? and if so, is there a recommended
>> way of working around it? if it matters, i'm using python 2.3 under
>> windows 95. any advice will be much appreciated.
>>
> It sounds to me much more like a bug in your script, to me at least. 
> Change of focus generates windowing events in much the same way as 
> clicking a button or hitting a key does, so I don't understand why you 
> think that "just [by] taking the focus off the window and bringing it 
> back again" shouldn't change anything.
> 
> For more specific insights we'd need to see some code, but sometimes 
> just changing your own focus from "Tkinter has a bug" to "my code has a 
> bug" is enough to help one find out what the problem really is. If you 
> have a soft toy I'd recommend you sit it down somewhere and explain to 
> it in great detail exactly why it can't be a bug in your program. You 
> may find you discover the error with no further assistance.
> 
> If not, fire the toy and ask again :-)
> 
> regards
>  Steve

To add to Steve's humorous perosonificatious techniques.  You should 
probably check that you aren't inadvertently using some sort of object 
id or window handle as a color value.  As long as the object you use 
returns an integer you won't get an error message, but instead get 
different colors when the canvas object is updated.  Like when changing 
the focus.

Another place to look is where you may be adding or converting rgb color 
values.

This function convert decimal rgb values to a hex rgb string that 
tkinter expects.

 def rgb(red, green, blue):
 """ Convert RGB value of 0 to 255 to
 hex Tkinter color string.
 """
 return '#%02x%02x%02x' % (red, green, blue)

Cheers,
Ron

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


Re: tkinter blues (greens, reds, ...)

2005-10-28 Thread Ron Adam


Sean McIlroy wrote:
> i'm using the canned colors ("pink", "orange", etc). should i try
> changing to explicit color specifications to see if that makes a
> difference? i'm not sure what the other guy meant by a "soft toy", but
> i take it the idea is to try and construct a correctness proof for the
> script, and see what keeps it (the proof) from working. it's a sound
> idea, of course, but the script is pretty darn straightforward, as you
> can see (below). anyway, i'll let you know how it turns out.
> 
> peace

Hmm... It worked fine for me.  I'm using python 2.4.1 on windows XP.

I didn't see anything particularly wrong with the program that might 
cause the problem you are referring to.  So I'm afraid I can't help much.

Maybe someone with 2.3 can reproduce it?

BTW,  Nice puzzle, much harder than it looks.

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


Re: Arguments for button command via Tkinter?

2005-10-31 Thread Ron Adam


Steve Holden wrote:
> Francesco Bochicchio wrote:
> 
>> Il Mon, 31 Oct 2005 06:23:12 -0800, [EMAIL PROTECTED] ha scritto:
>>
>>
>>> And yet the stupidity continues, right after I post this I finnally
>>> find an answer in a google search, It appears the way I seen it is to
>>> create a class for each button and have it call the method within that.
>>> If anyone else has any other ideas please tell.
>>
>>
>>
>> This is  how I do it: Supposing I have three buttons b1, b2 and b3, and I
>> want for each button to call the same callback with, as argument, the
>> button itself:
>>
>>
>> def common_callback(button):
>> # callback code here
>>
>>
>> class CallIt(objetc):
>> def __init__(function, *args ):
>> self.function, self.args = function, args
>> def __call__(self, *ignore):
>> self.function(button, *self.args)
>>
>> b1['command']= CallIt(common_callback, b1)
>> b2['command']= CallIt(common_callback, b2)
>> b3['command']= CallIt(common_callback, b3)
>>
>> This way you need only one class (a sort of custom callable) and
>> its instances gets called by Tkinter and in turn calls your
>> callback with the proper arguments.
>>
> I don't see why this is preferable to having the callback as a bound 
> method of the button instances. What's the advantage here? It looks 
> opaque and clunky to me ...

I'm not sure on the advantage either.  I just recently started handling 
my buttons with button id's.

 def __init__(self, *args, **kwds):
 ...

 b1 = Tk.Button( frame, text=button,
 command=self.command(button) )
 ...

The button label is used as the id above, but a number or code could 
also be used.

 def command(self, id):
 """ Assign a command to an item.
 The id is the value to be returned.
 """
 def do_command():
 self.exit(event=id)
 return do_command

In this case it's a dialog button so it calls the exit method which sets 
self.return to the button id before exiting.

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


Re: dictionary that have functions with arguments

2005-11-02 Thread Ron Adam


[EMAIL PROTECTED] wrote:
> hi
> i have a dictionary defined as
> 
> execfunc = { 'key1' : func1 }
> 
> to call func1, i simply have to write execfunc[key1] .
> but if  i have several arguments to func1 , like
> 
> execfunc = { 'key1' : func1(**args) }
> 
> how can i execute func1 with variable args?
> using eval or exec?
> 
> thanks

Eval or exec aren't needed.  Normally you would just do...

execfunc['key1'](**args)

If your arguments are stored ahead of time with your function...

execfunc = {'key1':(func1, args)}

You could then do...

func, args = execfunc['key1']
func(**args)

Cheers,
Ron


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


Re: dictionary that have functions with arguments

2005-11-02 Thread Ron Adam


Neal Norwitz wrote:

> Ron Adam wrote:
> 
>>Eval or exec aren't needed.  Normally you would just do...
>>
>>execfunc['key1'](**args)
>>
>>If your arguments are stored ahead of time with your function...
>>
>>Committed revision 41366.

Committed revision 41366 ?


>>You could then do...
>>
>>func, args = execfunc['key1']
>>func(**args)
> 
> 
> Interesting that both Ron and Alex made the same mistake.  Hmmm, makes
> me wonder if they are two people or not...
> 
> If args is a tuple, it should be:
> 
>   func(*args)

No mistake at all,  I simply reused the name the OP used in his example.

  >>>  execfunc = { 'key1' : func1(**args) }

There's no rule that says you can't name a dictionary 'args', and it 
wasn't part of the posters question.


> If you want the full generality and use keyword args:
> 
>   func(*args, **kwargs)

I tend to prefer (*args, **kwds) myself.  There are also times when I 
don't want full generality.  In many cases the less general your 
arguments are to a function the easier it is to catch errors.

Cheers,
Ron




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


Re: Tkinter- Building a message box

2005-11-07 Thread Ron Adam

Tuvas wrote:
> I've been trying to build a fairly simple message box in tkinter, that
> when a button is pushed, will pop up a box, that has a line of text, an
> entry widget, and a button, that when the button is pushed, will return
> the value in the line of text. However, while I can read the value of
> the button, I want to wait till the button is pushed to return the
> value. Any ideas of how I could do this?

The way I do it is to set self.result in the dialog to the return value 
just before closing and exiting.

And then instead of openiug the dialog directly I use a function to pass 
and sometimes modify the values to the dialog and then return the 
dialog.result value after it's closed.

Something like...

def domydialog(*args, **kwds):
#
# Check and modify args or kwds here if needed.
#
mydialog(*args, **kwds)
return mydialog.result

Cheers,
Ron

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


Re: Tkinter- Building a message box

2005-11-07 Thread Ron Adam


Tuvas wrote:
> Do you have any info on dialogs? I've been trying to find some, without
> alot of success...
> 

Be sure and look at the examples in python24/lib/lib-tk.  The Dialog.py 
file there does pretty much what you want.

In the dialog caller example I gave, it should have been ...

def domydialog(*args, **kwds):
 #
 # check or change args or kwds
 #
 d = mydialog(*args, **kwds)
 return d.result

I left out the returned object name 'd'.  Which is needed to get the 
result from the dialog instance.

Cheers,
Ron




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


Re: when and how do you use Self?

2005-11-07 Thread Ron Adam

Tieche Bruce A MSgt USMTM/AFD wrote:
> I am new to python,
> 
> Could someone explain (in English) how and when to use self?
> 
> I have been reading, and haven't found a good example/explanation
> 
>   
> Bruce Tieche ([EMAIL PROTECTED])


Hi,  Sometimes it's hard to get a simple answer to programming questions 
as everyone sees different parts of the elephant. ;-)


The use of self is needed because methods in class's are shared between 
all the instances (objects created from class's).  Because of this 
sharing, each method in a class needs a name to receive the specific 
instance reference which called it.

If every instance had it's own copy of all the methods in a class, we 
might not need 'self', but our programs would become extreme memory 
hogs. So sharing code is the great benefit of class's.

For example...

class myclass(object):
 def foo(self, a, b):
self.c = a + b

The method foo is defined but not executed until it is called later from 
an instance.  It's located in the class, but may be called from a lot, 
(thousands or more), different instances made from this class.

bar = myclass()# create a single instance (object)
# and bind it to the name bar.


Then when you do...

bar.foo(1,2)   # converted to ->  myclass(bar, 1, 2)

It calls the 'foo' method located in the parent class and pass's a 
reference to 'bar' as the first argument.  'self' becomes the new name 
for bar within foo.

 self.c = a + b#  same as ->  bar.c = a + b


This should be enough to visualize the basic relationship.  Hope it helped.

Cheers,
Ron











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


Re: Newbie Alert: Help me store constants pythonically

2005-11-07 Thread Ron Adam


Brendan wrote:
>>How many is LOOONG? Ten? Twenty? One hundred?
> 
> 
> About 50 per Model
> 
> 
>>If it is closer to 100 than to 10, I would suggest
>>putting your constants into something like an INI file:
>>
>>[MODEL1]  # or something more meaningful
>>numBumps: 1
>>sizeOfBumps: 99
>>
>>[MODEL2]
>>numBumps: 57
>>sizeOfBumps: 245

It looks to me like you may want a data file format that can be used by 
various tools if possible.

A quick search for 3d file formats finds the following list.  If any of 
these are close to what you need you may have an additional benefit of 
ready made tools for editing.

  http://astronomy.swin.edu.au/~pbourke/dataformats/


> which I'm not sure the .ini format can easily support.  I could use
> (key buzzword voice) XML, but  I fear that might send me down the
> 'overcomplicating things' path.  Your suggestion has given me some new
> places to search Google (configparser, python config files), so I'll
> look around for better ideas.
> 
>Brendan


One approach is to just store them as Python dictionaries.  Then just 
import it and use it where it's needed.

# models.py

M1 = dict(
numBumps=1,
sizeOfBumps=2,
transversePlanes=[
dict(type=3, z=4),
dict(type=5, z=6),
dict(type=3, z=8) ]
 )

M2 = ...


Then in your application...

# makemodels.py

import models

class Model(object):
def __init__( self, numBumps=None, sizOfBumps=None,
  transversePlanes=None ):
self.numBumps = numBumps
self.sizeOfBumps = sizeOfBumps
self.transversePlanes = []
for p in tranversePlanes:
self.transversePlanes.append(Plane(**p))

mod1 = Model(**models.M1)


This may be good to use until you decide how else to do it.  You can 
easily write the dictionaries to a text file in the chosen format later 
and that will tell you what you need to do to read the file back into 
the dictionaries as it will just be reversed.

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


Re: overloading *something

2005-11-07 Thread Ron Adam


James Stroud wrote:

> Hello All,
> 
> How does one make an arbitrary class (e.g. class myclass(object)) behave like 
> a list in method calls with the "*something" operator? What I mean is:

You need to base myclass on a list if I understand your question.

class myclass(list):
 def __init__(self, *items):
 # change items if needed
 # initate other attributes if needed
 list.__init__(self, *items)

Then the line below should work.  Of course it won't do much with out 
something in it.  ;-)

> myobj = myclass()
> 
> doit(*myobj)
> 
> I've looked at getitem, getslice, and iter. What is it if not one of these?
> 
> And, how about the "**something" operator?
> 
> James

A dictionary would be pretty much the same except subclassed from a 
dictionary of course.

Cheers,
Ron



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


Re: Returning a value from a Tk dialog

2005-11-07 Thread Ron Adam


Gordon Airporte wrote:
> The dialogs in tkColorChooser, tkFileDialog, etc. return useful values 
> from their creation somehow, so I can do stuff like this:
> 
> filename = tkFileDialog.askopenfilename( master=self )
> 
> I would like to make a Yes/No/Cancel dialog that can be used the same 
> way (returning 1/0/-1), but I just cannot figure out how to do it. At 
> best I've been able to get some kind of instance id from the object. How 
> does this work?

All of the dialogs you mention use functions as a caller.  And then the 
function is returning the result.


 From tkColorChooser...

def askcolor(color = None, **options):
 "Ask for a color"

 if color:
 options = options.copy()
 options["initialcolor"] = color

 return Chooser(**options).show()


In this case the Chooser(**options) initiates the dialog, and then the 
show() method is called and it returns the value.  The return line above 
is the same as...

cc = Chooser(**options)
color = cc.show()
return color

The other dialogs work in same way.  They are all based on 
tkCommonDialog, so look in tkCommonDialog.py to see exactly what's going on.

Cheers,
Ron



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


Re: overloading *something

2005-11-07 Thread Ron Adam


Alex Martelli wrote:
> Ron Adam <[EMAIL PROTECTED]> wrote:
> 
> 
>>James Stroud wrote:

>>>And, how about the "**something" operator?
>>>
>>>James
>>
>>A dictionary would be pretty much the same except subclassed from a 
>>dictionary of course.
> 
> 
> I believe this one is correct (but I have not checked in-depth!).
> 
> 
> Alex

A quick test shows the error message to be very specific in this case, 
where as the *something error message requests a more general sequence.


 >>> def foo(**b): pass
...
 >>> class a: pass
...
 >>> foo(**a)
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: foo() argument after ** must be a dictionary


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


Re: How to convert a number to hex number?

2005-11-08 Thread Ron Adam


Bengt Richter wrote:
> On 08 Nov 2005 08:07:34 -0800, Paul Rubin  wrote:
> 
> 
>>"dcrespo" <[EMAIL PROTECTED]> writes:
>>
>>hex(255)[2:]
>>>
>>>'ff'
>>
>>'%x'%255 is preferable since the format of hex() output can vary.  Try 
>>hex(33**33).
> 
> 
> Not to mention ([EMAIL PROTECTED] deleted ;-)
> 
>  >>> hex(-255)[2:]
>  'xff'
>  >>> hex(-255)
>  '-0xff'
>  >>> hex(-255&0xff)
>  '0x1'
> 
> Regards,
> Bengt Richter

I just happen to have been playing around with converting bases the last 
couple of days.  (idonowhy) ;-)

Oh yeah,  I was thinking of using base62 to generate non-repeating id 
strings and wanted to try it out.

A few nits ...

* Existing hex strings need to be converted to uppercase to work 
correctly with base2int() below.

* The reason I placed capitals before lower case is so sequences (in 
higher bases) will sort correctly.

* The base_iter (or generator) probably needs more work. I'm not sure 
what the best behavior should be for it, but iterating a string is 
faster than converting to int and back.


I doubt I can make these significantly faster at this point.  Using 
dictionary lookups really helped a lot going both ways.

Cheers,
Ron


import string
BaseDigits = sorted(list(string.digits + string.ascii_letters))
BaseDigitIndex = dict([(y,x) for (x,y) in enumerate(BaseDigits)])

def int2base(n, base):
 """
 Convert an integer to a string of base 2 to 62.
 """
 if not 1 < base < 63:
 raise ValueError, "base out of range"
 if n < 0:
 sign = '-'
 n = abs(n)
 else:
 sign = ''
 s = ''
 while 1:
 s = BaseDigits[n % base] + s
 n //= base
 if n == 0: return sign + s

def base2int(s, base):
 """
 Convert a string base 2 to 62 to an integer
 """
 if not 1 < base < 63:
 raise ValueError, "base out of range"
 if s[0] == '-':
 sign = -1
 s = s[1:]
 else:
 sign = 1
 n = 0
 i = lens = len(s)-1
 for digit in s:
 n += BaseDigitIndex[s[i]] * base ** (lens-i)
 i -= 1
 return n * sign

def base_iter(base=None, start='0'):
 """
 Generate a sequence of strings in base 2 to 62
 """
 if not 1 < base < 63:
 raise ValueError, "base out of range"
 digits = BaseDigits[:base]
 incriment = dict(zip(digits, digits[1:]+digits[:1]))
 def nBase():
 value = start
 maxindex = 0
 while 1:
 yield value
 i = maxindex
 while i >= 0:
 value = value[:i] + incriment[value[i]] + value[i+1:]
 if value[i] != '0':
 break
 i -= 1
 else:
 value = '1' + value
 maxindex += 1
 return nBase().next





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


Re: which feature of python do you like most?

2005-11-08 Thread Ron Adam


[EMAIL PROTECTED] wrote:

> which feature of python do you like most?
> 
> I've heard from people that python is very useful.
> Many people switch from perl to python because they like it more.
> 
> I am quite familiar with perl, I've don't lots of code in perl.
> Now, I was curious and interested in the python people.
> They certainly made their best choice from perl to python.

I wrote a few programs in perl that I thought were quite nice.  I loved 
the flexibility and powerful expressions.  But then when I went back to 
those programs several months later, I couldn't (easily) figure out what 
I did.  That was enough to turn me off of perl.

> but i have no interesting python experence before, thought i've read a
> few chapters
> of a python tutorial book. The things are much like the perl one.
> 
> I have no idea why people are so facinating with python.
> So I post this question:  What do you use in your dairy work with
> python?
> what is the thing that python makes you happy?

What I like most about Python is how many times the best way to solve a 
problem turns out to be how I thought of doing it in the first place.

For example, instead of using index's and arrays and defining structures 
for handling data, I can usually just iterate through a list of stuff 
and make changes as I go. Which is most likely how  see above. ;-)


> I certainly don't want to miss a language if it's so great!
> can anyone share your happy experence with python?
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a number to hex number?

2005-11-09 Thread Ron Adam


Bengt Richter wrote:
> On Wed, 09 Nov 2005 00:42:45 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:
> 
> 
>>
>>Bengt Richter wrote:
>>
>>>On 08 Nov 2005 08:07:34 -0800, Paul Rubin <http://[EMAIL PROTECTED]> wrote:
>>>
>>>
>>>
>>>>"dcrespo" <[EMAIL PROTECTED]> writes:
>>>>
>>>>
>>>>>>>>hex(255)[2:]
>>>>>
>>>>>'ff'
>>>>
>>>>'%x'%255 is preferable since the format of hex() output can vary.  Try 
>>>>hex(33**33).
>>>
>>>
>>>Not to mention ([EMAIL PROTECTED] deleted ;-)
>>>
>>> >>> hex(-255)[2:]
>>> 'xff'
>>> >>> hex(-255)
>>> '-0xff'
>>> >>> hex(-255&0xff)
>>> '0x1'
>>>
>>>Regards,
>>>Bengt Richter
>>
>>I just happen to have been playing around with converting bases the last 
>>couple of days.  (idonowhy) ;-)
>>
> 
> It seems to be one of those inevitable things, enjoy it ;-)

I do, it's one of the things that keeps me interested here and help me 
find new ideas to explore. :-)


> But you still use '-' + yourconversion(abs(x)) to deal with a negative number.
> That's what I was [EMAIL PROTECTED] about. You can't see the 'bits' in the 
> way one was
> used to with the old int values. My answer was a base-complement 
> representation,
> of which base-16 is a particular case. See
> 
> http://groups.google.com/group/comp.lang.python/msg/d8324946fcdff8f8
> 
> and the code in the second reference from there:
> 
> http://groups.google.co.uk/group/comp.lang.python/msg/359927a23eb15b3e

It seems I came in the back door concerning this discussion.  I hadn't 
read those specific threads.

I think I see what direction you are going in, but I'm not sure what the 
actual goal is.

Originally two's compliment representations were used to efficiently 
store signed integers when memory and processors where both real 
expensive slow and small. It also allowed for getting a signed number 
into a register in one instruction when you only had 8 bit data lines. 
And it was/is useful when designing electronic gate logic.

So what is the need to use a compliment form in other bases now?  I 
suppose it can still save memory, using a byte to store a value that can 
be stored in a single bit does seem to be a bit wasteful.  Then again 
the same could be said for any ascii representation of numbers.

Probably the most efficient way is to keep the number as integers
where it will be stored in binary and only convert it to the desired 
base if it needs to be viewed with a __repr__ or __str__ method.

hmm...  I'm not sure at what point in Pythons int handling they get 
converted from binary to decimal?

In this case the bit/byte storage issue of negative numbers would be 
side stepped.  But if you are working with hex or binary there still may 
be some situations you might still want to distinguish between the twos 
(or ones?) compliment hexadecimal or binary data.  Is this the correct 
issue you are referring to?

> I only put in characters for up to base 36, but it's a function parameter
> you can pass, so your digits ought to work if passed.
> The idea of base-complement is that the first digit is the zero digit for
> positive numbers and the digit for base-1 for negative numbers. This can
> be arbitrarily repeated to the left as fill without changing the numeric 
> value.
> 
> so for base 10 one is 01 and -1 is 99, and for hex that
> is 01 and FF. For base 2, 01 and 11. Etc. To make a general
> literal you need a prefix to the data that tells you the base value
> to use in interpreting the data part. A la 0x01, I proposed
> 0b.
> So +1 -1 is 0b2.01 and 0b2.11 or octal 0b8.01 and 0b8.77 or
> decimal 0b10.01 and 0b10.99 and hex 0b16.01 and 0b16.ff

So you are using two's compliment.

 1  ->  0b2.01
-1  ->  0b2.11  reverse bits, add 1
 3  ->  0b2.0011
-3  ->  0b2.1101or.. 2**4 - 3 = 13 = 1101

Then higher bases would be (base**digits)-n

 3  ->  0b8.03
-3  ->  0b8.75  8**2 - 3

 1  ->  0b10.01
-1  ->  0b10.99 10**2 - 1

So I presume you mean for edge cases...

89  ->  0b10.89 is 89 or must it be 0b10.089 ?
   -89  ->  0b10.921


How about preceding two's compliment with a 1b instead of 0b.  then all 
the value digits can use as values and no padding is needed, but can 
still be used if desired.

 3  ->  0b2.11   or 0b2.0011
-3  ->  1b2.101 1b2.1101

Signs could still be used also.

 3  ->   0b2.11
-3  ->  -0b2.11

I'm still 

Re: help make it faster please

2005-11-13 Thread Ron Adam


Fredrik Lundh wrote:
> Lonnie Princehouse wrote:
> 
> 
>>"[a-z0-9_]" means "match a single character from the set {a through z,
>>0 through 9, underscore}".
> 
> 
> "\w" should be a bit faster; it's equivalent to "[a-zA-Z0-9_]" (unless you
> specify otherwise using the locale or unicode flags), but is handled more
> efficiently by the RE engine.
> 
> (you can use \w in sets too, so you can do e.g. "[EMAIL PROTECTED]")
> 
> 

The \w does make a small difference, but not as much as I expected. 
Surprisingly a standard Python word iterator works just as well, and is 
easier to understand than the re version.

Which one is faster depends on the average word length and number of 
ignored characters.

Cheers,
Ron




Character count: 10
Word count: 16477
Average word size: 6.06906597075
word_counter: 0.06820057 (best of 3)
count_words: 0.07333837 (best of 3)


#

import string
import re
import time
import random


# Create a really ugly n length string to test with.
n = 10
random.seed(1)
lines = ''.join([ random.choice(string.ascii_letters * 2
   + '[EMAIL PROTECTED]&*()#/<>' + '\n' * 6) for x in 
range(n) ])
print 'Character count:', n
print 'Word count:', len(lines.split())
print 'Average word size:', float(n)/len(lines.split())



letters = string.lowercase + string.digits + '_@'

def word_iter(text, letters=letters):
 ltrs=letters.lower()
 wd = ''
 for c in text + ' ':
 if c in ltrs:
 wd += c
 elif wd != '':
 yield wd
 wd = ''

def word_counter(text):
 txt = text.lower()
 countDict={}
 for wd in word_iter(txt):
 if wd in countDict:
 countDict[wd] += 1
 else:
 countDict[wd] = 1
 return countDict




word_finder = re.compile('[EMAIL PROTECTED]', re.I)

def count_words(string, word_finder = word_finder):
 # avoid global lookups
 countDict = {}
 for match in word_finder.finditer(string.lower()):
 word = match.group(0)
 countDict[word] = countDict.get(word,0) + 1
 return countDict



foos = [word_counter, count_words]
r1 = r2 = None
for foo in foos:
 best_time = 0
 for n in range(3):
 t = time.clock()
 for line in lines.splitlines():
 countDict = foo(line)
 tt = time.clock()-t
 if tt > best_time: best_time = tt

 r1 = r2
 r2 = countDict
 if r1 != None:
 # change to 1 if assert fails to find problem
 if 0:
 for k in r1.keys():
 if r1[k] != r2[k]:
 print k,r1[k],r2[k]
 assert r1 == r2

 print '%s: %.8f (best of %d)' \
   % (foo.__name__, best_time, n+1)

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


Re: help make it faster please

2005-11-13 Thread Ron Adam


Fredrik Lundh wrote:
> Ron Adam wrote:
> 
> 
>>The \w does make a small difference, but not as much as I expected.
> 
> 
> that's probably because your benchmark has a lot of dubious overhead:

I think it does what the OP described, but that may not be what he 
really needs.

Although the test to find best of n, instead was finding worse of n. 
Which explains why I was getting a larger variance than I thought I 
should have been getting.


>>word_finder = re.compile('[EMAIL PROTECTED]', re.I)
> 
> 
> no need to force case-insensitive search here; \w looks for both lower-
> and uppercase characters.

But the dictionary keys need to be either upper or lower otherwise you 
count 'The' separately from 'the'.


>> for match in word_finder.finditer(string.lower()):
> 
> 
> since you're using a case-insensitive RE, that lower() call is not necessary.
> 
> 
>> word = match.group(0)
> 
> 
> and findall() is of course faster than finditer() + m.group().

Cool,  I don't use re that often so I just used what was posted to test 
against.

> 
>> t = time.clock()
>> for line in lines.splitlines():
>> countDict = foo(line)
>> tt = time.clock()-t
> 
> 
> and if you want performance, why are you creating a new dictionary for
> each line in the sample?

Because that's what the OP apparently wanted.  A line by line word 
count.  I originally did it to get an the over all count and then change 
it so it matched the re version that was posted.

> here's a more optimized RE word finder:
> 
> word_finder_2 = re.compile('[EMAIL PROTECTED]').findall
> 
> def count_words_2(string, word_finder=word_finder_2):
>  # avoid global lookups
>  countDict = {}
>  for word in word_finder(string):
>  countDict[word] = countDict.get(word,0) + 1
>  return countDict
> 
> with your original test on a slow machine, I get
> 
> count_words: 0.29868684 (best of 3)
> count_words_2: 0.17244873 (best of 3)
> 
> if I call the function once, on the entire sample string, I get
> 
> count_words: 0.23096036 (best of 3)
> count_words_2: 0.11690620 (best of 3)
> 
> 

Wow, a lot bigger difference than on my machine.An athlon 
64 3000+ on winxp.  I'm not sure how much difference that would make?

This is what I get after adding the above version to it, with the 
lower(). There's not quite as big a difference as you get, but the find 
all version is still faster than both the others.

Cheers,
Ron


Character count: 10
Word count: 16477
Average word size: 6.06906597075
word_counter: 0.06245989 (best of 3)
count_words: 0.07309812 (best of 3)
count_words_2: 0.04981024 (best of 3)


And as count all words...

Character count: 10
Word count: 16477
Average word size: 6.06906597075
word_counter: 0.05325006 (best of 3)
count_words: 0.05910528 (best of 3)
count_words_2: 0.03748158 (best of 3)


They all improve, but the re find all version is clearly better.



#

import string
import re
import time
import random

# Create a really ugly n length string to test with.
# The word length are
n = 10
random.seed(1)
lines = ''.join([ random.choice(string.ascii_letters * 2
   + '[EMAIL PROTECTED]&*()#/<>' + '\n' * 6) for x in 
range(n) ])
print 'Character count:', n
print 'Word count:', len(lines.split())
print 'Average word size:', float(n)/len(lines.split())


letters = string.lowercase + string.digits + '_@'

def word_iter(text, letters=letters):
 wd = ''
 for c in text + ' ':
 if c in letters:
 wd += c
 elif wd != '':
 yield wd
 wd = ''

def word_counter(text):
 countDict={}
 for wd in word_iter(text.lower()):
 if wd in countDict:
 countDict[wd] += 1
 else:
 countDict[wd] = 1
 return countDict


word_finder = re.compile('[EMAIL PROTECTED]', re.I).finditer

def count_words(string, word_finder=word_finder):
 # avoid global lookups
 countDict = {}
 for match in word_finder(string.lower()):
 word = match.group(0)
 countDict[word] = countDict.get(word,0) + 1
 return countDict


word_finder_2 = re.compile('[EMAIL PROTECTED]').findall

def count_words_2(string, word_finder=word_finder_2):
  # avoid global lookups
  countDict = {}
  for word in word_finder(string.lower()):
  countDict[word] = countDict.get(word,0) + 1
  return countDict


foos = [word_counter, count_words, count_words_2]
r1 = r2 = None
for foo in foos:
 best_time = 100  # too large to be use

Re: Loop until condition is true

2005-06-18 Thread Ron Adam
Joseph Garvin wrote:
> Peter Otten wrote:
> 
>> I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of 
>> "for
>> (" in the Python 2.4 source, so using these rough estimates do-while 
>> still
>> qualifies as "rarely used".
>>
>> Peter
>>
>>  
>>
> That's 136 times you'd have to use an ugly hack instead. I definitely 
> wouldn't mind an until or do/while.

I would happy with just having while: without a 1 or True to indicate a 
continuous loop.  Having a if-break at the end doesn't bother me at all.

while:
   
   if : break

Being able to move the break point to where it's needed or have more 
than one is a feature and not a problem. IMHO of course.

It also has the benefit that you have the option to do an extra bit of 
cleanup between the if and the break if you need to.  The until or 
do-while doesn't give you that option.

I suppose if an until : , could be made to be more 
efficient and faster than an if : ; break,  then I'd 
be for that.

   while:
  
  until [: suite]  # optional suite or block
  

But I doubt it would be significantly faster than an if statement with a 
break. So the only benefit I see is you don't have to use the break 
keyword, and the exit conditions will stand out in blocks with a lot of 
if statements in them.

Regards, Ron






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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-19 Thread Ron Adam
Bo Peng wrote:
> Roy Smith wrote:
> 
>> Can you give us some idea of what it is that you're trying to do?  It 
>> pretty unusual to see a requirement like that.
> 
> 
> def func(type_of_obj1, type_of_obj2, .):
>   callfunc( [
> type_of_obj1 and obj1a() or obj1b(),
> type_of_obj2 and obj2a() or obj2b(),
> 
> ])
> 
> callfunc can take arbitrary number of objects whose types are determined 
> by type_of_obj1 etc. I was using a bunch of if/else to create objects 
> and pass them to callfunc.
> 
> Since type_of_obj1 etc are usually binary and obj1a() etc will never be 
> false, the and/or solution does not look so bad in this case.
> 
> Thanks.
> Bo

Are you matching the order to the obj_type?

objlist = [ (type_obj1, obj1a, obj2b),
 (typ_obj2, obj2a, obj2b),
 etc...]

objs = [type_of_obj1, type_of_obj2, etc...]

for n in range(len(objs)):
 if objs[n] == objlist[n][0]:
  objlist[n][1]()
 else:
  objlist[n][2]()


What significance does the order have?


You might be able to use a dictionary of tuples.

call_obj = {(type_obj1,0):obj1a,
 (type_obj1,0):obj1b,
 (type_boj2,1):obj2a,
 (type_obj2,1):obj2b,
 etc... }
call_obj[(type_of_obj,order)]()


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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-20 Thread Ron Adam
Ron Adam wrote:

> You might be able to use a dictionary of tuples.
> 
> call_obj = {(type_obj1,0):obj1a,
> (type_obj1,0):obj1b,
> (type_boj2,1):obj2a,
> (type_obj2,1):obj2b,
> etc... }
> call_obj[(type_of_obj,order)]()
> 
> 
> Regards, Ron

This won't work like I was thinking it would.


But to get back to your is there a ? operator question...

Try this.

def foo():
return "foo"

def boo():
return "boo"

print (foo, boo)[1>0]()# prints "boo"
print (foo, boo)[1<0]()# prints "foo"

Regards,
Ron













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


Re: getting an object name

2005-06-22 Thread Ron Adam
David Bear wrote:
> Let's say I have a list called, alist. If I pass alist to a function,
> how can I get the name of it?
> 
> alist = range(10)
> 
> def afunction(list):
> listName = list.__name__ (fails for a list object)
> 

Using an object's name as data isn't a good idea because it will 
generally cause more problems than it solves.


If you have several different types of lists and need to handle them 
differently, then you might consider using class's that knows how to 
handle each type of list.

Also, if the name is really part of the data, then you should store the 
name as a string with the list.


class data1(object):
 def __init__(self, alist, name):
 self.list = alist
 self.name = name
 def data_type(self):
 print "This is a data1 object"

class data2(object):
 def __init__(self, alist, name):
 self.list = alist
 self.name = name
 def data_type(self):
 print "This is a data2 object"

list_a = data1( range(10), "small list")
print list_a.list
print list_a.name

list_b = data2( range(100), "large list")

def data_type(data):
 data.data_type()  # don't need the name here

data_type(list_a) # prints 'This is a data1 object'
data_type(list_b) # prints 'This is a data2 object'



You can also store a name with the list in a list if you don't want to 
use class's.

alist = ['mylist',range[10]]
print alist[0] # name
print alist[1] # list


Regards,
Ron

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


PEP 343, second look

2005-06-22 Thread Ron Adam

After taking a break from following PEP 343 and it's associated PEPs, I 
wanted to look at it again because it still seemed a bit hard to get my 
mind around.

 http://www.python.org/peps/pep-0343.html


> A new statement is proposed with the syntax:
> 
> with EXPR as VAR:
> BLOCK
> 
> Here, 'with' and 'as' are new keywords; EXPR is an arbitrary
> expression (but not an expression-list) and VAR is a single
> assignment target.

How is EXPR arbitrary?  Doesn't it need to be or return an object that 
the 'with' statement can use?  (a "with" object with an __enter__ and 
__exit__ method?)

And if so, what is the minimum 'with' class needed to create such an 
object?  It would need an __exit__ method, because there would be no 
point if it didn't have one.  Does it absolutely need an __enter__ 
method?  Are there any uses that might not require an __enter__?

Presuming __enter__ is always needed, would this be a minimum class that 
returns a 'with' object?

class With(object):
def __enter__(self):
pass
def __exit__(self):
pass


A 'with-generator' object would need __enter__ and __exit__ methods, and 
a try-yield-finally generator. Is there a name for a 'with-generator' 
object?  (a witherator ?)

It's possible that a function may be used that returns an 
'with-generator' object and would be used in the same way that range() 
is used in 'for' statements.

 func with_gen(func, *args, **args):
 wg = WithGen()
 wg.gen = func(*arg, **args)
 return wg


Which would use a generic with-generator base class.

 class WithGen(object):
def gen(self): # Should this raise an error
try:   # if it does't get over ridden?
yield None
finally:
pass
def __enter__(self):
try:
return self.gen.next()
except StopIteration:
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
if type is None:
try:
self.gen.next()
except StopIteration:
print "file closed by with statement"
return
else:
raise RuntimeError("generator didn't stop")
else:
try:
self.gen.throw(type, value, traceback)
except (type, StopIteration):
return
else:
raise RuntimeError("generator caught exception")


And used like this:

 def opening(filename, mode):
 f = open(filename, mode)
 try:
yield f
 finally:
f.close()

 with with_gen(opening, "testfile", "w") as f:
 f.write("test file")


This seems (to me) to be an easier to understand alternative to the 
decorator version.  The class could also be used as a base class for 
constructing other 'with' class's as well as the with_template decorator.

Will this work or am I missing something?  Any suggestions for a 
different (better) name for the with_gen function?

Regards,
Ron

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


Re: PEP 343, second look

2005-06-22 Thread Ron Adam
Paul Rubin wrote:
> Ron Adam <[EMAIL PROTECTED]> writes:
> 
>>>A new statement is proposed with the syntax:
>>>with EXPR as VAR:
>>>BLOCK
>>>Here, 'with' and 'as' are new keywords; EXPR is an arbitrary
>>>expression (but not an expression-list)...
>>
>>How is EXPR arbitrary?  Doesn't it need to be or return an object that
>>the 'with' statement can use?  (a "with" object with an __enter__ and
>>__exit__ method?)
> 
> 
> That's not a syntactic issue.  "x / y" is a syntactically valid
> expression even though y==0 results in in a runtime error.

The term 'arbitrary' may be overly broad.  Take for example the 
description used in the 2.41 documents for the 'for' statement.

"The expression list is evaluated once; it should yield an iterable object."


If the same style is used for the with statement it would read.

"The expression, (but not an expression-list), is evaluated once; it 
should yield an object suitable for use with the 'with' statement. ... "

Or some variation of this.


Regards,
Ron






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


Re: Favorite non-python language trick?

2005-06-24 Thread Ron Adam
George Sakkis wrote:
> "Joseph Garvin" wrote:
> 
> 
>>I'm curious -- what is everyone's favorite trick from a non-python
>>language? And -- why isn't it in Python?
> 
> 
> Although it's an optimization rather than language trick, I like the
> inline functions/methods in C++. There has been a thread on that in the
> past (http://tinyurl.com/8ljv5) and most consider it as useless and/or
> very hard to implement in python without major changes in the language
> (mainly because it would introduce 'compile-time' lookup of callables
> instead of runtime, as it is now). Still it might be useful to have for
> time-critical situations, assuming that other optimization solutions
> (psyco, pyrex, weave) are not applicable.
> 
> George

Thanks for the link George, It was interesting.

I think some sort of inline or deferred local statement would be useful 
also.  It would serve as a limited lambda (after it's removed), eval 
alternative, and as a inlined function in some situations as well I think.

Something like:

 name = defer 

then used as:

 result = name()

The expression name() will never have arguments as it's meant to 
reference it's variables as locals and probably will be replaced 
directly with names's byte code contents at compile time.

Defer could be shortened to def I suppose, but I think defer would be 
clearer.  Anyway, it's only a wish list item for now.

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


Re: Thoughts on Guido's ITC audio interview

2005-06-27 Thread Ron Adam
Dave Benjamin wrote:
> Guido gave a good, long interview, available at IT Conversations, as was
> recently announced by Dr. Dobb's Python-URL! The audio clips are available
> here: 
> 
> http://www.itconversations.com/shows/detail545.html
> http://www.itconversations.com/shows/detail559.html


Thanks for the links Dave. :-)

He talked a fair amount on adding type checking to python.  From 
reading his blog on that subject, it seems Guido is leaning towards 
having the types as part of function and method definitions via the 'as' 
and/or '->' operator in function and class argument definitions.

My first thoughts on this was to do it by associating the types to the 
names. Limiting reassignment of a names to specific types would be a 
form of persistent name constraint that would serve as a dynamic type 
system.

Has any form of "name constraints" been discussed or considered 
previously?

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-28 Thread Ron Adam
Mike Meyer wrote:
> Riccardo Galli <[EMAIL PROTECTED]> writes:
> 
> 
>>On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote:
>>
>>
Bo Peng wrote:


>I need to pass a bunch of parameters conditionally. In C/C++, I can
>do func(cond1?a:b,cond2?c:d,.)
>
>Is there an easier way to do this in Python?


>>>The answer is simply no, just use an if statement instead.
>>
>>That's not true.
>>One used form is this:
>>result = cond and value1 or value2
>>
>>which is equal to
>>if cond:
>>   result=value1
>>else:
>>   result=value2
>>
>>
>>another form is:
>>
>>result = [value2,value1][cond]
>>
>>
>>the first form is nice but value1 must _always_ have a true value (so not
>>None,0,'' and so on), but often you can handle this.
> 
> 
> Note that [value2, value1][cond] doesn't do exactly what cond ? value1 : 
> value2
> does either. The array subscript will always evaluate both value2 and
> value1. The ?: form will always evaluate only one of them. So for
> something like:
> 
>   [compute_1000_digits_of_pi(), compute_1000_digits_of_e][cond]
> 
> you'd really rather have:
> 
>   cond ? compute_1000_digits_of_e() : compute_1000_digits_of_pi()
> 
> There are other such hacks, with other gotchas.
> 
>   http://mail.python.org/mailman/listinfo/python-list


Re: Boss wants me to program

2005-06-28 Thread Ron Adam
[EMAIL PROTECTED] wrote:

> Ok, sorry to throw perhaps unrelated stuff in here, but I want everyone
> to know what we have right now in the office. We started with an
> electric typewriter and file cabinets. We were given an old 386 with a
> 20 mb hard drive about 5 years ago, and we moved everything over to a
> very very old version of msworks on msdos 6. Depending on what we are
> given(for reasons best left alone, I won't explain why we can't
> actually COUNT on the actual buying of a new system), we will be left
> with this relic, or be given a 486. Maybe a old pentium 90 or so. I may
> try to convince the boss that I can write dos programs for the existing
> machine. If we get any kind of upgrade, I'm sure it will be able to run
> linux with X and a low overhead window manager. If that happened, I'd
> be able to use python and this "tk" thing you have talked about and
> make something that will work for him, am I correct? The other
> alternative is to install console mode linux on it and hope that the
> ncurses library can be used by python. The system could be as low as a
> 486 dx2 66 with maybe 16 megs of ram. Well, I just thought I'd give you
> people more info on the situation.
> 
> Xeys

Check the yellow pages in your area (or closest large city if you're not 
in one), for used computer stores. Or just start calling all the 
computer stores in your area and ask them if they have any used 
computers for sale.  I was able to get a Dell Pentium 3 for $45 dollars 
last year for a second computer to put Linux on.  I just asked him if he 
had any old computers for really cheep that booted, and that's what he 
found in the back.  I just needed to add ram and a hard drive.

You might be surprised what you can get used if you ask around.

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


Re: Is there something similar to ?: operator (C/C++) in Python?

2005-06-30 Thread Ron Adam
Antoon Pardon wrote:
> Op 2005-06-29, Scott David Daniels schreef <[EMAIL PROTECTED]>:
> 
>>Roy Smith wrote:
>>
>>>Andrew Durdin <[EMAIL PROTECTED]> wrote:
>>>
Corrected version:
   result = [(lambda: expr0), lambda: expr1][bool(cond)]()
>>
>>Sorry, I thought cond was a standard boolean.
>>Better is:
>> result = [(lambda: true_expr), lambda: false_expr][not cond]()
> 
> 
> How about the following:
> 
>   result = (cond and (lambda: true_expr) or (lambda: false_expr))()
> 

That works as long as long as they are expressions, but the ? format 
does seem to be more concise I admit.


To use *any* expressions in a similar way we need to use eval which is a 
lot slower unfortunately.

result = eval(['expr0','expr1'][cond])


A thought occurs to me that putting index's before the list might be an 
interesting option for expressions.

result = expr[expr0,expr1]


This would probably conflict with way too many other things though. 
Maybe this would be better?

result = index from [expr0,expr1]


Where index can be an expression.  That is sort of an inline case 
statement.  Using a dictionary it could be:

result = condition from {True:expr1, False:expr0}


As a case using values as an index:

 case expr from [
expr0,
expr2,
expr3 ]


Or using strings with a dictionary...

 case expr from {
'a':expr0,
'b':expr1,
'c':expr3 }
 else:
expr4

Reads nice, but can't put expressions in a dictionary or list without 
them being evaluated first, and the [] and {} look like block brackets 
which might raise a few complaints.

Can't help thinking of what if's.  ;-)

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-01 Thread Ron Adam
Tom Anderson wrote:

> So, if you're a pythonista who loves map and lambda, and disagrees with 
> Guido, what's your background? Functional or not?

I find map too limiting, so won't miss it.  I'm +0 on removing lambda 
only because I'm unsure that there's always a better alternative.

So what would be a good example of a lambda that couldn't be replaced?

Cheers,
Ron


BTW...  I'm striving to be Pythonic. ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   >