A class question

2007-10-29 Thread Donn Ingle
Hello,

Is there a way I can, for debugging, access the instance variable name from
within a class?
E.g:
Class X: 
 def debug(self):
  print "My instance var is %s" % (some magic Python stuff)

So that:
>>>x = X()
>>>x.debug()
>>>My Instance var is x

( Without passing the name in like: x=X(name="x") ) 

Thx.
\d

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


Re: A class question

2007-10-29 Thread Donn Ingle
bump :)

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


Re: A class question

2007-10-29 Thread Donn Ingle
> vzcbeg vafcrpg
> 
> qrs _svaq(senzr, bow):
> sbe anzr, inyhr va senzr.s_ybpnyf.vgrevgrzf():
> vs inyhr vf bow:
> erghea anzr
> sbe anzr, inyhr va senzr.s_tybonyf.vgrevgrzf():
> vs inyhr vf bow:
> erghea anzr
> envfr XrlReebe("Bowrpg abg sbhaq va senzr tybonyf be ybpnyf")
> 
> pynff K:
> qrs qroht(frys):
> cevag ("Pnyyre fgberf zr va %f (nzbat bgure cbffvoyr cynprf)"
>% _svaq(vafcrpg.pheeragsenzr(1), frys))

Now that's taking i18n too far. Klingon is not a widely understood
language :D


\d

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


Re: A class question

2007-10-29 Thread Donn Ingle
> for humans:
Sweet. Thanks, I'll give it a go. It's only for debugging and will make life
easier.

\d

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


Re: A class question

2007-10-29 Thread Donn Ingle
> While Java's variable declarations bear a superficial (syntactical)
> similarity to C, their semantics is in fact equivalent to the
> object-reference semantics we know in Python. 

I come from Z80A/GWBASIC/VB and a little C, I would describe a Python
variable as a pointer - in that it contains the address of something. 
What that "something" is, is a little fuzzy. Right now I imagine it's to a
kind of structure which has meta info about the object as well as it's
actual address.

How far off would that be?

\d

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


parsing string to a list of objects - help!

2007-11-05 Thread Donn Ingle
Hi, I really hope someone can help me -- I'm stuck.

 I have written three versions of code over a week and still can't get past
this problem, it's blocking my path to getting other code written.

This might be a little hairy, but I'll try to keep it short.

Situation: 
I want to pass a string to a function which will parse it and generate
objects in a list.
Each object is a "property" which keeps members like x,y,r,g,b etc.
Each element in the final list describes a frame in an animation.

I want to be able to pass only the properties of key moments (key frames) in
time to the function. Along with that is passed the *way* each moment
changes into the next.

The form I am using is like this:
t=Thing()
t.propLayout("#---#---#==_##_")
prop1 = Property(x=10,y=10,r=1,g=1,b=1,a=0)
prop2 = Property(x=20,y=10,r=0,g=0,b=1,a=1)
prop3 = Property(x=10,y=100,r=1,g=1,b=1,a=1)
prop4 = Property(x=100,y=200,r=1,g=1,b=1,a=1)
t.setProps(prop1,prop1,prop2,prop3,prop4)

So setProps is the parser and it creates a proplist within t.

My short-hand for this:
# is a property
- is a 'tween' (where the property before it influences it)
= is a property exactly the same as the one before it.
_ (underscore) is a blank frame

Things like this can be expressed:
1234567890123
#---#--#===_#
(4 keyframes, #'s. 13 frames, lifetime.)
In words that would say:
Frame 1, make a property.
Frame 2 to 4 tweening : copy previous property (from 1) and advance the
members by the average (calculated by getting the range between 1 and 5 and
going through each member variable (x,y,z,r,g,b) and dividing etc. This
means looking ahead.)
Frame 5, make a property
Frame 6 to 7 tweening.
Frame 8, make a property
Frame 9 to 11, copy property from 8
Frame 12, make a blank
Frame 13, make a property.

So, the animation will proceed: Start at 1, move/morph to 5, move/morph to
8, remain static to 11, go away for 12 and appear somewhere at 13.

It seems so simple, but I just cannot nail it down. Each time I end up with
a mess of string[index] and if else tests within while loops that seem to
work until I get to a test string that breaks it all.

I'm sure there must be a better way to formalize this little 'language' and
break it down into a list of property objects that exactly describes the
string -- catching user errors too.

The rules:
Tweens : must start and end in # signs: ##
Static : must start with a # : #===
No other chars can be within a range: #==_= is bad. #--=--# is bad.

Odds:
Singles: things like ### are valid. This means each is a frame somewhere,
implying they will jump around (i.e. not be statics)
Blanks : are simple - they are properties for every underscore

I have glanced around at parsing and all the tech-speak confuses the heck
out of me. I am not too smart and would appreciate any help that steers
away from cold theory and simply hits at this problem.

Donn.

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


Re: parsing string to a list of objects - help!

2007-11-05 Thread Donn Ingle
Wow Paul, you have given me much to chew. I'll start testing it in my slow
way -- it looks so simple!

Thank you.
\d

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


Re: parsing string to a list of objects - help!

2007-11-05 Thread Donn Ingle
Paul,
I quickly slapped your example into a py file for a first-glance test and
the first part works, but the second gives me the error below. Could I have
an old version of pyparser? I will dig into it anyway, just being lazy :)

code:
from pyparsing import *

frame = Literal("#")
tween = Word("-") # that is, it is a "word" composed of 1 or more -'s
copy = Literal("=")
blank = Literal("_")

animation = OneOrMore((frame + Optional(
(tween + FollowedBy(frame)) |
OneOrMore(copy | blank) ) ) )

test = "#---#--#===_#"

print animation.parseString(test)

class Prop(object):
def __init__(self,tokens):
pass

class Tween(object):
def __init__(self,tokens):
self.tween = tokens[0]
self.tweenLength = len(self.tween)

class CopyPrevious(object):
def __init__(self,tokens):
pass

class Blank(object):
def __init__(self,tokens):
pass

frame.setParseAction(Prop)
tween.setParseAction(Tween)
copy.setParseAction(CopyPrevious)
blank.setParseAction(Blank)


animation.parseString(test)

result:
containers:$ python parser.py
['#', '---', '#', '--', '#', '=', '=', '=', '_', '#']
Traceback (most recent call last):
  File "parser.py", line 39, in ?
animation.parseString(test)
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 620, in
parseString
loc, tokens = self.parse( instring.expandtabs(), 0 )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 562, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 1768, in
parseImpl
loc, tokens = self.expr.parse( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 562, in parse
loc,tokens = self.parseImpl( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 1390, in
parseImpl
loc, resultlist = self.exprs[0].parse( instring, loc, doActions )
  File "/usr/lib/python2.4/site-packages/pyparsing.py", line 588, in parse
tokens = self.parseAction( instring, tokensStart, retTokens )
TypeError: __init__() takes exactly 2 arguments (4 given)


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


Re: parsing string to a list of objects - help!

2007-11-05 Thread Donn Ingle
Wow Paul, you have given me much to chew. I'll start testing it in my slow
way -- it looks so simple!

Thank you.
\d

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


pyparsing frames and tweens - take 2

2007-11-05 Thread Donn Ingle
Paul,

> frame = Literal("#")
> tween = Word("-") # that is, it is a "word" composed of 1 or more -'s
> copy = Literal("=")
> blank = Literal("_")
> 
> animation = OneOrMore((frame + Optional(
> (tween + FollowedBy(frame)) |
> OneOrMore(copy | blank) ) ) )

I found that this form insists on having a # in char 0. How could it be
changed to take a bunch of blanks before the first frame?
# ?

I have tried:
animation = OneOrMore( 
Optional ( blank | frame ) +
Optional( (tween + FollowedBy(frame) ) |  OneOrMore(copy | blank)  )  
)

And permutations thereof, but it goes into a black hole.

\d

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


Insane crazy question - printing commands

2007-11-06 Thread Donn Ingle
Hi,
I'm doing something odd with pycairo and friends and I want to see what
commands are coming out of my objects.

Here's some code:

class Box:
 def draw()
  self.context.set_source_rgb(1, 0, 0)
  self.context.rectangle(0, 00, 50, 50)
  self.context.fill()

Box.draw() draws a red box, all fine. But, I *also* want it to output the
actual commands within the draw def to the console (or a file).

At the moment I am doing this:
class Box:
 def draw()
  self.context.set_source_rgb(1, 0, 0)
  self.context.rectangle(0, 00, 50, 50)
  self.context.fill()
  print """
  self.context.set_source_rgb(1, 0, 0)
  self.context.rectangle(0, 00, 50, 50)
  self.context.fill()
  """
Do you see the form? Is there some  python introspection way I
can perform that automagically without having to use the print statement?

Something like:
class Box:
 def draw()
  self.context.set_source_rgb(1, 0, 0)
  self.context.rectangle(0, 00, 50, 50)
  self.context.fill()
 def dump():
  

See, I told you it was insane :)

\d


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


Re: Insane crazy question - printing commands

2007-11-06 Thread Donn Ingle
Thanks for the replies -- Python, is there anything it can't do? :D

\d

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


pyparsing and svg

2007-11-08 Thread Donn Ingle
Hi - I have been trying, but I need some help:
Here's my test code to parse an SVG path element, can anyone steer me right?

d1="""
M 209.12237 , 172.2415
 L 286.76739 , 153.51369
 L 286.76739 , 275.88534
 L 209.12237 , 294.45058
 L 209.12237 , 172.2415
 z """

#Try it with no enters
d1="""M 209.12237,172.2415 L 286.76739,153.51369 L 286.76739,275.88534 L
209.12237,294.45058 L 209.12237,172.2415 z """

#Try it with no spaces
d1="""M209.12237,172.2415L286.76739,153.51369L286.76739,275.88534L209.12237,294.45058L209.12237,172.2415z"""

#For later, has more commands 
d2="""
M 269.78326 , 381.27104
C 368.52151 , 424.27023 
 90.593578 , -18.581883
 90.027729 , 129.28708
C 89.461878 , 277.15604
 171.04501 , 338.27184
 269.78326 , 381.27104
 z """
 
## word   :: M, L, C, Z
## number :: group of numbers
## dot :: "."
## comma   :: ","
## couple :: number dot number comma number dot number
## command :: word
## 
## phrase :: command couple

from pyparsing import Word, Literal, alphas, nums, Optional, OneOrMore

command = Word("MLCZ")
comma = Literal(",")
dot = Literal(".")
float = nums + dot + nums
couple = float + comma + float

phrase = OneOrMore(command + OneOrMore(couple |  ( couple + couple ) ) )

print phrase

print phrase.parseString(d1.upper())

Thanks
\d

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


Re: easy 3D graphics for rendering geometry?

2007-11-08 Thread Donn Ingle
> I recommend taking a look at Blender 3D: http://www.blender.org/

Oh yeah, Blender is THE way to go. It's fantastic.

\d

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


Global variables within classes.

2007-11-09 Thread Donn Ingle
Hi,
I'm getting myself really confused. I have three classes. Two of them need
to reference the third, like so:

Canvas ---> Stack <--- Thing

I am doing this right now:

s = Stack()

And then within  I am referring directly to the global
variable 's' (and again from Thing).

Now, this works, but it bugs me somewhat. I don't want to limit a user to
having to declare a global variable of a particular name.
They should be able to say 

This may also leads to more confusion because the user can also make Things
directly  and I want the new things to all reference the
*same* Stack. (Right now it works because I reference 's' within Thing.)

I thought this might be a case for multiple inheritance but I just keep
getting recursion errors as one thing refers to another in a big mess.

Does that makes sense?

\d

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


Re: Global variables within classes.

2007-11-09 Thread Donn Ingle
>> I thought this might be a case for multiple inheritance
> ???
Well, in terms of having Canvas and Thing inherit from Stack and thereby
(somehow, not sure how) they would both have access to Stack.stack (a list)
 
> wrt/ all Thing instances having to refer to a same Stack instance,
> there's a pretty obvious answer: make the Stack instance an attribute of
> class Thing, ie:
> class Thing(object):
>stack = Stack()
> 
>def some_method(self, val):
>   self.stack.push(val)
># etc...

No can do:
Canvas ---> Stack <--- Thing
Both Canvas and Thing have to use the same Stack. It gets things pushed onto
it by them both.

> Now the point that isn't clear is the exact relationship between Stack
> and Canvas. You didn't give enough details for any answer, advice or
> hint to make sens.
Sorry, didn't want to write an overly long post.

a Canvas holds many Things (graphics) and it pushes each Thing onto the
Stack. The Things also push data onto the same Stack. After that the Stack
pops and draws each Thing to the screen.

What I'm asking about is subtle and I don't know how to word it: how can
Classes share common objects without using global variables specifically
named within them?


## == API in another module perhaps ===
Class Stack:
 def push(self,stuff):
  pass

Class Canvas:
 def do(self):
  s.push("data") #I don't feel right about 's' here.

Class Thing:
 def buzz(self):
  print s.pop(0)

## == User space code area ===
s = Stack() #I want to avoid this direct naming to 's'
c = Canvas()
c.push("bozo")
t = Thing()
t.buzz()

Hope that makes more sense.
\d


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


Re: Global variables within classes.

2007-11-09 Thread Donn Ingle
> I guess you mean "instances", not "classes".
Yes.
 
> Err...Perhaps a dumb question, but what about passing the "common
> objects" to initializers ?
> s = Stack()
> c = Canvas(s)
> t = Thing(s)

Okay, I see where you're going. It's better than what I have at the moment.
Thanks.

\d


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


Re: Global variables within classes.

2007-11-10 Thread Donn Ingle
Very interesting reply. I must ask a few questions, interleaved:

> If you mean that all instances of Class Canvas and Thing will share
> the *same* Stack, I think we can do it kind of like this:
What's the difference between "same Stack" and "same instance of Stack"? I
thought I knew what an instance was, but this code has made me doubt my
basics.

> class Stack:
> list = []
Okay, this has me a little weirded-out. How is this different from putting
it in: 
def __init__(self):
self.list = []
?
I see from tests that it is different, but I don't quite grok it. Who owns
the list ref?

> def pop(self):
> item = self.list[-1]
> del self.list[-1]
> return item
Is there some reason you do all that and not a self.list.pop(0)?
 
> class Canvas:
> def __init__(self):
> self.s = Stack()
Surely this makes a unique instance within Canvas such that it's a new
Stack?

> class Thing:
> def __init__(self):
> self.s = Stack()
Same question again -- my brain is telling me this is *another* Stack and
not the same one that it's in Canvas at all.

It looks like it could work for me, but I gotta get it in my head first :)

 
> or: if you want a pair of instances of class Canvas and class Thing
> share
> the *same* instance of class Stack, maybe we can make it like this:
> c = Canvas()
> c.push("bozo")
> t = Thing(c.getStack())   #associate t with c
> t.buzz()
This one I understand better because it does not imply anything - it's
easier to follow and it's where my head is at with Python, but your first
example is a whole new world.

Thanks for the post!
\d

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


Re: Global variables within classes.

2007-11-10 Thread Donn Ingle
> The first creates an attribute of the class, the second creates an
> attribute in the instance.

Given that, can you clarify this:

class Test:
attribute = "original value"

class Bob:
def __init__(self):
self.ref = Test()

class Jim:
def __init__(self):
self.ref = Test()

b = Bob()
j = Jim()

print b.ref.attribute #prints "original value"

b.ref.attribute = "haschanged"
## Where is the value "haschanged" going here?
print b.ref.attribute # print "haschanged"

print j.ref.attribute #prints "original value"
## If it changed and an attribute of the Class, then
## why is it back to "original value" ?

> Actually the lookup is somewhat more complex than that when you use new-
> style classes (and you should always use new-style classes): properties
> (or other objects with a 'get' method) are class attributes but take
> precedence over instance attributes.
What is a 'get' method? Do you mean it should get all Java-esque with
getBlah and setBlah for every little thing?

I have been hearing about "new classes" for a while but there's no clarity
in the Python docs (that I can find). Have you any references for me? I
thought they were the standard by now anyway. I've only been pythoning
since 2.3 anyway.


\d

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


Re: Global variables within classes.

2007-11-10 Thread Donn Ingle
Included again for clarity:
>> class Test:
>> attribute = "original value"
>> 
>> class Bob:
>> def __init__(self):
>> self.ref = Test()
>> 
>> class Jim:
>> def __init__(self):
>> self.ref = Test()
>> 
>> b = Bob()
>> j = Jim()
>> 
>> print b.ref.attribute #prints "original value"
>> b.ref.attribute = "haschanged"
>> ## Where is the value "haschanged" going here?
> 
> To *instance* of `Test` you created and bound to `b.ref`.
> 
I don't follow you here. I *think* you are saying I created a *new* (on the
fly) ref within b that is also called 'attrib', so that it's kind of
shadowing the original 'attribute' ref (the so-called class attribute.)
?

>> print b.ref.attribute # print "haschanged"
>> 
>> print j.ref.attribute #prints "original value"
>> ## If it changed and an attribute of the Class, then
>> ## why is it back to "original value" ?
> 
> Because the *instance* of `Test` bound to `j.ref` does not have
> `attribute` it is looked up in the *class* `Test`.
Okay, I sort of see that. It's not a property of 'j' so it looks upwards
into the class. 
This is kind of weird. It's not clear like Python usually is. Is this
something intentional or did it 'fall through the cracks'? I mean, can one
rely on it or will it be 'fixed'?
 
> Good $GOD no!  
:D

> He's talking about the `__get__` method on properties. Read 
> the docs for the built in `property()` function.  
Okay, I'll go have a look.

Thx
\d


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


Re: Global variables within classes.

2007-11-10 Thread Donn Ingle
Thanks for your time and patience Marc, that was some hotshot ascii art.
I'll have to take some time to digest this.

\d

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


Override method name and original method access

2007-11-12 Thread Donn Ingle
In an unusual twist of code I have a subclass which overrides a method but
it also needs to call the original method:

class One:
 def add (self, stuff):
  self.stuff.append(stuff)

class Two(One):
 def __init__(self, otherstuff):
  (otherstuff) #otherstuff must go into list within the parent.
 #The override - totally different function in this context.
 def add (self, data):
  self.unrelated.append (data)

For:

I have tried:
 self.One.add( otherstuff ) 
No go.
 super ( Two, self).add( otherstuff ) 
Gives this error:TypeError: super() argument 1 must be type, not classobj
(Which reminds me, how the heck does super work? I always get that error!)

I could just change the method name to adddata() or something. I could pass
parent references around, but want to avoid that. 

I thought I'd ask about it here.

\d



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


Re: Override method name and original method access

2007-11-12 Thread Donn Ingle
> You need to be a new-style class (that is, you must inherit from
> object) for super() to work. 
Problem is that my classes inherit already, from others I wrote. So, should
I explicitly put (object) into the ones at the top?

> Other than that, you are using it 
> correctly here.
Well, even with  it seems to be calling to local overridden
method. In a bit of a hurry, so can't test again right now.


/d

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


Re: Override method name and original method access

2007-11-13 Thread Donn Ingle
> One.add(self, otherstuff)
Ah! Thanks - that makes more sense. Much appreciated.

/d

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


Re: Override method name and original method access

2007-11-13 Thread Donn Ingle
Chris Mellon wrote:
>  The use of super()
> (and new style classes) should be the default implementation,

To get some clarity on this subject, how do I make sure my classes
are "new"? I've got the idea that my hierarchy must start from a base-class
that explicitly derives from Object  and not .
I'm using GTK and one of them is  how do I
make sure Canvas is "new"?

It's fuzzy. And I have read the docs but they're fuzzy too :)

/d

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


Looking for docs

2007-11-16 Thread Donn Ingle
Hi,
I have seen strange looking things in various Python code like:
staticmethod and also lines starting with an @ sign, just before method
defs - I can't find an example right now.
 I have Python 2.5 installed with it's docs, but I can't find any discussion
of 'new style' classes and other info.

I'm not even sure what subject that @ sign stuff falls under.

Anyone have a link?

/d

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


Re: overriding methods - two questions

2007-11-16 Thread Donn Ingle
> for child in self.childrens:
> if 'foo' in child.__class__.__dict__:
> child.foo()
Bruno, you're the man! I really must take the time to look into all those
under-under score things! 

Thanks.

/d

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


overriding methods - two questions

2007-11-16 Thread Donn Ingle
Hi,
Here's a framework for the questions:

--- In a module, part of an API ---
class Basis ( object ):
 def foo ( self, arg ):
  pass

--- In user's own code ---
class Child ( Basis ):
 def foo ( self, not, sure ):
  ...


Question 1:

Given that the user of the API can choose to override foo() or not, how can
I control the signature that they use? In the example the user has chosen
bad arguments and Python will complain, but it's describing the sig of the
*overridden* method and not the one in the parent class.

 Is there some way I can control the error message to make it clear to the
user that they are using the signature of foo() incorrectly?

Question 2:

Say I am in class Basis, doing a loop and I have a list of Child objects. I
want to run the foo() method for each one that *has* a foo() method. i.e.
user has done this:

class Sam ( Child ):
 ...
*Sam does not define foo()

class Judy ( Child ):
 def foo ( self, arg ):
  ...
* Judy does define foo()

Instances of Sam and Judy have been put into the list (within the instance)
of Basis. I want Basis to detect that Judy has foo() and run it.

I can handle question 2 by using a flag that must be set by the user.
Something like:
class Judy ( child ):
 def __init__( self ):
  self.pleaseCallFoo = true

And now, Basis can check for that var and only then call foo(), but this is
ugly and means more for the user to learn API-wise.

Any ideas?
/d


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


Re: overriding methods - two questions

2007-11-16 Thread Donn Ingle
>This may help (on an old Python version):
 class Sam: pass
 class Judy:
> ...def foo(self): pass
> ...
 children = [Sam(), Judy(), Sam()]
 for child in children: hasattr(child, "foo")
> ...
> False
> True
> False

That's not what my tests are showing. While Sam has no foo, it's coming from
(in my OP) Child (which is the parent class), so hasattr(Sam(),"foo") is
returning True.

/d

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


Re: overriding methods - two questions

2007-11-16 Thread Donn Ingle
> Actually, Python is complaining about your user's poor choice of
> argument names. 'not' is a reserved keyword.  
My example was poor, but my actual test code did't use 'not'. Python simply
checks the use of foo() to the local sig of foo() and does not go up the
chain. This is understandable and your next answer is more-or-less what I
was expecting.

> Python's philosophy of "you are the human, so you must know what you
> are doing" (which is both an assumption and a directive), I don't
> think you will find much language machinery to prevent it.

Yeah. I guess I was hoping there'd be some clever trick to do it.

/d

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


Re: overriding methods - two questions

2007-11-16 Thread Donn Ingle
>> While technically possible (using inspect.getargspec), trying to make
>> your code idiot-proof is a lost fight and a pure waste of time.
 
> Worse: it's actually counter-productive!
> The whole idea of being able to subclass a class means that the user
> should be able to override foo() *including* the signature.
Steven,
 In this case, the def in question is named Draw. It's args are context and
framenumber. The body is 'pass'. I want users to use the exact signature
(but they can change the varnames to suit) because the draw() method is
*not* being called by the user but *by* my API (in a timeout loop). 

 So, my API is sending blah.Draw( cairo.context, currentFrame ) *to* the
user's own object.Draw.Thereafter, whatever Cairo drawing commands they use
in their override of Draw() is what gets drawn -- if that makes sense :)

I guess that's the long way of saying it's a call-back function :)

So, I'm trying to guarantee that they don't mess with it to make life easier
for them. As Bruno has mentioned, this is up to the human and so it'll be a
rule in the docs instead.

/d

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


Re: Global variables within classes.

2007-11-16 Thread Donn Ingle
Very interesting reply. I must ask a few questions, interleaved:

> If you mean that all instances of Class Canvas and Thing will share
> the *same* Stack, I think we can do it kind of like this:
What's the difference between "same Stack" and "same instance of Stack"? I
thought I knew what an instance was, but this code has made me doubt my
basics.

> class Stack:
> list = []
Okay, this has me a little weirded-out. How is this different from putting
it in: 
def __init__(self):
self.list = []
?
I see from tests that it is different, but I don't quite grok it. Who owns
the list ref?

> def pop(self):
> item = self.list[-1]
> del self.list[-1]
> return item
Is there some reason you do all that and not a self.list.pop(0)?
 
> class Canvas:
> def __init__(self):
> self.s = Stack()
Surely this makes a unique instance within Canvas such that it's a new
Stack?

> class Thing:
> def __init__(self):
> self.s = Stack()
Same question again -- my brain is telling me this is *another* Stack and
not the same one that it's in Canvas at all.

It looks like it could work for me, but I gotta get it in my head first :)

 
> or: if you want a pair of instances of class Canvas and class Thing
> share
> the *same* instance of class Stack, maybe we can make it like this:
> c = Canvas()
> c.push("bozo")
> t = Thing(c.getStack())   #associate t with c
> t.buzz()
This one I understand better because it does not imply anything - it's
easier to follow and it's where my head is at with Python, but your first
example is a whole new world.

Thanks for the post!
\d

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


Re: overriding methods - two questions

2007-11-16 Thread Donn Ingle
> I am curious as to why you want to go through such contortions.  What
> do you gain. 
for obj in list:
 if obj has a foo() method: 
  a = something
  b = figureitout ( )
  object.foo ( a, b )

I am accepting objects of any class on a stack. Depending on their nature I
want to call certain methods within them. They can provide these methods or
not. 

> What happens, for example, if a subclass of Judy is 
> passed in that does not override foo?  Should foo be called in that
> case or not?
No.

Bruno has given me a good solution:

for obj in list:
 if 'foo' in obj.__class__.__dict__:
  etc.

Although I am concerned that it's a loop ('in') and so may be slower than
some other way to detect foo().

So, that's the story.

/d

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

Re: overriding methods - two questions

2007-11-17 Thread Donn Ingle
> This is strictly a documentation matter, in my mind. Python does not
> offer any means to enforce the calling sequence of an "override method".
Yes, I hear you.
 
> You might be able to wrap YOUR calling code with a try/except block
> to trap errors if the callback doesn't like the "documented API"
> arguments.
Good plan. Thanks, dunno why I didn't think of that!

/d

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


Re: overriding methods - two questions

2007-11-17 Thread Donn Ingle
> *not* being called by the user but *by* my API (in a timeout loop).
> 
> You don't know that. How can you possibly guarantee that the user won't
> find some other use for the draw() method 
Well, as per your good examples, I would answer that as the parameters
passed to draw() grow in number, so the API is actually growing and so the
draw() call will be updated. Or, other calls can be introduced like
drawPreview() etc. (Better cos it won't break old code.)

The way it is now, in heavy alpha :), is that the draw() is *only* called
outwards and does not return or call parentClass.draw( self, ...) back in
any way. It's a pure source of context.cairo_ commands.

> BTW, it is a convention for method names to be lower case, and classes to
> be Title case. Seeing something like obj.Draw, most(?) Python developers
> will expect that the Draw attribute of obj is itself a class:
Thanks, I'm pretty damn unorganized in that way. Is it convention to do:

class BigLetterAndCamels():
 def smallLetterAndCamels()

or
 def smallletterandnocamels()

?

/d

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


Re: overriding methods - two questions

2007-11-17 Thread Donn Ingle
Thanks, good tips all-round. I have it working okay at the moment with all
the suggestions. It may break in future, but that's another day :)


/d

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


Re: Python too complex ?!?!?!

2007-11-17 Thread Donn Ingle
I dunno about your dog :) but Python libs are not too demanding. From a
Gnu/Linux pov with package managers things are quite simple.

My wish is to find a way to make that even easier because the packaged
modules are not always up to date. 

If the Cheese Shop could supply downloads of modules and we could stick on a
gui interface that wraps around import statements to guide the installation
of any missing packages -- that would be progress.

If you are online and the app runs, it can check the "freshness" of your
modules (those called from the app and recursively) and offer to fetch the
latest stable versions.

The gui is an issue. Does one TK or rely on some fall-back system of
gnome/kde/x11/windows dialogue boxes (ending in abject failure by way of
raw_input on the command line)? Or (perhaps) have it fetch a standard
dialogue library which would fetch and install what is needed for future
occasions.

Anyway, this is a bit of a hijack and I have not touched C# in any way, but
I don't think Python has anything to be ashamed of.*

/d

* Okay, maybe decorators but that's just because I am far too thick to grok
them :D


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


Re: python debugging...

2007-11-17 Thread Donn Ingle
I don't know if this will help you, but if you can, install "Eric". It's an
IDE that I often use and you can do point and click debugging with
breakpoints and nice displays of all vars and whatnot as you go. Much
easier than fiddling with the debugger manually.


/d

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


Re: which Python ? asks beginner

2007-11-17 Thread Donn Ingle
> plans are afoot
You know, I've always wanted ask; if plans are afoot, what are hands?

:D

Sorry, it's late.

/d

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


Re: Python too complex ?!?!?!

2007-11-17 Thread Donn Ingle
> Interesting idea, although it's not something I'd want included and
> turned on by default.  Should certainly be possible, though, with a
> little __import__ magic.
Well, since we're shooting the sh*t :), I tried in my one and only released
app (Fonty Python) to wrap the imports in try clauses and then print
helpful strings to the console to guide the user. 
 I'm really not too clued-up on the __deep__ magic of Python, so I can't say
what tricks there are, but a simple "catch a fail and then start a
solution" process is a general approach.
 
>> If you are online and the app runs, it can check the "freshness" of your
>> modules (those called from the app and recursively) and offer to fetch
>> the latest stable versions.
> Something similar to Java's webstart?  Implement an __import__ hook
> that downloads and caches the latest (stable) versions of libraries as
> needed.
I have also never touched Java, so I can't say, but something like that. 
 The main problem with having modules coming from the web is time. How long
is the life of a URL? The Cheese Shop seems pretty well established and
could serve the role. Perhaps there are already ways of making sure that a
hard-coded link in an app can reach a variable URL online.
 
> You wouldn't really *need* a GUI, although it probably should be a
> configurable option ... 
I'd agree, but then I grew up with commands lines. I can say with total
confidence that the command-line scares a lot of people and if there are
any questions that need answering during the automated process (and there's
always *something* that crops up ) then a gui is the natural way to reach
the user.

> No reason why it couldn't be totally
> automated.  easy_install already provides for automated installation
> of python apps/libraries, so you could build off that.
Totally automated would be the goal. I'd say a throbber or progress
animation of some kind would be needed. 

 Just thought of a wrinkle - say a new module is available and is installed
and then proves to be broken. How can the app recover? There'd have to be a
system of flags in a db that mark the situation and on re-run can roll back
to the last working module. Then we get feedback to the author of the
module 

And let's not forget all the joy that can be spread by having to compile
modules (on various platforms) from C/C++ and then worry about *their*
dependant libraries!

Oh fun times :p

(I think I can see why this has never been approached.)

> Merely using decorators is, IMHO, much easier
> to understand (but still requires a slight brain-warp).  
I'm still stuck with those things. I can't really find an example that I
want to use. My brain keeps saying "yeah, but that's so smoke and mirrors
and I could do it this way ... which seems much plainer."

> I think some 
> people try to understand decorators too completely too quickly, and
> end up labeling them one of those complex/unintuitive/"way out"
> things.
I have put them in the bag along with Design Patterns and Threads as "things
that I don't have to worry about because liff is too short. And like the
Spanish Inquisition, they're welcome to surprise me when I least expect it,
but I'm not going to lose my mind waiting :D

/d

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


Re: which Python ? asks beginner

2007-11-18 Thread Donn Ingle
>> You know, I've always wanted ask; if plans are afoot, what are hands?
> The answer, seeing as it's late, is that whisky is at hand.
Ha. Brilliant answer! It also explains decorators :D


/d

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


Re: Function stopping a function

2007-11-22 Thread Donn Ingle
> For instance, lenghty_function() executes, when an
> external event triggers cancel(), which is supposed to
> abruptly stop lengthy_function(), reset some variables
> and exit immediately.
I would set a variable someplace (perhaps globally) that gets tested in
lengthy_function()'s loop and issues a break.

If it's threaded then colour me clueless.

\d

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


Catching a segfault in a Python library

2007-11-23 Thread Donn Ingle
Yo,
An app of mine relies on PIL. When PIL hits a certain problem font (for
unknown reasons as of now) it tends to segfault and no amount of try/except
will keep my wxPython app alive.

 My first thought is to start the app from a bash script that will check the
return value of my wxPython app and could then launch a new app to help the
user grok what happened and fix it.

 Do you think that's a good idea, or is there another way to handle stuff
like this? (perhaps a Python app launching another Python app?)

/d

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


Re: Catching a segfault in a Python library

2007-11-23 Thread Donn Ingle
> Run your app under a debugger and figure out what is making it crash.
Already done, the code within PIL is causing the crash. It gets ugly and out
of my remit. It's a freetype/Pil thing and I simply want to a way to catch
it when it happens.
 Since a segfault ends the process, I am asking about "wrappers" around code
to catch a segfault.

\d

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


Re: Is there pointer * in Python?

2007-11-23 Thread Donn Ingle
> think inside Python...
Assuming you *can* think while being slowly crushed and digested :D

\d

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


Re: Catching a segfault in a Python library

2007-11-23 Thread Donn Ingle
> Well I think you should actually debug it, or at least reproduce it
> and send a bug report to the PIL folks,
It was a while ago, and if memory serves I did that, but memory fails.

> but anyway you can use 
> os.wait() to get the exit status and recognize the seg fault.
Okay, that's a good start. Thanks, I'll go for a python starts wxpython
thing with os.wait() to sniff the outcome.


\d

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


Re: Catching a segfault in a Python library

2007-11-23 Thread Donn Ingle
> You may have to roll your own fork/exec to start the wxpython, instead
> of using popen or the subprocess module.  I'm not terribly conversant
> in those modules but they may start a shell which would isolate your
> program from the wxpython exit code.
Hrmm... Neither am I, that's why I asked here :) But I'll skin that Python
when I get to it.

Thanks.
\d

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

Re: Catching a segfault in a Python library

2007-11-24 Thread Donn Ingle
> I think the idea is, certain fonts in his collection may be corrupt,
> and he wants to just scan through and load them, ignoring the ones
> that make the program crash.  
Ya got me! Sheesh, I can't hide anywhere :D

> The bug in this case lies with a third 
> party and isn't something he can easily fix (although he can file
> reports to the third party (PIL)).
I've a bad memory and can't recall what I told PIL at the time. It might
have been a case of waiting to see what new versions can do.

> not nice for the application to just crash when that happens, asking
> them if they want to debug it.  
Zigactly! You can wrap try/except around the calls that (by debugging) you
know are the culprits, but a segfault is a segfault and bam! you are at the
command line again.

> I haven't really found a solution, 
> just have tried to prevent corrupted files in the system for now.  Let
> me know if you get this solved
I'll certainly pop a note. I think, though, that the answer may reside in
the basic theme of this thread:

runapp
 result = runActualApp( )
 while True:
  if result == allokay: break
  else: 
   

Unless a segfault goes through that too, like Krypton through Superman.
\d

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

Re: Catching a segfault in a Python library

2007-11-24 Thread Donn Ingle
Paul Rubin wrote:
> then maybe your trap-and-restart approach can keep things usable for a
> while.
Trap and restart gracefully is the road I want to take. If my app (FP)
chokes on a font (it will have made a note before doing what kills it,
because I know the 'danger' areas ) and then will die. The second layer
(launcher) app will then (hopefully) be returned to (after the segfault)
and it will then check the "badfont" file and start a wizard for the user
so that the fonts can be renamed/moved/killed.

This is mainly because I lack the skills to hack deeply into complex stuff
like PIL, even though a lot of it is Python, and also because the goals
keep changing as new versions of libs like PIL and Freetype come out. I'd
rather have a parachute than a scalpel :)

\d

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


Re: Catching a segfault in a Python library

2007-11-24 Thread Donn Ingle
MrJean1 wrote:
> Try catching SIGSEGV using the Python signal module
> 
> An example (for SIGALRM) is on the next page
> 
> However, it may not work since a SIGSEGV fault is pretty much the end
> of everything
Thanks for the lead -- I'll go have a look. 

If I can just write a "BLOODYHELL" flag to a text file and then let it all
crash, the next time the app is run, it can go into "Dude, we have
issues..." mode.


\d

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


basic if stuff- testing ranges

2007-11-25 Thread Donn Ingle
Sheesh, I've been going spare trying to find how to do this short-hand:
if 0 > x < 20: print "within"

So that x must be > 0 and < 20.

I usually do:
if x > 0 and x < 20: print "within"

What's the rule? Does it even exist?
I read something like it recently on the list but can't find it, that's
where I got the urge to try it from. I can't find anything in the docs, but
then again (imho) the Python docs are like a tangled jungle...


\d

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


Re: basic if stuff- testing ranges

2007-11-25 Thread Donn Ingle
> you mean : 0 < x < 20 ?
Yes. I had gotten the impression that there was some Python form of:
if NUMBER test VAR test NUMBER:

Part of the question was to discover if I was smoking my socks :)

> x in range(1,20) ?
Sure, that's okay, but it has clarity issues, and is calling a func.

>> but then again (imho) the Python docs are like a tangled jungle...
> 
Well, I said it was MHO and if it was easier (for me) to find answers in the
docs I'd have an easier time of it. 

\d

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


Re: basic if stuff- testing ranges

2007-11-25 Thread Donn Ingle
Mel wrote:
> if 0 < x < 20:
> ?
I take it I was tripping then. That's okay, it seemed a little too weird
anyway :)

\d

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


Re: basic if stuff- testing ranges

2007-11-25 Thread Donn Ingle
> 
> if 0 > x: print "within"
> 
Ah, I didn't know you could one could use the sarcasm.xml module and then
use tags to influence Python commands. Most interesting...

import sarcasm.xml

I.fartIn( Your.Direction( general ) )


:D

\d

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


Re: basic if stuff- testing ranges

2007-11-25 Thread Donn Ingle
>> if 0 > x < 20: print "within"
> That means "if x LESS THAN 0 and x < 20".
Oh, bugger. It's tricky. 
> So try
> if 0 < x < 20:
Thanks. I was flipping signs in my tests, but I guess I flipped both and got
myself all confused.
 
> Likely manuals: Tutorial & Reference
> Tutorial: check contents, "if statement" looks possible, but no luck
Yes, I got that far.
> Reference: check contents, "comparisons" looks possible, and
Thanks again. I find the reference is laid-out in a way that I don't find
intuitive and every time I look for something I fail. I even grep through
the folder to get a clue, which shows how poor the index is (to me)!
 
Many thanks for the help!
\d

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


Re: basic if stuff- testing ranges

2007-11-26 Thread Donn Ingle
> The output of the following program might help:
Hey, nifty! Thanks Paddy.

\d

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
Well, I don't know all the answers, but you can start here:

def boobs(): print "Oohh little birds!"
b="boobs"
>>>eval(b)()
Ohhh little birds!

Naturally, eval is going to run anything... Even code to format your drive.

HTH
\d

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


Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
> I see someone already showed you eval.  Eval is evil.  Don't use it. 
> Especially if the functions are coming to you from a public URL!
Yes, I suggested to him (by email) this:

thisinstance =  SomeObject.__class__.__dict__

for f in yourlist:
 if f in thisinstance: eval(f)(params)

Which would vet the functions too.


\d

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

Re: Need to call functions/class_methods etc using string ref :How

2007-11-26 Thread Donn Ingle
> target = 
> for funcname in funclist:
> func = getattr(target, funcname, None)
> if callable(func):
> func(*args, **kwargs)
Nice. 'callable' is new to me. Live and learn :)

\d

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


Re: Gnu/Linux dialogue boxes in python

2007-11-30 Thread Donn Ingle
Paul Boddie wrote:
> I didn't proceed any
> further than a simple wrapping around KDialog, Zenity and Xdialog,
> since the aim is to cover more than the usual UNIX-like platforms.
> However, I could make that code available separately
Thanks for the feedback and the links. I'd like to use your code (if you
don't mind! ) if it's GPL or something similar -- it may save me time.

Anyone know if zenity can be reliably assumed to be installed on a typical
Gnome desktop?

\d

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


Re: Gnu/Linux dialogue boxes in python

2007-11-30 Thread Donn Ingle
> [1] http://www.python.org/pypi/desktop
Oh, just saw this link and fetched the code -- will have a look around.

\d

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


Gnu/Linux dialogue boxes in python

2007-11-30 Thread Donn Ingle
Hi,
 Okay, so I am in the mood to try this: Inform the user about what modules
the app requires in a graphical dialogue that can vary depending on what
the system already has installed. (It will fail-to output on cli)

I am running Kubuntu and I seem to have 'kdialog' installed by default (not
sure if it came as stock.)

What other 'stock' systems are there out there in the wild? Ubuntu? Suse?
Fedora? Others?

I would take a stab at wrapping them in python so that I can use the first
dialogue system found to popup messages for the user.

(Hoping, natch, that this has already been done ... ? )

\d

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


Re: Gnu/Linux dialogue boxes in python

2007-12-01 Thread Donn Ingle
Paul Boddie wrote:
> but I'll
> either upload a new release, or I'll make the code available
> separately.

Thanks, give me a shout when you do -- if you remember!

\d

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


i18n a Python app

2007-12-02 Thread Donn Ingle
Hi,
 I have been going spare looking for a tutorial or howto from my pov as a
total beginner to i18n.
 I understand that one must use gettext, but there seems to be no good info
about *how* one uses it.
 What command line utilities does one use to:
1. make a .pot file
2. make a .mo file
 Are there specific Python aspects to the above, or is it all pure Gnu
gettext?

 The docs are not a tutorial and simply list bare functions which does not
provide any insight. I was hoping there'd be some good links or experience
on the list.

\d

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


Re: i18n a Python app

2007-12-02 Thread Donn Ingle
Another thought, how would one provide translations for doc strings?

class Boo:
 """This class goes Boo!"""

Can one do this, which does not seem likely:
class Boo:
 _( "This class goes Boo!" )


\d

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


Re: Gnu/Linux dialogue boxes in python

2007-12-02 Thread Donn Ingle
> But why?  Either
> 
> (a) your program has a GUI and can display a dialogue box by itself
> (b) your program has a GUI but has problems opening even a tiny part
> of it (missing modules?), and should output diagnostics on the terminal
> (c) your program is console-based, or a daemon or something, and should
> not require a GUI to work.
> 
I realise those things, and it's the simplest case. 

 I was thinking of  allow a setup.py file to
be double-clicked and have the install start to run. When it comes to the
bit where all the import statements happen, it can popup a stock dialogue
informing the user about what they need to install first.

I was hoping to get a list of the most common, distro-installed scriptable
dialogues. Perhaps I should even look at TK -- I understand it comes
standard with Python?

 Another thing to realize, and I have experienced this first-hand, is that a
bunch of text, no matter how nicely formatted, spewed out of an app in
white on black ( the usual terminal colours ) does *not* invite a user's
attention. To read it is a chore and they usually panic.

\d

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

String formatting with %s

2007-12-02 Thread Donn Ingle
Hi,
 I'm sure I one read somewhere that there is a simple way to set the order
of replacements withing a string *without* using a dictionary.

What I mean is:
>>> s = "%s and %s" % ( "A", "B" )
>>> print s
A and B

Now, is there something quick like:
>>> s = "%s/2 and %s/1" % ( "A", "B" )
>>> print s
B and A

?

I know it can be done with a dict:
d = { "one" : "A", "two" : "B"  }
s = "%(two)s and %(one)s" % d


\d

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


Re: String formatting with %s

2007-12-02 Thread Donn Ingle
> but not Python, AFAIK
Damn!

\d

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


pprinting objects

2007-12-08 Thread Donn Ingle
Hi,
 Is there a way to get a dump of the insides of an object? I thought pprint
would do it. If I had a class like this:

class t:
 def __init__(self):
  self.x=1
  self.y=2
  self.obj = SomeOtherObj()

Then it could display it as:

 t,
 x,1,
 y,2,
 obj,

Or something like that -- a complete output of the object really, with
id()'s and so forth.


\d

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


Re: pprinting objects

2007-12-08 Thread Donn Ingle

> AFAIK you have to roll your own. Here is a very rudimentary example:
Very cool, thanks.

\d


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


setattr getattr confusion

2007-12-08 Thread Donn Ingle
Hi,
 Here's some code, it's broken:


class Key( object ):
def __init__(self):
self.props = KeyProps()
def __getattr__(self, v):
return getattr( self.props,v )
def __setattr__(self,var,val):
object.__setattr__(self.props,var,val)

class KeyProps(object):
def __init__(self):
self.x="NOT SET YET"
k1=Key()

It does not run because of the recursion that happens, but I don't know how
to lay this out.

I am trying to set the x value within props within Key:
k1.x="DAMN"
print k1.x

It seems to work, but it's really making a new 'x' in k1.
print k1.props.x
Shows "NOT SET YET", thus proving it failed to set x here.

I want to change k1.props.x by k1.x="something new" -- can this be done?

\d

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


Re: setattr getattr confusion

2007-12-08 Thread Donn Ingle
> So you might want to describe your use-case.
Um.. I wanted an object with Key to hold other data. I wanted a way to set
that *other* data within Key without having to specify the "object
in-between" everytime.

k1.x = "ni!"

should perform:
k1.props.x = "ni!"

and
print k1.x
should perform:
print k1.props.x


I'll go look at your link. Thanks.

\d   


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


Re: pprinting objects

2007-12-08 Thread Donn Ingle
> Define a __repr__ or __str__ method for the class
Yes, then I could include the code John Machin suggested in there:

for attr, value in sorted(self.__dict__.iteritems()): blah

That will do nicely. Thanks all.

\d


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


callback confusion

2007-12-08 Thread Donn Ingle
Hi,
I have two modules, the second is imported by the first.
Let's call them one.py and two.py (two being my API)

In the first I register a function into the second.
[in one.py]
def boo(): ...
...
two.register( boo )

two.startLoop()

In two.py it starts a loop (GTK timeout), so processing remains there.
At some point it's time to call the callback.

[within the loop in two.py]
f = getFunc()
f()

That works, it calls boo( ) in one.py -- all fine. The thing I can't figure
out is that it's calling it from the namespace p.o.v of two.py -- For
example:

[in one.py]
kills=0
def boo():
 print kills

It will abort with:
print kills
UnboundLocalError: local variable 'kills' referenced before assignment

How can I get the 'self' of a module? If I could tell it to [print
moduleself.kills] or something like that I'd be in business again. 
 It would be best to have no funny stuff on the user-end of the API; a
simple [print kills] would be best.

\d

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


Re: setattr getattr confusion

2007-12-08 Thread Donn Ingle
> class Key(object):
> def __init__self):
> self.__dict__['props'] = KeyProps()
Okay - that's weird. Is there another way to spin this?

> def __setattr__(self,var,val):
> setattr(self.props,var,val)
Perhaps by changing this one?

\d

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


Re: Basic animation in Python - how to

2007-12-08 Thread Donn Ingle
> Please refer me to some basic Python code for animation like that .
You are in for a wild ride! Depending on your platform you can use dozens of
different tools. Try wxPython, pyCairo, pyGTK and PIL (Python Imaging
Library) for the most capable.

Basically you are looking at a fairly complex thing - you need to create
a "context" and then draw into it with commands (they vary according to
your toolkit) and then display the result. Loop that and change the drawing
every time and you have animation.

wxPython has very easy widgets for doing something like this (you can use an
animated gif for example), and it's cross-platform so that a big plus. It's
tricky to get into, but well worth it.

hth
\d

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


Re: setattr getattr confusion

2007-12-08 Thread Donn Ingle
Thanks Bruno, I had to keep coding, so I used the long form
[Object.subobject.property = blah] anyway. It's long-winded, but
unambiguous.

\d

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


Re: callback confusion

2007-12-08 Thread Donn Ingle
> As far as I can tell, you have a bit more code in boo, and somewhere in
> that code (after the print statement), you rebind the name 'kills'.
Okay, yes:
def boo()
 kills += 1
 print kills

> the absence of a global declaration, this makes this name a local
> variable. 
I think I see what you mean:

>>> kills=0
>>> def boo():
...  kills += 1
...  print kills
...
>>> print kills
0
>>> boo()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in boo
UnboundLocalError: local variable 'kills' referenced before assignment
>>> kills=77
>>> def boo(): print kills
...
>>> boo()
77

I'm amazed that I've spent so much time with Python and something like that
totally stumps me!?

> FWIW, this is a FAQ. 
If you have a link, that'll help.

\d


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


import X between submodules in a package

2007-12-18 Thread Donn Ingle
Hi, I'm sure this is a FAQ, but I have just not found clarity on the
web/docs.

(using monospaced type to show the tree)
trunk:$ tree
.
fp
|-- fontypython
|   |-- __init__.py
|   |-- cli.py
|   |-- config.py

(I start it all with ./fp)

fp says:
import cli

cli.py says:
import os
import config

config.py says:
print os.environ['HOME']

I get a NameError in config.py

If I add 'import os' to config.py all is well.

So, I guess I am confused about the 'scope' of what gets imported where. I
am thinking that if one module (py file) does *import os* something and
*then* imports another module - the second module should have access to os
too?
 I imagine myself "standing" inside cli.py at this point and saying "well I
can see os, and I'm bringing config *into* this space, so they should be
able to see os too."

How do I structure things so that I don't have endless repetitions of import
in every py file within my package directory?

\d


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


Re: Gnu/Linux dialogue boxes in python

2007-12-18 Thread Donn Ingle
> I've now uploaded a new release of the desktop module which is now, in
> fact, a package:
Thanks Paul, I saw it via the cheese shop rss. I have been too busy to read
this list for a week. I will have a look in due course.

\d

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


Re: import X between submodules in a package

2007-12-19 Thread Donn Ingle
Chris wrote:
> print cli.os.environ['HOME']
I was really confused by your reply until I saw the cli.os part. Okay, I see
what you mean.

\d

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


Re: import X between submodules in a package

2007-12-19 Thread Donn Ingle
> would be a VeryBadThing(tm). 
:)

> Having explicits imports in each module is good wrt/ readability. 
Okay, I can accept that. I worry that it's opening the module file over and
over again - or does it open it once and kind of re-point to it when it
hits a second import of the same thing?

> package, you can of course factor them out in a distinct submodule and
> just do a 'from myimports import *' at the top of the others submodules...
Good point.

\d

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


Re: import X between submodules in a package

2007-12-19 Thread Donn Ingle
> You guess. When fisrt imported, the module's source is executed, a
> module object is created and stored in sys.modules, and the needed names
> are inserted into the importing module's namespace. Next times the
> module is "served" directly from sys.modules.

Peachy, thanks.

\d

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



Sorting Objects by property using locale

2007-12-21 Thread Donn Ingle
Hi,
 Well, I'm beat. I can't wrap my head around this stuff. 

I need to create a list that will contain objects sorted by a "name"
property that is in the alphabetical order of the user's locale.

I used to have a simple list that I got from os.listdir and I could do this:
l = os.listdir(".")
l.sort(locale.strcoll)
Which would work fine. 

But now I need to make objects (of different stripes) for each of the
filenames returned and then I want to collect them all into a main list and
have *that* main list be sorted.

I started some test code like this: I hope the odd characters show.

# -*- coding: utf8 -*-

class Test(object):
def __init__(self,nam):
self.name = nam
def __cmp__(self, other):
return cmp(self.name, other.name)

l = [ Test("ABILENE.ttf"), Test("Årgate.ttf"), Test("årse.ttf"),
Test("Ärt.ttf"), Test("MomentGothic.ttf"), Test("öggi.ttf"),
Test("Öhmygawd.ttf")]

import locale

l.sort() # won't work -> locale.strcoll)

for i in l: print i.name


Can anyone give me a leg-up?

\d

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

Re: Sorting Objects by property using locale

2007-12-21 Thread Donn Ingle
In follow-up: I think this should work:

# -*- coding: utf8 -*-
import locale
locale.setlocale( locale.LC_ALL, "" )

class Test(object):
def __init__(self,nam):
self.name = nam
def __cmp__(self, other):
return cmp(self.name, other.name)

l = [ Test("ABILENE.ttf"), Test("Årgate.ttf"), Test("årse.ttf"),
Test("Ärt.ttf"), Test("MomentGothic.ttf"), Test("öggi.ttf"),
Test("Öhmygawd.ttf")]

l.sort( cmp=locale.strcoll, key=lambda obj:obj.name ) 

for i in l: print i.name


Any bugs?
\d


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

Re: Sorting Objects by property using locale

2007-12-21 Thread Donn Ingle
> Which is even more correct than I hoped for -- in Norwegian, aa is
> pronounced the same as å (which is the 29th letter in the Norwegian
> alphabet) and is sorted according to pronunciation.
Much appreciated bjorn.

\d

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

i18n questions

2007-12-28 Thread Donn Ingle
Hi,
 A soon-to-be happy new year to everyone!

I'm 100% new to this i18n lark and my approach so far has been to create
a .mo file per module in my app. 
 My thinking was, why load one huge .mo file when a single module only needs
a few strings? Since then, it seems, I have made the wrong decision.

For example I have module A that imports module B. Each one does this:

gettext.install( domain, localedir, unicode = True )
lang = gettext.translation(domain, localedir, languages = [ loc ] )
lang.install(unicode = True )

(where doman is the name of the module, so "A" and "B")

The problem is that domain "A" loads and then import B happens and so
the "lang" reference (I think) gets replaced by domain "B" -- the result is
that module A can only translate strings that are in domain "B".

How does one 'merge' gettext.translations objects together? Or is that
insane?

What's the best way to handle a project with multiple domain.mo files?

I hope someone can give me some advice.

\d

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


Re: i18n questions

2007-12-28 Thread Donn Ingle
Thanks for taking the time to post those links. I have read most of them
before. They don't seem to cover the basic issue in my OP, but i18n on
Python is a dark art and maybe there's something I missed.

\d

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


Re: i18n questions

2007-12-28 Thread Donn Ingle
Is there a group better suited to gettext/i18n questions of this sort? Just
wondering because I have little time left to finish my "December" project!

> How does one 'merge' gettext.translations objects together? Or is that
> insane?
> 
> What's the best way to handle a project with multiple domain.mo files?


\d

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


Re: i18n questions

2007-12-29 Thread Donn Ingle
Thorsten Kampe wrote:

> gettext.textdomain('optparse')
> gettext.install('script', unicode = True)

They speak of a 'global' domain in the docs, but (as is my usual beef with
the Python docs -- see PHP docs for sterling help) there is no clarity. 

It *sounds* like there can be a .mo file for *everything* and then one can
also install others on a per-script/module basis, as your code seems to
suggest.

All very confusing.

I have had an entire day to stew and I spent it combining all my po files
into one big file. Now I install that once, and efficiency be damned.

 Still, I'm interested in what's possible and I'll give your approach a
whirl.

Don't let the thread die yet, c'mon you i18n boffins!

Thanks,
\d

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


LANG, locale, unicode, setup.py and Debian packaging

2008-01-12 Thread Donn Ingle
Hello,
 I hope someone can illuminate this situation for me.

Here's the nutshell:

1. On start I call locale.setlocale(locale.LC_ALL,''), the getlocale.

2. If this returns "C" or anything without 'utf8' in it, then things start
to go downhill:
 2a. The app assumes unicode objects internally. i.e. Whenever there is
a "string  like this" in a var it's supposed to be unicode. Whenever
something comes into the app (from a filename, a file's contents, the
command-line) it's assumed to be a byte-string that I decode("utf8") on
before placing it into my objects etc.
 2b. Because of 2a and if the locale is not 'utf8 aware' (i.e. "C") I start
getting all the old 'ascii' unicode decode errors. This happens at every
string operation, at every print command and is almost impossible to fix.

3. I made the decision to check the locale and stop the app if the return
from getlocale is (None,None). 

4. My setup.py (distutils) also tests locale (because it then loads gettext
to give localized information to the user during setup).

5. Because it's doing a raise SystemExit if the locale is (None,None) which
happens if LANG is set to "C", the setup.py stops.

6. Someone is helping me to package the app for Debian/Ubuntu. During the
bizarre amount of Voodoo they invoke to do that, the setup.py is being run
and it is breaking out because their LANG is set to "C"

7. I have determined, as best I can, that Python relies on LANG being set to
a proper string like en_ZA.utf8 (xx_YY.encoding) and anything else will
start Python with the default encoding of 'ascii' thus throwing the entire
app into a medieval dustbin as far as i18n goes.

8. Since I can't control the LANG of the user's system, and I am relying on
it containing 'utf8' in the locale results.. well I seem to be in a
catch-22 here. 

Does anyone have some ideas? Is there a universal "proper" locale that we
could set a system to *before* the Debian build stuff starts? What would
that be - en_US.utf8?

Any words of wisdom would help.
\d

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


piping into a python script

2008-01-24 Thread Donn Ingle
Hi,
(Gnu/Linux - Python 2.4/5)
Given these two examples:
1. 
./fui.py *.py
2.
ls *.py | ./fui.py

How can I capture a list of the arguments?
I need to get all the strings (file or dir names) passed via the normal
command line and any that may come from a pipe.

There is a third case:
3.
ls *.jpg | ./fui.py *.png
Where I would be gathering strings from two places.

I am trying to write a command-line friendly tool that can be used in
traditional gnu/linux ways, otherwise I'd skip the pipe stuff totally.

I have tried:
1. pipedIn = sys.stdin.readlines()
Works fine for example 2, but example 1 goes into a 'wait for input' mode
and that's no good. Is there a way to tell when no input is coming from a
pipe at all?

2. import fileinput
for line in fileinput.input():
print (line)
But this opens each file and I don't want that. 


I have seen a lot of search results that don't quite answer this angle of
the question, so I'm trying on the list.

\d

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


Re: piping into a python script

2008-01-24 Thread Donn Ingle
> Try the fileinput module.
I did give the fileinput module a go, but I can't find much info on it and
the help is ... well, it's python help ;)

> in goes to its stdin where it is processed if it has an argument of -
> fileinput works that way
Okay, I did think of the dash, but did not know how to handle it. Is it a
bash thing or will that dash get passed into the args? (I am using getopt
to parse the options and args)

> which would work for ls and a python program using the fileinput
> module.
Any examples of fileinput (that do not open each file) would be great!
(I'll go searching now anyway)

Thanks,
\d

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


Re: piping into a python script

2008-01-24 Thread Donn Ingle
Paddy wrote:
> ls *.a | ./fui.py -f - *.b
To be sure I grok this: I am seeing the single dash as a placeholder for
where all the piped filenames will go, so *.b happens after *.a has been
expanded and they all get fed to -f, right?

I'm also guessing you mean that I should detect the single dash and then go
look for stdin at that point. How do I detect a lack of stdin?

Thanks,
\d

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


Re: piping into a python script

2008-01-24 Thread Donn Ingle
Paddy wrote:
> fileinput is set to process each file a line at a time unfortunately.
Wow. So there seems to be no solution to my OP. I'm amazed, I would have
thought a simple list of strings, one from stdin and one from the args,
would be easy to get.

I *really* don't want to open each file, that would be insane.

Perhaps I shall have to forgo the stdin stuff then, after all.

\d

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


Re: piping into a python script

2008-01-25 Thread Donn Ingle
Nick Craig-Wood wrote:

> This iterates over the lines of all files listed in sys.argv[1:],
> defaulting to sys.stdin if the list is empty. If a filename is '-', it
> is also replaced by sys.stdin. To specify an alternative list of
> filenames, pass it as the first argument to input(). A single file
> name is also allowed.
Yeah it has been discussed. It seems the one problem with it is that it
opens each file. I only want the filenames.

Anyway, this has more-or-less been solved now.

Thanks,
\d

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


Re: piping into a python script

2008-01-25 Thread Donn Ingle
Hexamorph wrote:

> It's a bit clumsy, but seems to do what I guess you want.
Hey, thanks for that! I will have a go.

\d

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