Re: Help with Iteration

2008-10-17 Thread Aaron "Castironpi" Brady
On Oct 17, 10:44 pm, Chris McComas <[EMAIL PROTECTED]> wrote:
> i have a python script that is computing ratings of sports teams.
>
> what i'm trying to do is setup an iteration for the rating so that the
> python program recomputes the rating if any of the value difference is
>
> > 0.5. it's common for sports ratings to run such iterations...
>
> any tips, pointers on where to look on how to do this the best way?
>
> right now i'm getting the ratings from the file, limiting my results
> to 1 entry, the biggest number, if it's > 0.5, then i want it to
> compute the ratings again. if it is < 0.5 then it just goes on to
> the next step in the file.
>
> thnx in advance.

Can you cut and paste a few lines?  Otherwise I assume your file looks
like this:

A 0.1
B 0.3
C 0.6

You interpret the file like this:

name= A, rating= 0.1
name= B, rating= 0.3
name= C, rating= 0.6
--recompute--

new values:
name= A, rating= 0.1
name= B, rating= 0.2
name= C, rating= 0.4

new file:
A 0.1
B 0.2
C 0.4

Am I right so far?
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Hidden Features of Python'

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 17, 11:00 am, coldpizza <[EMAIL PROTECTED]> wrote:
> Having read through the link below I finally managed to grasp some
> concepts that I only read about in the docs but never got to really
> understand. Maybe it will be helpful for people like myself who are
> not yet fully comfortable with some of Python's `hidden' features.
>
> http://stackoverflow.com/questions/101268/hidden-features-of-python

+1 good link.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to transfer data structure or class from Python to C/C++?

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 9:10 am, Hongtian <[EMAIL PROTECTED]> wrote:
> Not exactly.
>
> In my C/C++ application, I have following function or flow:
>
> void func1()
> {
>     call PyFunc(struct Tdemo, struct &Tdemo1);
>
> }
>
> I mean I want to invoke Python function 'PyFunc' and transfer a data
> structure 'Tdemo' to this function. After some process in Python, I
> want it return 'Tdemo1' back to the C/C++ application.
>
> I research boost.python and think it is not a reasonable solution
> because it make the C/C++ application too complex.
>
> Thanks.
snip

Solution produced here.  Includes dirty kludge, which will welcome
correction.

/C file:

#include 

typedef struct {
int a;
float b;
} TypeA;

static PyObject *
methA(PyObject *self, PyObject *args) {
TypeA a;
TypeA b;
PyObject* fun;
PyObject* res;

PyArg_ParseTuple( args, "O", &fun );
a.a= 10;
a.b= 20.5;

res= PyObject_CallFunction( fun, "II", &a, &b );

printf( "%i %f\n", b.a, b.b );
Py_DECREF( res );

return PyInt_FromLong( 0 );
}

static PyMethodDef module_methods[] = {
{"methA", methA, METH_VARARGS, "No doc"},
{NULL, NULL, 0, NULL}  /* Sentinel */
};


#ifndef PyMODINIT_FUNC  /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initng27ext(void)
{
PyObject* m;
m = Py_InitModule3("ng27ext", module_methods,
   "Custom.");
if (m == NULL)
  return;
}

/Py file:

import ng27ext

import ctypes as c
class TypeA( c.Structure ):
_fields_= [
( 'a', c.c_int ),
( 'b', c.c_float )
]

from _ctypes import _cast_addr
_data_cast= c.PYFUNCTYPE( c.py_object, c.c_void_p, c.py_object,
c.py_object)( _cast_addr ) #dirty kludge

def exposed( obj1, obj2 ):
cob1= _data_cast( obj1, None, c.POINTER( TypeA ) )
cob2= _data_cast( obj2, None, c.POINTER( TypeA ) )
print cob1.contents.a, cob1.contents.b
cob2.contents.a= c.c_int( 60 )
cob2.contents.b= c.c_float( 70.5 )
print cob2.contents.a, cob2.contents.b

print ng27ext.methA( exposed )

/Compile & link:

c:/programs/mingw/bin/gcc ng27ext.c -c -Ic:/programs/python25/include
c:/programs/mingw/bin/gcc -shared ng27ext.o -o ng27ext.pyd -Lc:/
programs/python25/libs -lpython25

/Output:

10 20.5
60 70.5
60 70.50
0
Press any key to continue . . .

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


Re: Finding the instance reference of an object

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 17, 4:03 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Oct 17, 2008, at 2:36 PM, Steve Holden wrote:
snip
> And here, you're doing an assignment -- this is the only test of the  
> three that tests whether the parameter is passed by reference or by  
> value.  The result: it's by value.
>
> > So, is it call by reference or not?
>
> Not.

But it's not by value, q.e.d.
snip

> ...except, of course, that Python's syntax is cleaner...

Excepting that thou then proceedst to 3.

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


Re: Finding the instance reference of an object

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 17, 10:56 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Oct 16, 2008, at 11:23 PM, Dennis Lee Bieber wrote:
snip
> >    But, it seems, you are the only one arguing that "the semantics are
> > all the same"... Doesn't that suggest that they aren't the same?
>
> No, it suggests to me that there's a lot of confusion in the Python  
> community.  :)  It appears as though people either (a) really want to  
> think that Python's object handling is special and unique for  
> emotional reasons, or (b) are comparing it to really ancient languages  
> that didn't have any notion of objects and object references.  This  
> has led to making up new terminology and spreading confusion.  I'm  
> coming back to Python from almost a decade of working with other  
> modern languages (including implementing the compiler for one of  
> them), and I don't see any difference at all between Python's object  
> handling and those.
>
> Best,
> - Joe

I'm not fluent in Java so you'll have to be the judge.

In Python:

b= 0
f( b )

No matter what, b == 0.  C doesn't guarantee this.  Does Java?

Further:

b= {}
c= b
f( b )

No matter what, 'c is b' is true.  C doesn't have an 'is' operator.
Does Java?

Lastly, the word 'same' is ambiguous or poorly defined.  It can mean
either 'identical' or 'equal'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing arguments

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 17, 12:37 pm, Dan Ellis <[EMAIL PROTECTED]> wrote:
> On Oct 17, 6:17 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
>
> > Why do you want/need this magical g() function considering that, as
> > you yourself point out, Python already performs this normalization for
> > you?
>
> A caching idea I'm playing around with.
>
> @cache
> def some_query(arg1, arg2):
>     # Maybe do SQL query or something
>     return result
>
> cache returns a function that does:
>     - Make a key from its arguments
>     - If key is in the cache:
>         - Return result from cache
>     - If it isn't:
>         - Call some_query with the same arguments
>         - Cache and return the result

George Sakkis has a recipe that might help.

http://code.activestate.com/recipes/551779/

It was discussed here:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/91a24f281c59d4a4/31357f9cb4c7bdeb?lnk=st&q=#31357f9cb4c7bdeb
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 17, 6:56 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 17 Oct 2008 23:04:52 +1300, Lawrence D'Oliveiro wrote:
> > In message <[EMAIL PROTECTED]>, Duncan Booth wrote:
>
> >> We already get people asking why code like this doesn't return 3:
>
> > fns = [ lambda: x for x in range(10) ] fns[3]()
> >> 9
>
> >> ... making this change to default arguments would mean the solution
> >> usually proposed to the function scoping question above would no longer
> >> work:
>
> > fns = [ lambda y=x: y for x in range(10) ] fns[3]()
> >> 3
>
> > The right solution, of course, is
>
> >     fns = [(lambda x : lambda : x)(x) for x in range(10)]
>
> Only if by "right solution" you mean "excessively verbose, confusing, and
> the sort of thing that makes even supporters of lambda cringe".
>
> Yes yes, it's just a factory function written with lambdas. It's still
> ugly and exactly the sort of thing that gives ammunition to lambda-
> haters. Unlike the solution given by Duncan, which is understandable to
> any newbie who has learned about default values and lambda, your solution
> requires an understanding of higher-level functions (functions that
> return functions, for anyone who doesn't recognise the term) that most
> newbies won't have.
>
> And while I don't much care for premature optimization, I will point out
> that creating a factory function just to call it once then throw it away
> is very wasteful, and that waste is demonstrated by the running time
> being more than double that of Duncan's solution:
>
> >>> timeit.Timer('[ lambda y=x: y for x in range(10) ]').repeat()
>
> [7.6332600116729736, 6.9825620651245117, 7.0891578197479248]>>> 
> timeit.Timer('[(lambda x : lambda : x)(x) for x in range(10)]').repeat()
>
> [18.984915971755981, 17.808281898498535, 18.432481050491333]
>
> --
> Steven

No, there's a difference in meaning.  One creates a function that is
called with 0 arguments.  The other creates a function that can be
called with 0 or 1 arguments.  The purpose of a parameter is something
that the caller can supply, but doesn't have to.  It is not for
internal-use-only items.  Nested namespaces and object attributes can
be.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to transfer data structure or class from Python to C/C++?

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 9:10 am, Hongtian <[EMAIL PROTECTED]> wrote:
> Not exactly.
>
> In my C/C++ application, I have following function or flow:
>
> void func1()
> {
> call PyFunc(struct Tdemo, struct &Tdemo1);
>
> }
>
> I mean I want to invoke Python function 'PyFunc' and transfer a data
> structure 'Tdemo' to this function. After some process in Python, I
> want it return 'Tdemo1' back to the C/C++ application.
>
> I research boost.python and think it is not a reasonable solution
> because it make the C/C++ application too complex.
>
> Thanks.
>
> On Oct 16, 12:09 pm, "Aaron \"Castironpi\" Brady"
>
> <[EMAIL PROTECTED]> wrote:
> > On Oct 15, 8:08 pm, Hongtian <[EMAIL PROTECTED]> wrote:
>
> > > Hi friends,
>
> > > I am a newer of Python. I want to ask below question:
>
> > > I have a C/C++ application and I want to use Python as its extension.
> > > To do that, I have to transfer some data structure from C/C++
> > > application to Python and get some data structure from Python to C/C++
> > > application. I have researched Python document, but the example only
> > > describes how to transfer some simple data, such as integer,char,
> > > etc.
>
> > > Could you please guide me to do that? or tell me some document to have
> > > a research?
>
> > > Thanks.

Did you have any luck?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to transfer data structure or class from Python to C/C++?

2008-10-17 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 9:10 am, Hongtian <[EMAIL PROTECTED]> wrote:
> Not exactly.
>
> In my C/C++ application, I have following function or flow:
>
> void func1()
> {
>     call PyFunc(struct Tdemo, struct &Tdemo1);
>
> }
>
> I mean I want to invoke Python function 'PyFunc' and transfer a data
> structure 'Tdemo' to this function. After some process in Python, I
> want it return 'Tdemo1' back to the C/C++ application.
>
> I research boost.python and think it is not a reasonable solution
> because it make the C/C++ application too complex.
>
> Thanks.
>
> On Oct 16, 12:09 pm, "Aaron \"Castironpi\" Brady"
>
> <[EMAIL PROTECTED]> wrote:
> > On Oct 15, 8:08 pm, Hongtian <[EMAIL PROTECTED]> wrote:
>
> > > Hi friends,
>
> > > I am a newer of Python. I want to ask below question:
>
> > > I have a C/C++ application and I want to use Python as its extension.
> > > To do that, I have to transfer some data structure from C/C++
> > > application to Python and get some data structure from Python to C/C++
> > > application. I have researched Python document, but the example only
> > > describes how to transfer some simple data, such as integer,char,
> > > etc.
>
> > > Could you please guide me to do that? or tell me some document to have
> > > a research?
>
> > > Thanks.

Did you have any luck?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 8:30 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 16 Oct 2008 11:51:43 -0700, Aaron \"Castironpi\" Brady wrote:
> > If you're sure it's unique, why not just scan through the pairs in
> > locals()?
>
> > for k, v in locals():
> >   if v is the_object_im_looking_for:
> >     name_im_looking_for= k
>
> > This method can sometimes return more than one name, due to the variable
> > ordering of objects in dictionaries.
>
> Because:
>
> (1) in general, objects can have no name at all, or multiple names, so
> this won't work in general (although it may work in a specific case);
>
> (2) it's awfully inefficient if you are doing it a lot; and
>
> (3) even if it works and you can afford to pay the cost, it is almost
> certainly the Wrong Way to solve the problem at hand.
>
> --
> Steven

In fact, what's more called-for, is a mapping in reverse:

name_im_looking_for= lookup[ the_object_im_looking_for ]

You'll just have to modify it in parallel with your local variables,
which is a (yet another) bad sign.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 7:54 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 16 Oct 2008 12:18:49 -0700, Aaron \"Castironpi\" Brady wrote:
>
> [snip]
>
> >> If Python re-evaluated the default value i=i at runtime, the above
> >> would break.
>
> > Not with a mere extra lambda.
>
> Not so. It has nothing to do with lambda, lambda just happens to be a
> convenient example. Here's the code I demonstrated:
>
> >>> for i in xrange(len(callbacks)):
>
> ...     callbacks[i] = lambda s, i=i: '%d %s' % (i, s)
> ...>>> for cb in callbacks:
>
> ...     print cb('string')
> ...
> 0 string
> 1 string
> 2 string
> 3 string
>
> At the end of the first loop, i == 3. If the default value i=i was re-
> evaluated each time the function was called, then i would get the value 3
> each time, which is the same behaviour you get from the version with this:
>
> callbacks[i] = lambda s: '%d %s' % (i, s)
>
> Worse, because you're now relying on i as a global, it's subject to
> strange and mysterious bugs if you later change i and then call the
> callback.
>
> > The fact that a syntax is an opportunity
> > to have a behavior does not imply that it should have one.  The fact
> > that newbies ask about these semantics doesn't imply that they'd ask
> > about another one just as much.  The fact that these semantics have
> > these two uses, doesn't imply that the others don't have more.
>
> Nowhere did I say that the one logically implies the other. I was asked
> for examples of how the current behaviour is useful, not to prove that
> the current behaviour logically follows from first principles. If you
> want to use a programming language where function default values are re-
> evaluated at runtime, you know where to find them.
>
> By the way, for the record I myself has found that behaviour useful on
> occasion. But that's easy to do with current Python:
>
> def spam(x, y=None):
>     if y is None:
>         # re-evaluate the default value at runtime
>         y = get_some_other_value()
>     return x + y
>
> So if you want that behaviour, you can get it. But if Python's semantics
> changed, then how would you implement today's semantics where the default
> is evaluated once only? I don't think you can. So Python's current
> semantics allows the behaviour you want, but in a slightly inconvenient
> form; but the re-evaluate-at-runtime semantics would prevent the
> behaviour I want completely.
>
> > Immutable defaults behave identically in both.
>
> Not quite. To have immutable defaults behave identically, you would need
> to remove at least one more feature of Python: the ability to set a
> default value to an arbitrary expression, not just a literal.
>
> Why do you need to do this? This toy example demonstrates the problem if
> you don't:
>
> yy = 3  # immutable value bound to the name yy
> def spam(x, y=yy-1):
>     return x + y
>
> will have the *expression* yy-1 re-evaluated when they call the function.
> That means that even though 2 is immutable, you can no longer rely on the
> default value being 2, or even existing at all. (What if I del yy at some
> point, then call the function?)
>
> So now to get the behaviour you desire, you not only have to change the
> way Python functions are implemented (and that will have a real and
> significant performance cost), but you also have to change the parser to
> only allow literals as default values.
>
> Note that there is absolutely nothing wrong with using an expression when
> setting default values. But you have to prohibit it, or else introduce
> unexpected behaviour which will trip up not just noobs but everybody. And
> then you'll have noobs writing in weekly asking why they can't write
> "def foo(x, y=10**6)" instead of y=1000.
>
> --
> Steven

You're correct.  I overstated the fact.

> > Immutable defaults behave identically in both.
> Not quite. To have immutable defaults behave identically, you would need

Immutable literal defaults behave identically in both.  Obviously
semantics would change if semantics change.

> > Not with a mere extra lambda.
>
> Not so. It has nothing to do with lambda, lambda just happens to be a
> convenient example. Here's the code I demonstrated:
snip

What I stated is true, but I may not have stated it verbosely enough.

>>> callbacks= [ None ]* 3
>>> for i in range( len( callbacks ) ):
... callbacks[ i ]= ( lambda i: ( lambda s: '%d %s' % (i, s) ) )
( i )
...
>>> for cb in callbacks:
... print cb

Re: How to transfer data structure or class from Python to C/C++?

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 9:10 am, Hongtian <[EMAIL PROTECTED]> wrote:
> Not exactly.
>
> In my C/C++ application, I have following function or flow:
>
> void func1()
> {
>     call PyFunc(struct Tdemo, struct &Tdemo1);
>
> }
>
> I mean I want to invoke Python function 'PyFunc' and transfer a data
> structure 'Tdemo' to this function. After some process in Python, I
> want it return 'Tdemo1' back to the C/C++ application.
>
> I research boost.python and think it is not a reasonable solution
> because it make the C/C++ application too complex.
>
> Thanks.

I am stumped.  Here's what I have.

/C file:

typedef struct {
int a;
float b;
} TypeA;

static PyObject *
methA(PyObject *self, PyObject *args) {
TypeA a;
TypeA b;
PyObject* fun;
PyObject* res;
TypeA* pa;
TypeA* pb;

PyArg_ParseTuple( args, "O", &fun );
a.a= 10;
a.b= 20.5;
b.a= 30;
b.b= 40.5;
printf( "%p %p\n", &a, &b );

pa= &a;
pb= &b;

res= PyObject_CallFunction( fun, "II", &pa, &pb );
Py_DECREF( res );

return PyInt_FromLong( 0 );
}

/Py file:

import ng27ext

import ctypes as c
class TypeA( c.Structure ):
_fields_= [
( 'a', c.c_int ),
( 'b', c.c_float )
]

def exposed( obj1, obj2 ):
print 'in exposed'
print hex( obj1 ), hex( obj2 )
a= c.POINTER( TypeA ).from_address( obj1 )
print a
print a.contents

print ng27ext.methA( exposed )

/Output:

0021FD48 0021FD40
in exposed
0x21fd48 0x21fd40

<__main__.TypeA object at 0x009FF4E0>
0

Which is unexpected.  The address on line 4 should be the contents of
'obj1', 0x21fd48, which it's not.  I must not be using 'from_address'
properly.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 12:23 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 16 Oct 2008 17:05:40 +1300, Lawrence D'Oliveiro wrote:
> > In message <[EMAIL PROTECTED]>, Steven D'Aprano
> > wrote:
>
> >> On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote:
>
> >>> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
>  No, it always contains the default argument because default values
>  are created just ONE TIME
> >  objects>...
>
> >>> Wow, it's a very "dangerous" behavior ...
>
> >> No, it's very *useful* behaviour.
>
> > Can you give an example of how useful it is? Something worth the pain of
> > newbies tripping over it every week?
>
> Did you read the effbot's explanation in the link above? He gives two
> examples, memoization and binding of locals.
>
> The second example is especially interesting, because that's also a
> Gotcha for newbies (not just noobs either...), and the solution to that
> specific gotcha is Python's use of define-time binding of default values.
>
snip
> Newbies get confused by this almost as often as by the default value
> semantics, but the simplest solution to this gotcha is to use Python's
> default values:
snip

Both of those are shorthand notations and there are alternative ways
to express both of them.  The alternatives might even be more literal,
that is, less idiomatic, in the language's tokens' semantics.

For the first one, effbot says: 'You could use a global variable
containing a dictionary instead of the default value; it’s a matter of
taste'.  You could also use an attribute of the function, which is an
entry in func_dict.

For the second one, it is more verbose, but you can add an enclosing
lambda or def expression, and call it on the spot.  I'll be honest:
those are plusses, that is pros of the decision, but they aren't that
strong.

> If Python re-evaluated the default value i=i at runtime, the above would
> break.

Not with a mere extra lambda.  The fact that a syntax is an
opportunity to have a behavior does not imply that it should have
one.  The fact that newbies ask about these semantics doesn't imply
that they'd ask about another one just as much.  The fact that these
semantics have these two uses, doesn't imply that the others don't
have more.  Immutable defaults behave identically in both.

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


Re: default value in __init__

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 1:05 am, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> On Wed, Oct 15, 2008 at 9:43 PM, Aaron Castironpi Brady
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Oct 15, 11:33 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> >> Aaron "Castironpi" Brady wrote:
>
> >> [about how default argument behavior should, in his opinion, be changed]
>
> >> Say what you like. The language is as it is by choice. Were it, for some
> >> reason, to change we would then be receiving posts every week that
> >> didn't understand the *new* behavior.
>
> >> Sometimes people just have to learn to confirm with reality instead of
> >> requiring reality to confirm with their preconceptions. This is one such
> >> case.
>
> >> regards
> >>  Steve
> >> --
> >> Steve Holden        +1 571 484 6266   +1 800 494 3119
> >> Holden Web LLC              http://www.holdenweb.com/
>
> > I am not convinced it should either stay or go, but it's hard to argue
> > one way or the other about something so deeply entrenched.  However,
> > what are your thoughts, whatever the default behavior is, on a
> > decorator that provides the alternative?  That is, a decorator that
> > either reevaluates default arguments each time when the language
> > evaluates them once, or a decorator that evaluates arguments once,
> > when the languages evaluates them each time?
>
> > P.S.
> >> we would then be receiving posts every week that
> >> didn't understand the *new* behavior.
> > That is not obvious and I don't know of any empirical evidence that
> > entails it.  Hard to search the standard library for that figure.
>
> Although primitive and likely somewhat flawed, you may find the
> statistics in the "Compatibility Issues" section 
> ofhttp://mail.python.org/pipermail/python-3000/2007-February/005704.html
> to be of interest.
>
> Cheers,
> Chris
> --
> Follow the path of the Iguana...http://rebertia.com
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

I remember, I've seen it before.  Are you proposing that the number of
posts we'd receive about this feature is proportional to its frequency
of usage?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-10-16 Thread Aaron &quot;Castironpi" Brady
On Oct 16, 12:25 pm, Astley Le Jasper <[EMAIL PROTECTED]>
wrote:
> Thanks for all the responses. That helps.
>
> Ta
>
> ALJ

If you're sure it's unique, why not just scan through the pairs in
locals()?

for k, v in locals():
  if v is the_object_im_looking_for:
name_im_looking_for= k

This method can sometimes return more than one name, due to the
variable ordering of objects in dictionaries.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 11:33 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
>
> [about how default argument behavior should, in his opinion, be changed]
>
> Say what you like. The language is as it is by choice. Were it, for some
> reason, to change we would then be receiving posts every week that
> didn't understand the *new* behavior.
>
> Sometimes people just have to learn to confirm with reality instead of
> requiring reality to confirm with their preconceptions. This is one such
> case.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

I am not convinced it should either stay or go, but it's hard to argue
one way or the other about something so deeply entrenched.  However,
what are your thoughts, whatever the default behavior is, on a
decorator that provides the alternative?  That is, a decorator that
either reevaluates default arguments each time when the language
evaluates them once, or a decorator that evaluates arguments once,
when the languages evaluates them each time?

P.S.
> we would then be receiving posts every week that
> didn't understand the *new* behavior.
That is not obvious and I don't know of any empirical evidence that
entails it.  Hard to search the standard library for that figure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 11:05 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message <[EMAIL PROTECTED]>, Steven D'Aprano
> wrote:
>
> > On Thu, 09 Oct 2008 01:39:30 -0700, kenneth (a.k.a. Paolo) wrote:
>
> >> On Oct 9, 10:14 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>
> >>> No, it always contains the default argument because default values are
> >>> created just ONE TIME
>
> ...
>
>
>
> >> Wow, it's a very "dangerous" behavior ...
>
> > No, it's very *useful* behaviour.
>
> Can you give an example of how useful it is? Something worth the pain of
> newbies tripping over it every week?

Not to be overly practical, but what kind of community push would van
Rossum need in order to make a change, especially with 3.0 almost
out?  Even if everyone agrees, it seems too late even for the entire
3.x series, to be changing something that deeply embedded in not only
_syntax_, but programmers' minds.  I'd say a decorator would be a
viable alternative, but even that would be hard to get into the
language now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to transfer data structure or class from Python to C/C++?

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 8:08 pm, Hongtian <[EMAIL PROTECTED]> wrote:
> Hi friends,
>
> I am a newer of Python. I want to ask below question:
>
> I have a C/C++ application and I want to use Python as its extension.
> To do that, I have to transfer some data structure from C/C++
> application to Python and get some data structure from Python to C/C++
> application. I have researched Python document, but the example only
> describes how to transfer some simple data, such as integer,char,
> etc.
>
> Could you please guide me to do that? or tell me some document to have
> a research?
>
> Thanks.

Take this for what it's worth.  If I understand correctly, you want
this:

struct info {
  char* name;
  char* address;
  int age;
};

int main( ) {
  info A, B;
  python_run( "\
from urllib import urlget\n\
from mylib import populate_struct\n\
page= urlget( 'http://something' )\n\
populate_struct( page, A )\n\
populate_struct( page, B )\n" );
  if( A.age> B.age ) {
something_in_C( );
  }
  return 0;
}

Am I on the right track?  Do you have any questions so far?
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE Question

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 1:07 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:
> Steve Phillips wrote:
> > Hi All,
> > I am just wondering what seems to be the most popular IDE. The reason
> > I ask is I am currently at war with myself when it comes to IDE's. It
> > seems like every one I find and try out has something in it that
> > others don't and viceversa. I am in search for the perfect IDE and
> > after many months of searching, I always come back to IDLE to do what
> > I need to do. I want to use Komodo badly but the one issue I have with
> > that is sometimes the auto-complete works and other times it doesn't.
> > Even if I carbon copy a script.
>
> So what are the specs of the "perfect IDE" ?
snip

I think the editors you see are too high-contrast in their color
scheme.  I look at PyCrust, etc., and NetBeans Java.  The bold, plus
italics, plus color, is too much.  I know it's exciting to be
recognizing patterns and changing fonts, but they overdo it, at least
in these cases.  If you're browsing code contrast is important, but if
you're looking at one screen or two for an extended time, you'll pick
out subtleties after a short time.

I look, sorry all, at Google Groups for an example of mild color
gradients.  I see two different grays and three blues on the current
screen alone.  I could see that as being popular one day.

As for keyboard action, the response time from a keystroke to the
visual reaction, I like mine as fast as possible, lowest lag.  I don't
think that's necessarily as popular, or necessarily as important,
especially if the IDE is written in Python.

You might like to, for the step-through functionality, add a
'settrace' on every thread if possible, overriding the thread module
if necessary.  I would also have appreciated a step through in the
ver. 2.6. 'multiprocessing' module, but that could get difficult,
since each separate instruction pointer spawns a new process.  It
would be even more valuable, and even pedagogically instructive, if
you could control what thread takes its turn next when you're running
more than one.

Keyboard shortcuts are one thing I like about my editor (the one I
prefer), which has hardly any non-essential features at all (in
contrast to emacs I understand).  You can select shortcut groups and
assign number keys.  'Bloodshed-Dev' did not overdo that one, since
they are developing for multiple platforms, and the conventions vary
considerably-- ctrl vs. alt, function keys, &c.  Arrow-movement is
emphasized in mine, with ctrl-arrow, alt-arrow, shift-arrow, all
having functions, plus ctrl-tab for changing file displayed.

The scope of the projects you're gearing to support is a variable--
you want fast startup times if the target projects are going to be
small, but good browsing abilities if they are large.  I haven't liked
the default behavior when identifiers are found that can't be placed
in a namespace, namely lumping them all together and sorting.  10
pixels vs. 12 can make a difference in overall look and feel in the
icons in your browser, and if you have one week to your release date,
I'd rather have an extra week into key response time, than in the
icons.

My $.02.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading operators

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 7:34 am, Mr.SpOOn <[EMAIL PROTECTED]> wrote:
> Hi,
> in a project I'm overloading a lot of comparison and arithmetic
> operators to make them working with more complex classes that I
> defined.
>
> Sometimes I need a different behavior of the operator depending on the
> argument. For example, if I compare a object with an int, I get a
> result, but if I compare the same object with a string, or another
> object, I get another result.
>
> What is the best way to do this? Shall I use a lot of "if...elif"
> statements inside the overloaded operator? Or is there a more pythonic
> and dynamic way?

Off topic.
For the record, the solution in C is pretty bad without using true
overloading.  There's no literal hash, and you have to carry your
types with your variables, possibly using a union.  But if so, you can
use an enum and an array.  This owes to the uniformity of function
signatures of the comparitors you're using.

(uncompiled)

typedef ( int comparitor_t* )( void* ob1, void* ob2 );
comparitor_t comparitors[]= { compare_ints, compare_strs /*,
others*/ };
enum comparison_types {
  ints= 0,
  strs= 1
};
struct variant {
  comparison_types type;
  union {
int i;
str s;
  };
};

int compare( variant& a, variant& b ) {
  assert( a.type== b.type );
  return comparitors[ a.type ]( a, b );
}

'compare' knows how to retrieve its members from the union.  The 'int'
comparitor accesses the 'i' field, &c.  Your compiler needs to know
that enums are ints or that they can be indices into an array.

For BASIC and even VisualBasic up to version 6, you have no choice but
use a switch statement.  The addressof operator won't help since
you're not calling DLL entry points.  VisualBasic.NET claims to
overload functions.  But C++ and VB can both employ the Visitor
pattern "double-dispatch".  It would be good practice to use Visitor
to keep your options open across more languages, except that it's kind
of trivial in Python, oddly enough.  Good middle ground, I guess.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File Management

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 12:47 pm, "erict1689" <[EMAIL PROTECTED]> wrote:
> I am writing this program in which I open up a file and update that
> information but to a new file.  I already have a global variable for
> it but how do I go about creating an openable file in the source code?
>  If it helps here is what I have:
>
> def startUp():
>     # Purpose: opens files and print report headings
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>     payFile=open("payroll.txt", "r")
>     payFile.readline()
>
> def readRecord():
>     # Purpose: reads a record
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
>     employeeRec = payFile.readline()
>     if employeeRec == "":
>         eof = True
>     else:
>         # parse file line for record fields and format/convert for
> final output
>         empName = employeeRec[0:25].strip()
>         previousYTD = float(employeeRec[25:40])
>         payRate = float(employeeRec[40:55])
>         hoursWorked = float(employeeRec[55:70])
>         recordCount += 1
>         eof = False
>
> def writeRecord():
>     # Purpose: writes the updated record to the output file
>     #Parameter
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
> def processRecords():
>     # Purpose: loops through input file and processes each record
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
>     while not eof:
>         calculatePay()
>         printReportLine()
>         writeRecord()
>         readRecord()
>
> def calculatePay():
>     # Purpose: calculates pay and updated YTD
>     # Return values: float - calculated pay, float - updated YTD amount
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
> def printReportLine():
>     # Purpose: prints employee pay information
>     # Parameters passed: float - calculated pay, float - updated YTD
> amount
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
> def closeUp():
>     # Purpose: end of program housekeeping
>     global empName, previousYTD, payRate, hoursWorked, recordCount,
> eof, payFile, \
>            payFileUpdated, newYTD, currentPay
>
>     payFile.close()
>     payFileUpdated.close()
>     print "\nNumber of records in the file was",recordCount
>
> Any and all help is appreciated.

You can use 'open( "result.txt", "w" )' to create a file if it doesn't
exist, and write to it.  Use 'a' instead of 'w' to add to the end of
an existing file.

Later on, you might want to create an object and attributes instead of
global variables.  The readability is different, but if you're only
using one such object, it's not necessarily better.  You can always
try it out and go back if you don't like it.

class PayFile:
  def startUp( self ):
self.payFile=open("payroll.txt", "r")
self.payFile.readline()
  ... etc ...
  def closeUp( self ):
self.payFile.close()
self.payFileUpdated.close()
print "\nNumber of records in the file was",self.recordCount

payFile= PayFile( ) #create a new instance
#or payFile= payfilemod.PayFile( ) in a separate module
payFile.startUp( ) #call the startUp method

Note the 'self' that precedes the variables.  It acts as a container
for them.  It's worth changing in some cases, even if the code is
merely more therapeutic to read.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overloading operators

2008-10-15 Thread Aaron &quot;Castironpi" Brady
On Oct 15, 7:34 am, Mr.SpOOn <[EMAIL PROTECTED]> wrote:
> Hi,
> in a project I'm overloading a lot of comparison and arithmetic
> operators to make them working with more complex classes that I
> defined.
>
> Sometimes I need a different behavior of the operator depending on the
> argument. For example, if I compare a object with an int, I get a
> result, but if I compare the same object with a string, or another
> object, I get another result.
>
> What is the best way to do this? Shall I use a lot of "if...elif"
> statements inside the overloaded operator? Or is there a more pythonic
> and dynamic way?

Multimethods do the thing you're looking for.  Google: 'python
multimethods' gives:

http://www.artima.com/weblogs/viewpost.jsp?thread=101605

by van Rossum.  Some examples:

from mm import multimethod

@multimethod(int, int)
def foo(a, b):
...code for two ints...

@multimethod(float, float):
def foo(a, b):
...code for two floats..

It is especially good if you're using inheritance.  You could also
collect the names of the types, and call a function by name:

(untested)
fname= a.__class__.__name__+ '_'+ b.__class__.__name__
or
fname= re.sub( '[^a-Za-z0-9]+', '', str( type( a ) ) ) + same
type( b )
ffunc= getattr( namespace, fname )

or build a dictionary.

(untested)
f= {}
f[ int, int ]= compA
f[ int, str ]= compB
...
ffunc= f[ type( a ), type( b ) ]

What's your favorite?
--
http://mail.python.org/mailman/listinfo/python-list


Re: docpicture

2008-10-14 Thread Aaron &quot;Castironpi" Brady
On Oct 14, 11:56 am, [EMAIL PROTECTED] wrote:
> André:
>
> > Ok, the following is my first attempt at implementing this idea.
>
> I suggest you to change the program you use to encode your images,
> because it's 1000 bytes, while with my program the same 256 colors
> image needs just 278 bytes:
>
> iVBORw0KGgoNSUhEUgAAABYeCAMfOR5kBGdBTUEAAL
> GPC/xhBQd0SU1FB9gKDhAtOfvfKucYUExURf///wAAADMzM1tb
> W4CAgKSkpMDAwP8AAEQE8ZoBdFJOUwBA5thmCXBIWXMAAA50AA
> AOdAFrJLPWdElEQVQoU63Q0QrAIAgFUO/U9f9/vIxqpRIMdqOXQ6lF
> RHBhsgAXs4zofXPzTZujlMayRjdmaMZDjXvtEy9FFp75zOXI/pX5n6D/lQ
> v1WHnUJarTjGuRxpIxkLHtyIinx4tcy2S694Kjfzn2HDNqYM54H/wB55QF
> O+Mp5mAASUVORK5CYII=
>
> (and it contains just 8 colors, so it can be saved as a 4 bit PNG,
> saving even more bytes). Generally I suggest to use as few bits/pixel
> as possible, just 1 if possible.
> For the encoding/decoding you can use str.encode("base64") and
> str.decode("base64"), you don't need to import modules.
>
> Bye,
> bearophile

+.5 docpicture.  For encoding, it might read in from a file, try
multiple different formats, including SVG, and uses whichever one is
shortest.  It might be nice, if they take too many lines, to store
them at the end of the file, and make sure docpicture looks for them
there.  It could be more hassle (maybe less, actually), to store them
as attributes of the objects they're accompanying, and still locate
them at the bottom-- sort of like an appendix or something.

def foo():
  code code
def bar():
  '''doc str'''
  code code

foo.__docpic__= '''
hexhexhex
hexhexhex'''
bar.__docpic__= '''
hexhexhex'''
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect feature

2008-10-14 Thread Aaron &quot;Castironpi" Brady
On Oct 14, 4:16 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 14, 5:00 pm, "Aaron \"Castironpi\" Brady"
>
>
>
> <[EMAIL PROTECTED]> wrote:
(snip
> > Here's some more info.
>
> > Ver 2.5:
>
> > >>> f( c= 0, c= 0 )
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > TypeError: f() got multiple values for keyword argument 'c'>>> getcallargs( 
> > f, c= 0, c= 0 )
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "", line 64, in getcallargs
> > TypeError: f() takes at least 2 non-keyword  arguments (0 given)
>
> > Just the wrong order to check errors in.
>
> The problem is getcallargs doesn't even see the double entry; if you
> print (args, kwds) from within getcallargs you get ((), {'c': 0}). The
> SyntaxError raised in 2.6 is more reasonable.
>
> George

There are some other bugs in inspect that put getcallargs on par with
the module as is, even without repairing it.  And it covers a majority
of cases.  Perhaps a lower-level C version could circumvent that, or
have access to the right information.
--
http://mail.python.org/mailman/listinfo/python-list


Re: default value in __init__

2008-10-14 Thread Aaron &quot;Castironpi" Brady
On Oct 14, 1:50 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> David C. Ullrich a écrit :
>
>
>
> > In article <[EMAIL PROTECTED]>,
> >  Bruno Desthuilliers <[EMAIL PROTECTED]>
> >  wrote:
snip
> (snip)
snip
> > In particular default parameters should work the way the user
> > expects! The fact that different users will expect different
> > things here is no excuse...
>
> If different users expect different - mostly incompatible - things, how
> would it be possible to have it working "the way the user expect" ?
> Should Python grow some telepathic features to guess the user's
> expectations and modifies itself to meet these expectations ?-)

No.  Just have a user community that only has one user.
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect feature

2008-10-14 Thread Aaron &quot;Castironpi" Brady
On Oct 14, 2:32 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 14, 2:35 pm, "Aaron \"Castironpi\" Brady"
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Oct 14, 9:42 am, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> > > On Oct 14, 3:06 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > > wrote:
>
> > > > En Fri, 10 Oct 2008 14:18:53 -0300, Aaron "Castironpi" Brady
> > > > <[EMAIL PROTECTED]> escribió:
>
snip
> > > > > You are wrapping a function with this signature:
>
> > > > > def f( a, b, c= None, *d, **e ):
>
> > > > > You want to find out the values of 'a', 'b', and 'c' in a decorator.
> > > > > You have these calls:
>
> > > > > f( 0, 1, 'abc', 'def', h= 'ghi' )
> > > > > f( 0, 1 )
> > > > > f( 0, 1, h= 'abc' )
> > > > > f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values
>
> > > > > How do you determine 'a', 'b', and 'c'?
>
> > > > I'm afraid you'll have to duplicate the logic described here:  
> > > > http://docs.python.org/reference/expressions.html#id9
> > > > To my knowledge, there is no available Python code (in the stdlib or
> > > > something) that already does that.
>
> > > I wrote such a beast some time ago; it's hairy but to the best of my
> > > knowledge it seems to reproduce the standard Python 
> > > logic:http://code.activestate.com/recipes/551779/
>
> > > George
>
> > I didn't see a 'got a duplicate argument for keyword "d"' error, but I
> > can add one if I need to.
>
> Why don't you try it out:
>
> >>> def f( a, b, c= None, *d, **e ): pass
> >>> getcallargs(f, 0, 1, 'abc', c= 'def' )
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "getcallargs.py", line 53, in getcallargs
>     "argument '%s'" % (f_name,arg))
> TypeError: f() got multiple values for keyword argument 'c'
>
> George

Excellent.

Here's some more info.

Ver 2.5:

>>> f( c= 0, c= 0 )
Traceback (most recent call last):
  File "", line 1, in 
TypeError: f() got multiple values for keyword argument 'c'
>>> getcallargs( f, c= 0, c= 0 )
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 64, in getcallargs
TypeError: f() takes at least 2 non-keyword  arguments (0 given)

Just the wrong order to check errors in.  Note the spacing '..keyword
arguments..'.  Not a problem on 2.6:

Ver 2.6:

>>> f( c= 0, c= 0 )
  File "", line 1
SyntaxError: keyword argument repeated
>>> getcallargs( f, c= 0, c= 0 )
  File "", line 1
SyntaxError: keyword argument repeated

+1 standard library.
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect feature

2008-10-14 Thread Aaron &quot;Castironpi" Brady
On Oct 14, 9:42 am, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Oct 14, 3:06 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > En Fri, 10 Oct 2008 14:18:53 -0300, Aaron "Castironpi" Brady
> > <[EMAIL PROTECTED]> escribió:
>
> > > On Oct 10, 3:36 am, Bruno Desthuilliers  > > [EMAIL PROTECTED]> wrote:
> > >> I don't get what you're after ??? The decorator has full access to both
> > >> the actual params *and* the function's signature (via
> > >> inspect.getargspec). So your initial question "if you wanted a decorator
> > >> that examines the parameters to a function" seems fully answered. You
> > >> will indeed have to write a couple lines of code if you want the same
> > >> formating as the one you'd get with inspect.currentframe(), but what ?
>
> > >> FWIW, Michele Simionato's decorator module has some trick to allow for
> > >> signature-preserving decorators, so you may want to have a look - but
> > >> I'm not sure if this would solve your problem - at least in a sane way.
>
> > > It's not exactly the next Millennium problem, but there are some
> > > substantial checks you have to do on a per-parameter basis to see the
> > > same thing that a function sees, when all you have is *args, **kwargs.
>
> > > You are wrapping a function with this signature:
>
> > > def f( a, b, c= None, *d, **e ):
>
> > > You want to find out the values of 'a', 'b', and 'c' in a decorator.
> > > You have these calls:
>
> > > f( 0, 1, 'abc', 'def', h= 'ghi' )
> > > f( 0, 1 )
> > > f( 0, 1, h= 'abc' )
> > > f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values
>
> > > How do you determine 'a', 'b', and 'c'?
>
> > I'm afraid you'll have to duplicate the logic described here:  
> > http://docs.python.org/reference/expressions.html#id9
> > To my knowledge, there is no available Python code (in the stdlib or
> > something) that already does that.
>
> I wrote such a beast some time ago; it's hairy but to the best of my
> knowledge it seems to reproduce the standard Python 
> logic:http://code.activestate.com/recipes/551779/
>
> George

I didn't see a 'got a duplicate argument for keyword "d"' error, but I
can add one if I need to.

Is there some reason why the built-in behavior should not be made
available, such as it's poorly defined outside the function?  Or is it
just the fact that it's complicated that keeps it out of 'inspect'?
--
http://mail.python.org/mailman/listinfo/python-list


Mail reader & spam

2008-10-12 Thread Aaron &quot;Castironpi" Brady
Hello all,

I'm hesitating to change news readers because I like Google's
interface.  In the interests of discussion, I'd make better
contributions without it, if only because it's a known spam source,
but its reader format beats the alternatives I've seen.  I checked out
the 'nntplib' module to see if some hybrid with Thunderbird and GMane,
for example, would be possible.  I don't think it would be that hard,
but before I put in the effort, I wanted feedback.  Here's what I like
about it.

When new messages come, the entire thread they're in is moved to the
top of the list.  You can click on it and browse the entire topic, and
compose your reply right under the message you're replying to.  You
can also mark topics, to keep updated on when and what replies to your
messages come too.  I haven't found all these features in another
reader, including Outlook, Thunderbird, and GMane.  You've noticed
Thunderbird isn't the best for discussing Python, due to its colored
indents instead of caret marks in the interpreter prompt..  Free is a
big plus too.

What's my best option?  Hijack Google's reader, and override 'reply'
to use an SMTP account?  Write my own, perhaps sorting marked and
unmarked messages separately?

It's of course everyone's choices whether to block Google or not, and
miss out on anyone that posts them through Google.  I don't think the,
'Well, if you insist' tactic is as cooperative and productive as
acknowledging, 'It's a big spam source, maybe I can find a provider
that isn't so beneficial to blacklist'.

Is there any resolution to the dilemma?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most compact "X if X else Y" idiom

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 12, 12:01 am, [EMAIL PROTECTED] wrote:
> I find myself having to do the following:
>
>   x = (some complex expression)
>   y = x if x else "blah"
>
> and I was wondering if there is any built-in idiom that
> can remove the need to put (some complex expression)
> in the temporary variable x.
>
> e.g. something like the below:
>
>  y= foobar ((some complex expression), "blah")
>
> I realized foobar() can be easily coded as:
>   def foobar(a,b):
>     if a: return a
>     else: return b
>
> But I was wondering if there was a built-in function or syntax
> that already does this.

You could take your chances on 'or', as follows:

>>> (6+ (3<< 1) ) or 'blah'
12
>>> (6- (3<< 1) ) or 'blah'
'blah'

You don't need to use the ternary statement:

y = (some complex expression)
if not y:
   y = "blah"

If you find yourself using it a lot, why not add it to your site's
utilities modules?  Take your time, and if you find numerous uses,
present them and make the case Python should have a built-in to do it,
something like 'ditto' marks:

(6- (3<< 1) ) if ditto else 'blah'

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


Re: default value in __init__

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 11, 4:41 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Fri, 10 Oct 2008 06:20:35 -0700, bearophileHUGS wrote:
snip
> > I have seen professional programmers too use class attributes instead of
> > instance ones...
>
> That's only a mistake if you don't mean to use class attributes instead
> of instance attributes.

Off topic: That gives me an idea for an interesting technique.

class Foo( HasInstanceVars ):
class InstanceVars:
x= 0
y= None
z= [ 0, 1 ]

The __init__ method in HasInstanceVars adds any InstanceVars members
to the instance members.  It's not terribly different than using
__init__-- slightly slower, slightly clearer.  It could even include a
'__initvars__' variable which adds constructor parameters by name to
the instance.  It's marginally problematic how to create new objects
each time Foo is instantiated.  You could require factories, pickle-
unpickle the contents, require 'deepcopy' compatibility, execute a
string, or call a function which uniquely executes the class
statement.

>>> foo= Foo()
>>> foo.x+= 1
>>> foo2= Foo()
>>> foo2.x
0
>>> foo.x
1

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


Re: default value in __init__

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 12:30 pm, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> [EMAIL PROTECTED] wrote:
> >> I don't think simply re-executing the default argument
> >> expression on each call works either: that would confuse at least as
> >> many people as the current system.
>
> > May I ask you why? I think I don't agree, but I am not sure.
>
(snip)
> I wonder whether it is the way the default argument expressions are
> embedded inside the function that causes the confusion? If for example
> default arguments were defined like this:
>
> class C:
>   @default(d={})
>   def __init__(self, i=10, d):
>     self.d = d
>     self.i = i
>
> would moving the expression before the 'def' make people less inclined to
> be suprised that the object is shared?

You could of course define a wrapper to do call-time assignment:

@calltime( d= dict, e= tuple )
def foo( self, d, e ):

If this decorator appeared in the standard library, newbies would be
able to stumble upon it.

I don't think either semantic is more obvious from the syntax alone.
It could mean either thing just as reasonably, and if Python defined
the opposite, we'd be getting opposite complaints.

On one hand, note that the return statement does not follow the same
convention:

>>> def f(): return [ 0, 1 ]
...
>>> f().append( 2 )
>>> f()
[0, 1]

It constructs a new object each time.  In light of this, the burden of
proof could even fall on Python for the inconsistency.  That is,
assuming that it's well- and always defined.
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 11, 1:59 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
>
> > What does print pythonapi.PyCObject_AsVoidPtr(display) give you?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Traceback (most recent call last):
>   File "pygametest.py", line 125, in 
>     app = PyGameOGREApp()
>   File "pygametest.py", line 33, in __init__
>     self._createWindow(width, height, fullscreen)
>   File "pygametest.py", line 65, in _createWindow
>     print pythonapi.PyCObject_AsVoidPtr(display)
> ctypes.ArgumentError: argument 1: : Don't
> know how to convert parameter 1
>
> --
> Gord Allott ([EMAIL PROTECTED])
>
>  signature.asc
> < 1KViewDownload

If anyone knows this better, feel free to step in.

Put this before the call:

ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p
ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ ctypes.py_object ]

The reason is that this is the default signature, which is wrong:

>>> ctypes.pythonapi.PyCObject_AsVoidPtr.restype

>>> ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes
>>>

There are other ways to prototype it if you like, too.
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 11, 9:45 am, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
>
> > My pygame install just returns an integer in get_wm_info.  Take a
> > look:
>
> >>>> pygame.display.get_wm_info()
> > {'window': 1180066, 'hglrc': 0}
> >>>> pygame.display.get_wm_info()['window']
> > 1180066
> >>>> ctypes.c_void_p( _ )
> > c_void_p(1180066)
>
> > You're suggesting yours looks like this:
>
> >>>> pygame.display.get_wm_info()
> > { ... 'display': ctypes.py_object( 1180066 ), ... }
>
> > What does type( display ) give you?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> yes its different on windows and linux, windows only has a few items
> where linux has many more. 'window' is just the window 'id'  at any rate
> which is not the data I am after (which is internally an address to an
> xlib structure)
> this is what pygame.display.get_wm_info() returns on linux:
> {'fswindow': 31457283, 'wmwindow': 31457284, 'window': 31457294,
> 'lock_func': , 'unlock_func':  object at 0x89dfa88>, 'display': }
>
> note how the display object is a PyCObject, thats got the address I want
>  inside it.
>

What does print pythonapi.PyCObject_AsVoidPtr(display) give you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x]

2008-10-11 Thread Aaron &quot;Castironpi" Brady
On Oct 11, 2:23 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
snip
> I am talking about a clash between *conventions*, where there could be
> many argument names of the form a_b which are not intended to be two item
> tuples.
>
> In Python 2.x, when you see the function signature
>
> def spam(x, (a, b))
>
> it is clear and obvious that you have to pass a two-item tuple as the
> second argument. But after rewriting it to spam(x, a_b) there is no such
> help. There is no convention in Python that says "when you see a function
> argument of the form a_b, you need to pass two items" (nor should there
> be).
>
> But given the deafening silence on this question, clearly other people
> don't care much about misleading argument names.

No, we just document them. (ducks) And ambiguous is different from
misleading anyway.  If the docs say pass a 2-tuple as the 2nd
parameter...?
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 10:54 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> snip
> > Last, you
> > haven't mentioned an attempt with PyCObject_AsVoidPtr yet:
>
> > void* PyCObject_AsVoidPtr(PyObject* self)
> >     Return the object void * that the PyCObject self was created with.
>
> > Where does that get you?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> sorry yes you were right, I was reading PyCObject_AsVoidPtr as
> PyCObject_FromVoidPtr :)
>
> using AsVoidPtr is a little confusing, this is the code I am using:
>         display = pygame.display.get_wm_info()['display']
>         pyobj = py_object(display)
>         ref = pointer(pyobj)
>
>         print pythonapi.PyCObject_AsVoidPtr(ref)
>
> it produces the following traceback:
> Traceback (most recent call last):
>   File "pygametest.py", line 125, in 
>     app = PyGameOGREApp()
>   File "pygametest.py", line 33, in __init__
>     self._createWindow(width, height, fullscreen)
>   File "pygametest.py", line 64, in _createWindow
>     print pythonapi.PyCObject_AsVoidPtr(ref)
> TypeError: PyCObject_AsVoidPtr with non-C-object
>
> - I think that's because its a pointer to the ctypes py_object() rather
> than the PyCObject we are dealing with but I have no idea how to create
> a pointer to that.
>

My pygame install just returns an integer in get_wm_info.  Take a
look:

>>> pygame.display.get_wm_info()
{'window': 1180066, 'hglrc': 0}
>>> pygame.display.get_wm_info()['window']
1180066
>>> ctypes.c_void_p( _ )
c_void_p(1180066)

You're suggesting yours looks like this:

>>> pygame.display.get_wm_info()
{ ... 'display': ctypes.py_object( 1180066 ), ... }

What does type( display ) give you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using multiprocessing

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 10:48 pm, nhwarriors <[EMAIL PROTECTED]> wrote:
> On Oct 10, 10:52 pm, "Aaron \"Castironpi\" Brady"
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Oct 10, 3:32 pm, nhwarriors <[EMAIL PROTECTED]> wrote:
>
> > > I am attempting to use the (new in 2.6) multiprocessing package to
> > > process 2 items in a large queue of items simultaneously. I'd like to
> > > be able to print to the screen the results of each item before
> > > starting the next one. I'm having trouble with this so far.
>
> > > Here is some (useless) example code that shows how far I've gotten by
> > > reading the documentation:
>
> > snip code
>
> > > This works great, except that nothing can be output until everything
> > > in the queue is finished. I'd like to write out the result of fac(n)
> > > for each item in the queue as it happens.
>
> > > I'm probably approaching the problem all wrong - can anyone set me on
> > > the right track?
>
> > Works fine for me.  Formatting time.clock(), with a different range:
>
> > 0.0 fac(25000) done on Process-2
> > 0.09334 fac(25001) done on Process-1
> > 2.25036 fac(25002) done on Process-2
> > 2.41227 fac(25003) done on Process-1
> > 3.57167 fac(25004) done on Process-2
>
> > I'm on Win32.
>
> Strange. I was on Win32 (Cygwin) earlier today and it was doing what I
> reported above. At home on Linux, it works as I wanted and you
> experienced. Must be something screwy with running it in Cygwin.
>
> Thanks guys!

You might need to flush the standard out between calls.  That gets
suggested from time to time.  Not sure what Python's req.s are.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 10:37 pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Oct 9, 5:30 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Is there a canonical way to address the bits in a structure
> > like an array or string or struct?
>
> > Or alternatively, is there a good way to combine eight
> > ints that represent bits into one of the bytes in some
> > array or string or whatever?
snip
>
> class BitSet:
>     def __init__( self, value ):
>         self.value= value
>     def __setitem__( self, index, value ):
>         if value:
>             self.value= self.value| (1<< index)
>         elif self[ index ]:
>             self.value= self.value^ (1<< index)
>     def __getitem__( self, index ):
>         return self.value& (1<< index )
snip

This could read:

def __getitem__( self, index ):
return 1 if self.value& (1<< index ) else 0

Or you could shift self.value, and mask with unity.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Efficient Bit addressing in Python.

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 9, 5:30 pm, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> Is there a canonical way to address the bits in a structure
> like an array or string or struct?
>
> Or alternatively, is there a good way to combine eight
> ints that represent bits into one of the bytes in some
> array or string or whatever?
>
> It seems to me that there is a dilemma here :
>
> if you can write:
>
> bit3 = 1
>
> Then you have to jump through hoops to get
> bit0 through bit7 into some byte that you can send
> to an i/o routine.
>
> On the other hand, if you keep the bits "in" the
> byte, then you can write:
>
> byte[3] = '\x7e'
>
> but you have to jump through hoops to get at
> the individual bits.
>
> Is there a "best" way?
>
> It would be nice to be able to write:
>
> if io.byte2.bit3:
>    do_something()
>
> if io.byte2 == alarm_value:
>   do_something_else()
>
> where:
>
>  io.byte2 & 8   "is"  io.byte2.bit3
>
> Is this possible?
>
> - Hendrik

This is tolerable.  If you've got a better 'clear' operation than
'xor', you're welcome to it.

class BitSet:
def __init__( self, value ):
self.value= value
def __setitem__( self, index, value ):
if value:
self.value= self.value| (1<< index)
elif self[ index ]:
self.value= self.value^ (1<< index)
def __getitem__( self, index ):
return self.value& (1<< index )
def __repr__( self ):
return repr( self.value )

if __name__== '__main__':
b= BitSet( 15 )
print b
b[0]= 0
print b
b[0]= 1
print b
b[4]= 1
print b
b[4]= 0
print b

/Output:
15
14
15
31
15
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using multiprocessing

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 3:32 pm, nhwarriors <[EMAIL PROTECTED]> wrote:
> I am attempting to use the (new in 2.6) multiprocessing package to
> process 2 items in a large queue of items simultaneously. I'd like to
> be able to print to the screen the results of each item before
> starting the next one. I'm having trouble with this so far.
>
> Here is some (useless) example code that shows how far I've gotten by
> reading the documentation:
>
snip code
>
> This works great, except that nothing can be output until everything
> in the queue is finished. I'd like to write out the result of fac(n)
> for each item in the queue as it happens.
>
> I'm probably approaching the problem all wrong - can anyone set me on
> the right track?

Works fine for me.  Formatting time.clock(), with a different range:

0.0 fac(25000) done on Process-2
0.09334 fac(25001) done on Process-1
2.25036 fac(25002) done on Process-2
2.41227 fac(25003) done on Process-1
3.57167 fac(25004) done on Process-2

I'm on Win32.
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 7:59 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > Yes, well said.  But no, not true, not necessarily.  You can choose/
> > change return types with your code.  If the call is defined already
> > and you can't change the return, just define a new one that returns
> > long.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> the problem is that the pointer or long or whatever it is thats returned
> won't be the data I am after. the code for PyCObject_FromVoidPtr is as
> follows:
>
> PyObject *
> PyCObject_FromVoidPtr(void *cobj, void (*destr)(void *))
> {
>     PyCObject *self;
>
>     self = PyObject_NEW(PyCObject, &PyCObject_Type);
>     if (self == NULL)
>         return NULL;
>     self->cobject=cobj;
>     self->destructor=destr;
>     self->desc=NULL;
>
>     return (PyObject *)self;
>
> }
>
> it obviously creates a new PyObject and returns that, which has already
> happened once (the address I am after is passed to python via
> PyCObject_FromVoidPtr(adress_i_am_after, NULL), doing that puts the
> address I am after into the .cobject attribute of a new pyobject
> structure and passes that to the python script via the 'display' key in
> a dictionary.
>
> If I were to then take the pycobject in this display key and pass it via
> ctypes into PyCObject_FromVoidPtr it would simply create a new pycobject
>  and put a pointer to the old pycobject in the new pycobject's .cobject
> attribute. it just means that I am getting further and further away from
> where I want to be surely? if I were to take the current pointer at this
> stage, to get to the address I actually want in C it would have to
> follow something along the lines of
> long address_i_want = (long)(new_pycobj->cobject->cobject);
>
> What would be great is if there is some easy simple way of accessing the
> .cobject attribute of the first pycobject thats passed via the
> dictionary to python.
>
> --
> Gord Allott ([EMAIL PROTECTED])
>
>  signature.asc
> < 1KViewDownload

You are hard to follow.  There is the 'cast' function, which I've had
some success with, even in adding pointers and offsets.  It took a
look at the code for it though, and calling an undocumented version of
it.  I can post that later if you don't have luck the same.  You can
write extension modules to do that as well, and there's always a
Google search which personally I forget half the time too.  Last, you
haven't mentioned an attempt with PyCObject_AsVoidPtr yet:

void* PyCObject_AsVoidPtr(PyObject* self)
Return the object void * that the PyCObject self was created with.

Where does that get you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where/how to propose an addition to a standard module?

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 2:10 pm, Joe Strout <[EMAIL PROTECTED]> wrote:
> I would like to propose a new method for the string.Template class.  
> What's the proper procedure for doing this?  I've joined the python-
> ideas list, but that seems to be only for proposed language changes,  
> and my idea doesn't require any change to the language at all.
>
>  From , it sounds like the  
> PEP process is appropriate here, though other PEPs (like 
>   > make it sound as though these are meant for proposals for "Python  
> 3000", which is not necessarily my intent.
>
> Here's a brief sketch of my proposal, in case it helps:
>
> Add a "match" function to string.Template, which takes a text string  
> as a parameter.  If this text string can be matched to the template,  
> by substituting some portion of the given string for each field of the  
> template, then .match returns a dictionary, where each key is a field  
> name and the value is the corresponding text from the input.  If the  
> text string cannot be matched to the template, then .match returns None.
>
> I understand that if I'm to write a PEP, I'll need to flesh this out  
> considerably as per PEP 0001.  But that document also suggests first  
> discussing it here.  I'm still a newbie (or actually, oldbie-turned-
> nonbie-turned-newbie-again), so I could use some advice.  What's the  
> next step in advocating for this idea?
>
> Thanks,
> - Joe

I think it's something the 're' module already does.  Correct me if
I'm wrong.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porn Addiction Solutions?

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 10:33 am, Aspersieman <[EMAIL PROTECTED]> wrote:
> On Fri, 10 Oct 2008 16:11:07 +0200, <[EMAIL PROTECTED]> wrote:
> > On Oct 10, 7:03 am, Um Jammer NATTY <[EMAIL PROTECTED]> wrote:
> >> On Oct 10, 5:37 am, [EMAIL PROTECTED] wrote:
>
> >> > It's very simple. You need to know the world is much more than the
> >> > imaginery life you are looking. Spend some time in the feet of the
> >> > Lord Jesus who would help you to come out of this trouble.
>
> >> Does anyone else find it amusing that this poster assumes 'imaginary'
> >> and the Lord Jesus are polar opposites???
>
> > I'm guessing...only you!
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Nope, not only him.
>
> On another note, why is this a discussion on c.l.p? Shouldn't we
> discourage these kinds of posts?

*Lol* to "calling the base class constructor" - Reacher.  But I
actually have a second to treat this.

First, no the poster did not assume the two referents were 'polar
opposites' per se (smacks of rhetoric), even to the extent that
individuals and relations to reality can be.  In other words, neither
Sherlock Holmes nor George Bush are opposites of imaginary.  No it
would not be exactly amusing if he did.

It is not clear from his post that he had thought through his advice
logically, or that it would help, unless so by definition: "Do
something that would help you."  If the latter (analytically true),
then no it should not be discouraged, a kind shoulder is nice to cry
on, even if its owner merely says, "there, there" or "best of luck".
If the former (not thought through), then no, he apparently means
well.  Someone (apparently) asked for help and he shouldn't be turned
away, even if the primary purpose of a gathering is academic and
unrelated.  What was the exact content of his advice, what are its
intended effects, and what are the actual effects, to the extent
they're different?

Neither the original post nor the replies were contrary to the group's
goal, I didn't find.  People are people and humor is good in small
quantities.  Furthermore, I have wondered what some of the external
beliefs and habits of the readers are, as they never show up
otherwise, and if only to know a little better who I'm talking to...
and hearing from!

Obviously the essays go somewhere else, in the vein of 'wrong time
wrong place', but a simple +1 quitting, +1 free expression, -1
addiction from a few, or whatever the beliefs they have are, would be
appropriate; so I hold.

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


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 4:16 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > I see.  If I understand, you have a PyCObject in a dictionary.
>
> > Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr.  Its
> > return type should be 'c_void_p', and you can use 'result.value' to
> > get the original pointer.
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> I have a hard time following that, if using ctypes you used PyDLL to
> call PyCObject_AsVoidPtr on the PyCObject I already have surely it would
>  give me back a pointer (void for sake of simplicity) but it would be a
> pointer to a new PyCObject and thus calling result.value on it would
> only return the memory address of the new PyCObject?
> --
> Gord Allott ([EMAIL PROTECTED])
>
>  signature.asc
> < 1KViewDownload


Yes, well said.  But no, not true, not necessarily.  You can choose/
change return types with your code.  If the call is defined already
and you can't change the return, just define a new one that returns
long.
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 12:04 pm, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > Did you try:
>
> > tmp= PyLong_FromLong( ( long ) info.info.x11.display );
> > PyDict_SetItemString (dict, "display", tmp);
> > Py_DECREF (tmp);
>
> > Or also try:
>
> > PyCObject_AsVoidPtr( tmp );
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> the problem is that I can't edit the C code - well I can and might
> submit a patch to the project but I also need a solution that works from
> the python side of things.
>

I see.  If I understand, you have a PyCObject in a dictionary.

Look at the 'ctypes' module and try calling PyCObject_AsVoidPtr.  Its
return type should be 'c_void_p', and you can use 'result.value' to
get the original pointer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect feature

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 3:36 am, Bruno Desthuilliers  wrote:
> Aaron "Castironpi" Brady a écrit :
>
>
>
> > On Oct 9, 3:48 am, Bruno Desthuilliers  > [EMAIL PROTECTED]> wrote:
> >> Aaron "Castironpi" Brady a écrit :
>
> >>> Hello,
> >>> The 'inspect' module has this method:
> >>> inspect.getargvalues(frame)
> >>> It takes a frame and returns the parameters used to call it, including
> >>> the locals as defined in the frame, as shown.
> >>>>>> def f( a, b, d= None, *c, **e ):
> >>> ...     import inspect
> >>> ...     return inspect.getargvalues( inspect.currentframe() )
> >>> ...
> >>>>>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )
> >>> (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
> >>> 'e': {'h': 'g
> >>> hi'}, 'd': 'abc', 'inspect':  >>> \Python26\lib\in
> >>> spect.pyc'>})
> >>> However, if you wanted a decorator that examines the parameters to a
> >>> function, you're out of luck.  By the time you have a frame, you're
> >>> already in the function.
> >> Hem...
>
> >> def decorator(func):
> >>      def _decorator(*args, *kw):
> >>          print "func args are ", *args, **kw
> >>          return func(*args, **kw)
> >>      return _decorator
>
> > It is less of a problem without tuple unpacking, but you still have
> > code like:
>
> > if len( args )>= 2:
> >    b= args[ 1 ]
> > else:
> >    try:
> >       b= (somehow check b's default val.)
> >    except NoDefaultVal:
> >       raise ArgumentError
>
> > Worse yet, you have it for each parameter.  Unless I missed something,
> > this is the only way to mimic/recreate the signature of the decoratee.
>
> I don't get what you're after ??? The decorator has full access to both
> the actual params *and* the function's signature (via
> inspect.getargspec). So your initial question "if you wanted a decorator
> that examines the parameters to a function" seems fully answered. You
> will indeed have to write a couple lines of code if you want the same
> formating as the one you'd get with inspect.currentframe(), but what ?
>
> FWIW, Michele Simionato's decorator module has some trick to allow for
> signature-preserving decorators, so you may want to have a look - but
> I'm not sure if this would solve your problem - at least in a sane way.

It's not exactly the next Millennium problem, but there are some
substantial checks you have to do on a per-parameter basis to see the
same thing that a function sees, when all you have is *args, **kwargs.

You are wrapping a function with this signature:

def f( a, b, c= None, *d, **e ):

You want to find out the values of 'a', 'b', and 'c' in a decorator.
You have these calls:

f( 0, 1, 'abc', 'def', h= 'ghi' )
f( 0, 1 )
f( 0, 1, h= 'abc' )
f( 0, 1, 'abc', c= 'def' ) #raise TypeError: multiple values

How do you determine 'a', 'b', and 'c'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: extracting null pointer address from PyCObject with ctypes

2008-10-10 Thread Aaron &quot;Castironpi" Brady
On Oct 10, 5:24 am, Gordon Allott <[EMAIL PROTECTED]> wrote:
> Hello :)
>
> The result of various incompatibilities has left me needing to somehow
> extract the address that a null pointer is pointing to with the null
> pointer being exposed to python via PyCObject_FromVoidPtr
>
> the code that creates the PyCObject is as follows:
>     tmp = PyCObject_FromVoidPtr (info.info.x11.display, NULL);
>     PyDict_SetItemString (dict, "display", tmp);
>     Py_DECREF (tmp);
>

Did you try:

tmp= PyLong_FromLong( ( long ) info.info.x11.display );
PyDict_SetItemString (dict, "display", tmp);
Py_DECREF (tmp);

Or also try:

PyCObject_AsVoidPtr( tmp );
--
http://mail.python.org/mailman/listinfo/python-list


Re: Traceback not going all the way to the exception?

2008-10-09 Thread Aaron &quot;Castironpi" Brady
On Oct 9, 3:27 am, sert <[EMAIL PROTECTED]> wrote:
> I just got an exception and the traceback wouldn't go all the
> way to the statement that threw the exception. I found that out
> by using the debugger.
>
> Contrast the traceback:
>
> http://tinyurl.com/5xglde
>
> with the debugger output (notice the arrow pointing to the last
> statement the traceback showed and how the execution went on
> beyond it):
>
> http://tinyurl.com/3fjgrl
>
> Is this a known issue or should I submit a bug report?

Could be you are re-raising an exception by hand instead of with the
bare 'raise' statement.  Notice the difference in tracebacks shown
here:

>>> def f():
... try:
... g()
... except Exception, e:
... raise e
...
>>> def g():
... raise Exception("abc")
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in f
Exception: abc
>>> def f():
... try:
... g()
... except Exception, e:
... raise
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in f
  File "", line 2, in g
Exception: abc
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe eval of insecure strings containing Python data structures?

2008-10-09 Thread Aaron &quot;Castironpi" Brady
On Oct 9, 1:44 pm, Jason Scheirer <[EMAIL PROTECTED]> wrote:
> On Oct 9, 9:01 am, Paul Rubin  wrote:
>
> > Lie Ryan <[EMAIL PROTECTED]> writes:
> > > in python 2.6, ast.literal_eval may be used to replace eval() for
> > > literals.
>
> > What happens on literal_eval('[1]*9') ?
>
> The documentation clearly states that it will fail to evaluate and
> raise a ValueError because there is an operation in the statement. 5*5
> is NOT the literal 25, it is the equivalent to operator.mul(5, 5), and
> the same is true to []*x

Kudos to author on creating this function!
--
http://mail.python.org/mailman/listinfo/python-list


Re: inspect feature

2008-10-09 Thread Aaron &quot;Castironpi" Brady
On Oct 9, 3:48 am, Bruno Desthuilliers  wrote:
> Aaron "Castironpi" Brady a écrit :
>
>
>
> > Hello,
>
> > The 'inspect' module has this method:
>
> > inspect.getargvalues(frame)
>
> > It takes a frame and returns the parameters used to call it, including
> > the locals as defined in the frame, as shown.
>
> >>>> def f( a, b, d= None, *c, **e ):
> > ...     import inspect
> > ...     return inspect.getargvalues( inspect.currentframe() )
> > ...
> >>>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )
> > (['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
> > 'e': {'h': 'g
> > hi'}, 'd': 'abc', 'inspect':  > \Python26\lib\in
> > spect.pyc'>})
>
> > However, if you wanted a decorator that examines the parameters to a
> > function, you're out of luck.  By the time you have a frame, you're
> > already in the function.
>
> Hem...
>
> def decorator(func):
>      def _decorator(*args, *kw):
>          print "func args are ", *args, **kw
>          return func(*args, **kw)
>      return _decorator

It is less of a problem without tuple unpacking, but you still have
code like:

if len( args )>= 2:
   b= args[ 1 ]
else:
   try:
  b= (somehow check b's default val.)
   except NoDefaultVal:
  raise ArgumentError

Worse yet, you have it for each parameter.  Unless I missed something,
this is the only way to mimic/recreate the signature of the decoratee.

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


Re: inspect bug

2008-10-09 Thread Aaron &quot;Castironpi" Brady
On Oct 9, 9:47 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Thu, 09 Oct 2008 00:24:20 -0300, Aaron "Castironpi" Brady  
> <[EMAIL PROTECTED]> escribió:
>
> > Found this bug.  It's in 2.6, too bad.
>
> Posting here is not going to help much, it just will be lost. Would be  
> better to file a bug report athttp://bugs.python.org/
>
> --
> Gabriel Genellina

It is at bugs.python.  http://bugs.python.org/msg74595 .
--
http://mail.python.org/mailman/listinfo/python-list


Re: Porn Addiction Solutions?

2008-10-08 Thread Aaron &quot;Castironpi" Brady
On Oct 8, 2:07 pm, [EMAIL PROTECTED] wrote:
> Help, I'm addicted to porn. I've been spending a lot of time
> downloading hardcore porn and masturbating to it. It's ruining my
> life. I just found out that one of these sites somehow hacked my card
> and rang up $5K in charges which they won't even refund me. Even with
> that I haven't stopped my habit and it's only getting worse. How can I
> end this addiction?
>
> Any suggestions?

Do you want ideas for strategies for contending with it?  Do you want
to talk?  Do you want ideas for other places to find people to talk to?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-08 Thread Aaron &quot;Castironpi" Brady
On Oct 8, 7:21 pm, greg <[EMAIL PROTECTED]> wrote:
> Terry Reedy wrote:
> > str.find is an historical anomaly that should not be copied.  It
> > was(is?) a wrapper for C's string find function.  C routinely uses -1 to
> > mean None for functions statically typed to return ints.  The Python
> > version logically should return None and usually does for other functions.
>
...
> [I]t can
> be inconvenient having a function that returns different
> types under different circumstances.
...

No.  It has precedent and there is no cost to convenience in pure
Python.

Perhaps you are passing the result straight to a C extension, and
parsing it straight to integer, but I can't attest to how common that
use case is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Safe eval of insecure strings containing Python data structures?

2008-10-08 Thread Aaron &quot;Castironpi" Brady
On Oct 8, 7:34 pm, "Warren DeLano" <[EMAIL PROTECTED]> wrote:
> I would like to parse arbitrary insecure text string containing nested
> Python data structures in eval-compatible form:  
>
...
> # But I know for certain that the above approach is NOT secure since
> object attributes can still be accessed...
>
> So is there an equally convenient yet secure alternative available for
> parsing strings containing Python data structure definitions?
>
> Thanks in advance for any pointers!
>
> Cheers,
> Warren

As mentioned, I don't know if everything has been tried or how secure
what attempts have been.  I haven't seen this one:

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> del __builtins__
>>> a= [ x for x in (1).__class__.__bases__[0].__subclasses__() if x.__name__==
'file' ][ 0 ]
>>> a

>>> a('abc.txt','w')
Traceback (most recent call last):
  File "", line 1, in 
IOError: file() constructor not accessible in restricted mode
>>> import os
Traceback (most recent call last):
  File "", line 1, in 
ImportError: __import__ not found

So, at least one of the newsgroup favorites is gone.  Take a shot
though!  Maybe a variant would be sufficient.  No warranty.
--
http://mail.python.org/mailman/listinfo/python-list


inspect feature

2008-10-08 Thread Aaron &quot;Castironpi" Brady
Hello,

The 'inspect' module has this method:

inspect.getargvalues(frame)

It takes a frame and returns the parameters used to call it, including
the locals as defined in the frame, as shown.

>>> def f( a, b, d= None, *c, **e ):
... import inspect
... return inspect.getargvalues( inspect.currentframe() )
...
>>> f( 0, 1, 'abc', 'def', ( 3, 2 ), h= 'ghi' )
(['a', 'b', 'd'], 'c', 'e', {'a': 0, 'c': ('def', (3, 2)), 'b': 1,
'e': {'h': 'g
hi'}, 'd': 'abc', 'inspect': })

However, if you wanted a decorator that examines the parameters to a
function, you're out of luck.  By the time you have a frame, you're
already in the function.

Perhaps it would not be as common as something like 'join' for
example, or even the rest of the functions in 'inspect', but do you
think something similar to 'getargvalues' that accepted a function and
an argument list, and returned a dictionary mapping parameters to
values, could be useful?

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


inspect bug

2008-10-08 Thread Aaron &quot;Castironpi" Brady
Hi all,

Found this bug.  It's in 2.6, too bad.

Python 2.6 (r26:66721, Oct  2 2008, 11:35:03) [MSC v.1500 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> type( inspect.getargvalues( inspect.currentframe() ) )


Docs say:

inspect.getargvalues(frame)
...
Changed in version 2.6: Returns a named tuple ArgInfo(args, varargs,
keywords, locals).

The code defines an ArgInfo type, but doesn't instantiate it in the
return, as shown here:

return args, varargs, varkw, frame.f_locals
--
http://mail.python.org/mailman/listinfo/python-list


Re: type-checking support in Python?

2008-10-07 Thread Aaron &quot;Castironpi" Brady
On Oct 7, 3:52 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> (e.g., man-day-widgets for
> questions like, "If it takes one man three days to make two widgets, how
> many widgets can five men make in two weeks?").

Wouldn't that be 'widgets per man-day'?
--
http://mail.python.org/mailman/listinfo/python-list


Re: type-checking support in Python?

2008-10-07 Thread Aaron &quot;Castironpi" Brady
On Oct 7, 5:24 am, Bas <[EMAIL PROTECTED]> wrote:
> On Oct 7, 8:36 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
>
> central.gen.new_zealand> wrote:
> > In message <[EMAIL PROTECTED]>, Gabriel
>
> > Genellina wrote:
> > > As an example, in the oil industry here in my country there is a mix of
> > > measurement units in common usage. Depth is measured in meters, but pump
> > > stroke in inches; loads in lbs but pressures in kg/cm².
>
> > Isn't the right way to handle that to attach dimensions to each number?
>
> What they taught me as a physics undergrad is to always convert random
> units given as input to SI units as soon as possible, do all your
> calculations internally in SI units and (only if really needed)
> convert back to arbitrary units on output.
(snip)

If you think it's a potential source of error, a lightweight version
wouldn't be hard to implement.  This one is absolute minimal, using
strings for the units.  Multiplication is harder, since you want 'foot
pounds' == 'pound feet'.

>>> class UnitScalar:
... def __init__( self, val, type ):
... self.val, self.type= val, type
... def __add__( self, other ):
... assert self.type== other.type, 'Must be same type'
... return self.__class__( self.val+ other.val,
self.type )
... def __repr__( self ):
... return ''% ( self.val, self.type )
...
>>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'feet' )
>>> a+ b

>>> a, b= UnitScalar( 2, 'feet' ), UnitScalar( 3, 'inches' )
>>> a+ b
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 5, in __add__
AssertionError: Must be same type
--
http://mail.python.org/mailman/listinfo/python-list


Re: Race condition when generating .pyc files

2008-10-07 Thread Aaron &quot;Castironpi" Brady
On Oct 7, 10:21 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> I have a large body of Python code which runs on many different (Unix)
> machines concurrently.  Part of the code lives in one place, but most
> of it lives in directories which I find at runtime.  I only have one
> copy of each Python source file and I think I'm hitting a race
> condition where two hosts attempt to import the same module at the
> same time.  My import fails on one of the machines and the following
> exception is thrown:
> EOFError: EOF read where object expected
> My hypothesis is that there's contention between the two (or more)
> hosts when the module's .pyc file is generated.


Acquire an flock on the .py file, then compile it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Array of dict or lists or ....?

2008-10-07 Thread Aaron &quot;Castironpi" Brady
On Oct 7, 10:16 am, "Barak, Ron" <[EMAIL PROTECTED]> wrote:
> Would the following be suitable data structure:
> ...
> struct = {}
> struct["Nebraska"] = "Wabash"
> struct["Nebraska"]["Wabash"] = "Newville"
> struct["Nebraska"]["Wabash"]["Newville"]["topics"] = "Math"
> struct["Nebraska"]["Wabash"]["Newville"]["Math"]["Max Allowed Students"] = 20
> struct["Nebraska"]["Wabash"]["Newville"]["Math"]["Current enrolled Students"] 
> = 0
> ...

That's not quite right as stated.

>>> struct = {}
>>> struct["Nebraska"] = "Wabash"
>>> struct["Nebraska"]["Wabash"] = "Newville"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

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


Re: Python 2.6 / 3.0: Determining if a method is inherited

2008-10-06 Thread Aaron &quot;Castironpi" Brady
On Oct 6, 1:17 pm, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Oct 6, 7:01 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
> wrote:
> > It's a very object oriented solution.  Essentially you're inheriting
> > all the classes that you want to fail, from a class that does.
>
> But not a very good solution to the problem...
>
> The specific problem is to determine if an arbitrary class implements
> a specified comparison method. The general problem (that gives rise to
> the specific problem) is to write a class decorator that can implement
> all comparison methods from a class that implements only one.
>
> See:http://code.activestate.com/recipes/576529/
>
> Michael
> --http://www.ironpythoninaction.com/

Nope, I'm out of ideas, I'm afraid.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-06 Thread Aaron &quot;Castironpi" Brady
On Oct 6, 3:37 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Oct 5, 11:40 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> > Your point, that taking floor(log2(x)) is redundant, is a good catch.
> > However, you should have added 'untested' ;-).  When value has more
> > significant bits than the fp mantissa can hold, this expression can be 1
> > off (but no more, I assume).   The following correction should be
> > sufficient:
>
> > res = math.frexp(value)[1] - EXP_OF_ONE
> > test = 1< > if test > r:     res -= 1
> > elif 2*test < r: res += 1
>
> > For value = 2**n -1, n > 53, it is always 1 too high on my Intel
> > machine, so the first correction is sometimes needed.  I do not know if
> > the second is or not.
>
> See alsohttp://bugs.python.org/issue3439
> where there's a proposal to expose the _PyLong_NumBits method.  This
> would give an O(1) solution.
>
> Mark

That generates an odd error with ctypes.

>>> from ctypes import *
>>> _PyLong_NumBits= PYFUNCTYPE( c_int, py_object )( pythonapi._PyLong_NumBits )
>>> _PyLong_NumBits( 1<<50 )
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 295, in 'calling callback function'
ctypes.ArgumentError: argument 1: :
long int to
o long to convert
2227205
>>>

Seems 'ctypes' tries to call PyLong_AsUnsignedLong for you.  Anyone
know a way around it?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 / 3.0: Determining if a method is inherited

2008-10-06 Thread Aaron &quot;Castironpi" Brady
On Oct 6, 4:30 am, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Oct 6, 1:13 am, MRAB <[EMAIL PROTECTED]> wrote:
>
>
>
> > Fuzzyman wrote:
> > > Hello all,
>
> > > I may well be being dumb (it has happened before), but I'm struggling
> > > to fix some code breakage with Python 2.6.
>
> > > I have some code that looks for the '__lt__' method on a class:
>
> > > if hasattr(clr, '__lt__'):
>
> > > However - in Python 2.6 object has grown a default implementation of
> > > '__lt__', so this test always returns True.
>
> > > >>> class X(object): pass
> > > ...
> > > >>> X.__lt__
> > > 
> > > >>> X.__lt__ == object.__lt__
> > > False
>
> > > So how do I tell if the X.__lt__ is inherited from object? I can look
> > > in the '__dict__' of the class - but that doesn't tell me if X
> > > inherits '__lt__' from a base class other than object. (Looking inside
> > > the method wrapper repr with a regex is not an acceptable answer...)
>
> > > Some things I have tried:
>
> > > >>> X.__lt__.__self__
> > > 
> > > >>> dir(X.__lt__)
> > > ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__',
> > > '__format__', '__getattribute__', '__hash__', '__init__', '__name__',
> > > '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__',
> > > '__self__', '__setattr__', '__sizeof__', '__str__',
> > > '__subclasshook__']
> > > >>> X.__lt__.__func__
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > > AttributeError: 'method-wrapper' object has no attribute '__func__'
>
> > > Hmmm... I can get this working with Python 2.6 with:
>
> > > if '__lt__' in dir(cls):
>
> > > The default implementation of '__lt__' doesn't appear in the dir of
> > > classes. However this fails with Python 3 where the default
> > > implementation *does* appear in the output of 'dir'. Any suggestions?
>
> > Methods are objects. How do you know if two references refer to the
> > same object? You use "is":
>
> > X.__lt__ is object.__lt__
>
> Didn't you see that even an equality test fails - so they are not the
> same (that being the problem)...
>
> They are unbound method objects - in Python 3 the unbound method has
> gone away, so the problem is with Python 2.6.
>
> Michael
> --http://www.ironpythoninaction.com/

Not tested extensively.

class NoLTException( Exception ): pass

class NoLT( object ):
def __lt__( self, other ):
raise NoLTException()

class A( NoLT ):
pass

class B( A ):
def __lt__( self, other ):
return self

def test_lt( obj ):
try:
obj.__lt__( None )
except NoLTException:
return False
except:
pass
return True

>>> a= A()
>>> b= B()
>>> test_lt( a )
False
>>> test_lt( b )
True
>>>

This method won't work for arbitrary classes, only ones that you
control, that inherit from 'NoLT'.  The 'test_lt' function works by
trying to call '__lt__' on its argument.  The parameter to it doesn't
matter because of what happens next.  If '__lt__' raises a
NoLTException, you know it was inherited from NoLT.  Otherwise, even
if another exception occurs, the object you know has '__lt__'.

It's a very object oriented solution.  Essentially you're inheriting
all the classes that you want to fail, from a class that does.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lint for Python?

2008-10-05 Thread Aaron &quot;Castironpi" Brady
On Oct 5, 8:53 am, Pat <[EMAIL PROTECTED]> wrote:
> Miki wrote:
> > Hello,
>
> >> In module one, I have a function:
>
> >> def foo( host, userid, password ):
> >>      pass
>
> >> In module two, I call that function:
>
> >> foo( userid, password)
>
> >> lint doesn't find that error and it won't be caught until it's called
> >> while the program is running.
> > pychecker does find these kind of errors.
>
> Before posting my original question, I tried pychecker and it didn't
> catch that error.

Sorry for the multiple posting earlier (you heard me right, not 2 but
3 identical).  The basic checker of walking a parse tree, doing
imports by hand, and checking call signatures isn't awful.  60 lines.

/File:

from ng23mod1 import foo as foo
userid, password= 'abc', '123'
import random
foo( 'localhost', userid, password)
if random.uniform( 0, 1 )< .01: # 1 out of 100 times
foo( userid, password)

/Checker output:

foo ['Str', 'Name', 'Name'] found 3 expected
random ['Num', 'Num'] found 2 expected
foo ['Name', 'Name'] found 3 expected

But it's extremely delicate and at 60 lines only checks fixed-length
call signatures and functions, not even methods.  If you have a
statement:

x= y.z()

Then 'y' has to be defined somewhere, so you could make some educated
guesses that way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: When Python should not be used?

2008-10-05 Thread Aaron &quot;Castironpi" Brady
On Oct 5, 7:08 pm, Andrea Francia <[EMAIL PROTECTED]
HERE.ohoihihoihoih.TO-HERE.gmx.it> wrote:
> The right tool depends on the current problem.
>
> While some python users prefer to talk about when Python is the right
> tool I think that it is more instructive to know when it is not.
>
> Please, could you let me know what do you think about that?
>
> Thanks
> --
> Andrea 
> Franciahttp://andreafrancia.blogspot.com/2008/07/colinux-linux-dentro-window...

In a team situation when you need code and can't find discipline.  Its
freedom would only handicap you, and the restrictions static typing
has would help programmers keep their hands to themselves, more or
less enforcing function signatures and member visibility and so on.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6 / 3.0: Determining if a method is inherited

2008-10-05 Thread Aaron &quot;Castironpi" Brady
On Oct 5, 7:13 pm, MRAB <[EMAIL PROTECTED]> wrote:
> Fuzzyman wrote:
> > Hello all,
>
> > I may well be being dumb (it has happened before), but I'm struggling
> > to fix some code breakage with Python 2.6.
>
> > I have some code that looks for the '__lt__' method on a class:
>
> > if hasattr(clr, '__lt__'):
>
> > However - in Python 2.6 object has grown a default implementation of
> > '__lt__', so this test always returns True.
>
> > Hmmm... I can get this working with Python 2.6 with:
>
> Methods are objects. How do you know if two references refer to the
> same object? You use "is":
>
> X.__lt__ is object.__lt__

That doesn't work for me.

>>> class A( object ):
... pass
...
>>> class B( A ):
... def __lt__( self, other ):
... return self
...
>>> a= A()
>>> b= B()
>>> B.__lt__ is object.__lt__
False
>>> A.__lt__ is object.__lt__
False
>>>

Further, it's been noted before that

A().meth is not A().meth
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-05 Thread Aaron &quot;Castironpi" Brady
On Oct 5, 7:02 pm, Rich Healey <[EMAIL PROTECTED]> wrote:
> > P.S.  Back home, this sort of 'nitpicking' would be judged
> > unconstructive.  Worth pointing out, or not worth saying?
>
> > P.S.S.  'Thighest' bit?  I thought the spam filters would catch that.
>
> That should be P.P.S.
>
> PS: This is also unconstructive nitpicking.
>
> Kind regards
>
> Rich ;)

Hey, whatever gets the bills paid, friend.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the thighest bit position in big integers?

2008-10-05 Thread Aaron &quot;Castironpi" Brady
On Oct 5, 2:12 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
wrote:
> Duncan Booth wrote:
> > [EMAIL PROTECTED] wrote:
>
> > OFFSET = dict(("%x"%i, int(c)) for i,c in enumerate("5433"))
> > def get_highest_bit_num(r):
> >s = "%x"%r
> >return len(s) * 4 - OFFSET[s[0]]
>
> OFFSET= tuple( int(x) for x in "5433" )
> def get_highest_bit_num(r):
>  s = "%x"%r
>  return len(s) * 4 - OFFSET[int(s[0],16)]

That's really counterintuitive.  (That's the word, yes.)  They're both
function calls and both global variables.  Maybe you could use 'len(s)
* 4' to mask out the rest and lookup that index, rather than
converting -back- to integer.  Or, better yet, take 'ord' of s[0].
(Ha ha, -you- time it.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6: Determining if a method is inherited

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Fuzzyman wrote:

Hello all,

I may well be being dumb (it has happened before), but I'm struggling
to fix some code breakage with Python 2.6.

I have some code that looks for the '__lt__' method on a class:

if hasattr(clr, '__lt__'):

However - in Python 2.6 object has grown a default implementation of
'__lt__', so this test always returns True.


class X(object): pass

...

X.__lt__



X.__lt__ == object.__lt__

False

So how do I tell if the X.__lt__ is inherited from object? I can look
in the '__dict__' of the class - but that doesn't tell me if X
inherits '__lt__' from a base class other than object. (Looking inside
the method wrapper repr with a regex is not an acceptable answer...)


They're of different types.  I'm not sure how much you could use that, 
or how reliable it is.


>>> class A( object ):
... pass
...
>>> class B( object ):
... def __lt__( self, other ):
... pass
...
>>> hasattr( A, '__lt__' )
True
>>> hasattr( B, '__lt__' )
True
>>> A.__lt__

>>> B.__lt__

>>>

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


Re: del and sets proposal

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Bruno Desthuilliers wrote:

Steven D'Aprano a écrit :

On Sat, 04 Oct 2008 18:36:28 +0200, Bruno Desthuilliers wrote:

Lists are the odd one out, because del alist[x] is used to remove the 
element at position x, rather than removing an element x.


Nope. It's perfectly consistent with dicts, where del adict[x] is used 
to remove element associated to key x, not to remove element with value 
x. Lists and dicts are both indexed collections, list being indexed by 
position and dicts by key. sets are not indexed.


(snip remaining - I could only keep on repeating the same thing).
--
http://mail.python.org/mailman/listinfo/python-list


Which one has seniority?  It's somewhat arbitrary which of 'pop' and 
'remove' have which meanings in lists.  You can 'remove' on index or 
value in lists, key or value in dicts, and only value in sets.


I agree that you don't pass an 'index' to 'del' in dicts, you pass a 
key.  Does the OP also hold that dicts should grow a 'remove' method to 
remove a value?


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


Re: how to get the thighest bit position in big integers?

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Duncan Booth wrote:

[EMAIL PROTECTED] wrote:


My question to the group: Does anyone know of a non-hackish way to
determine the required bit position in python? I know that my two
ideas
can be combined to get something working. But is there a *better* way,
that isn't that hackish?


How about using the hex representation of the value?

OFFSET = dict(("%x"%i, int(c)) for i,c in enumerate("5433"))
def get_highest_bit_num(r):
s = "%x"%r
return len(s) * 4 - OFFSET[s[0]]
--
http://mail.python.org/mailman/listinfo/python-list



You can replace the dict if it's faster.

OFFSET= tuple( int(x) for x in "5433" )
def get_highest_bit_num(r):
s = "%x"%r
return len(s) * 4 - OFFSET[int(s[0],16)]

P.S.  Back home, this sort of 'nitpicking' would be judged 
unconstructive.  Worth pointing out, or not worth saying?


P.S.S.  'Thighest' bit?  I thought the spam filters would catch that.

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


Re: lint for Python?

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Pat wrote:
I've been searching for a good multi-module lint checker for Python and 
I haven't found one yet.


Pylint does a decent job at checking for errors only within a single 
module.


Here's one of my problems.  I have two modules.

In module one, I have a function:

def foo( host, userid, password ):
pass

In module two, I call that function:

foo( userid, password)

lint doesn't find that error and it won't be caught until it's called 
while the program is running.  I don't want that error found at 3AM.


I've never used a language that didn't catch that type of error.  I'm 
quite surprised that Python is being used by a number of major 
companies.  How you catch these types of errors?


I've spoken to tech support at Wing and they weren't aware of a 
multi-module lint but they're considering putting their own lint into 
their IDE.


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



The example you gave is specific.  You could catch that one by hand.
But, would it hurt, perhaps by causing neglect of other errors; and
would it be worth the effort?  And, if you're using any dynamics at all,
catching that one's even in question.

from mod import foo
bar= foo
bar( arg1, arg2 )

It would add difficulty to catching by hand.  Same with variable
argument lists.

from mod import foo
args= ( arg1, arg2 )
foo( *args )

If you could knock off an error and ignore the false positives, that
might be worth an afternoon.




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


Re: lint for Python?

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Pat wrote:
I've been searching for a good multi-module lint checker for Python and 
I haven't found one yet.


Pylint does a decent job at checking for errors only within a single 
module.


Here's one of my problems.  I have two modules.

In module one, I have a function:

def foo( host, userid, password ):
pass

In module two, I call that function:

foo( userid, password)

lint doesn't find that error and it won't be caught until it's called 
while the program is running.  I don't want that error found at 3AM.


I've never used a language that didn't catch that type of error.  I'm 
quite surprised that Python is being used by a number of major 
companies.  How you catch these types of errors?


I've spoken to tech support at Wing and they weren't aware of a 
multi-module lint but they're considering putting their own lint into 
their IDE.


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



The example you gave is specific.  You could catch that one by hand.
But, would it hurt, perhaps by causing neglect of other errors; and
would it be worth the effort?  And, if you're using any dynamics at all,
catching that one's even in question.

from mod import foo
bar= foo
bar( arg1, arg2 )

It would add difficulty to catching by hand.  Same with variable
argument lists.

from mod import foo
args= ( arg1, arg2 )
foo( *args )

If you could knock off an error and ignore the false positives, that
might be worth an afternoon.




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


Re: lint for Python?

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Pat wrote:
I've been searching for a good multi-module lint checker for Python and 
I haven't found one yet.


Pylint does a decent job at checking for errors only within a single 
module.


Here's one of my problems.  I have two modules.

In module one, I have a function:

def foo( host, userid, password ):
pass

In module two, I call that function:

foo( userid, password)

lint doesn't find that error and it won't be caught until it's called 
while the program is running.  I don't want that error found at 3AM.


I've never used a language that didn't catch that type of error.  I'm 
quite surprised that Python is being used by a number of major 
companies.  How you catch these types of errors?


I've spoken to tech support at Wing and they weren't aware of a 
multi-module lint but they're considering putting their own lint into 
their IDE.


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



The example you gave is specific.  You could catch that one by hand. 
But, would it hurt, perhaps by causing neglect of other errors; and 
would it be worth the effort?  And, if you're using any dynamics at all, 
catching that one's even in question.


from mod import foo
bar= foo
bar( arg1, arg2 )

It would add difficulty to catching by hand.  Same with variable 
argument lists.


from mod import foo
args= ( arg1, arg2 )
foo( *args )

If you could knock off an error and ignore the false positives, that 
might be worth an afternoon.




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


Re: 2to3 refactoring [was Re: Tuple parameter unpacking in 3.x]

2008-10-05 Thread Aaron &quot;Castironpi" Brady

Steven D'Aprano wrote:
PEP 3113 offers the following recommendation for refactoring tuple 
arguments:


def fxn((a, (b, c))):
pass

will be translated into:

def fxn(a_b_c):
(a, (b, c)) = a_b_c
pass

and similar renaming for lambdas. 
http://www.python.org/dev/peps/pep-3113/



I'd like to suggest that this naming convention clashes with a very 
common naming convention, lower_case_with_underscores. That's easy enough 
to see if you replace the arguments a, b, c above to something more 
realistic:


def function(vocab_list, (result, flag), max_value)

becomes:

def function(vocab_list, result_flag, max_value)

Function annotations may help here, but not everyone is going to use them 
in the same way, or even in a way that is useful, and the 2to3 tool 
doesn't add annotations.


It's probably impossible to avoid all naming convention clashes, but I'd 
like to suggest an alternative which distinguishes between a renamed 
tuple and an argument name with two words:


def function(vocab_list, (result, flag), max_value):
pass

becomes:

def function(vocab_list, t__result_flag, max_value):
result, flag = t__result_flag
pass

The 't__' prefix clearly marks the tuple argument as different from the 
others. The use of a double underscore is unusual in naming conventions, 
and thus less likely to clash with other conventions. Python users are 
already trained to distinguish single and double underscores. And while 
it's three characters longer than the current 2to3 behaviour, the length 
compares favorably with the original tuple form:


t__result_flag
(result, flag)

What do people think? Is it worth taking this to the python-dev list?




There's the possibility that the most important words should go first in 
this case:


result_flag__t

But, I'll admit that other people could have learned different orders of 
scanning words than I, especially depending on their spoken language 
backgrounds.  A poll of the newsgroup isn't exactly academically 
impartial sampling, but there aren't any better ways to make decisions, 
are there?  (I think it would be easy to make either one a habit.)


Here's the other option in the same context:

def function(vocab_list, result_flag__t, max_value):
result, flag = result_flag__t
pass

To be thorough, there's also a trailing double underscore option.

def function(vocab_list, result_flag__, max_value):
result, flag = result_flag__
pass

Which I don't recognize from any other usages, but I defer.  If there 
aren't any, conditionally, I think this is my favorite.


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


Re: One class per file?

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 1:51 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> greg a écrit :
>
> > Bruno Desthuilliers wrote:
>
> >> OTHO, 'one class per file' is a standard idiom in Java and IIRC in C++
> >> (which both have namespaces one way or another)
>
> > In Java you don't get a choice, because the compiler
> > assumes a class can be found in the correspondingly
> > named file.
>
> For public classes only.
>
>
>
> > While C++ has namespaces, they don't have any defined
> > relationship to source files, so they don't help you
> > find which file something is defined in.
>
> Nope. But IIRC, one-class-per-file helps saving on compile/link time. A
> problem we don't have with dynamic languages !-)

I think that one goes in the 'handcuffs' category.  You are free to
adopt the idiom if you want, aren't required to.  (Though doesn't the
freedom handcuff later users of your code?)

Besides, it's not always clear what method in an inheritance tree is
getting called, so 'one class per file' doesn't guarantee you can find
an operation.

With 'exec( "class %s:\n..." )' statements and 'def f(): / class X: /
return X' statements, you don't even know all your classes at
startup.  And not to mention 'namedtuple's certainly make the idiom
impractical in at least corner cases.

(But, when you need code and can't find discipline, maybe 'inside-the-
box' restrictions can bring your goal closer, no?)
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 3:47 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> greg wrote:
> > jhermann wrote:
>
> >> I didn't see this mentioned in the thread yet: the double-lambda is
> >> unnecessary (and a hack).
>
> > Well, the alternative -- abusing default argument values --
> > is seen by many to be a hack as well, possibly a worse one.
>
> I disagree.  It is one way to evaluate an expression when a function is
> compiled.
>
> > It doesn't work in general, e.g. it fails if the function
> > needs to be called with a variable number of arguments.
>
> So?  Many things do not work 'in general'. If one wants multiple
> closures with a variable number of arguments, one should use a def
> statement and some other binding method, such as given below
>
> Here are four ways to get the list of closures desired:
> All print 0 ... 9 with for f in lst:  print(f()) #3.0
>
> lst = []
> for i in range(10):
>      lst.append(eval("lambda: %d" %i))
>
> # use exec instead of eval with def statement instead of lambda expression
>
> lst = []
> def f(i): return lambda: i
> for i in range(10):
>      lst.append(f(i))
>
> #I would most likely use this, with a def instead of lambda inside f for
> any real, non-trivial example.
>
> def populate(n):
>    n -= 1
>    if n >= 0: return populate(n)+[lambda:n]
>    else: return []
> lst = populate(10)
>
> # body recursion
>
> def populate(i,n,lst):
>      if i < n: return populate(i+1,n,lst+[lambda:i])
>      else: return lst
> lst = populate(0,10,[])
>
> # tail recursion
>
> Terry Jan Reedy

Is there a way to get at the 'reduce' / 'setstate' mechanism that
pickle uses without going through the serialization?  I.e. doing a
serial round trip?

In either case, 'copy' module or 'loads( dumps( obj ) )' gets you a
copy of the object, but 'def' is the only way to get its own namespace.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a class instance name during creation?

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 1:46 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> dmitrey a écrit :
>
> > hi all,
> > I have a code
> > z = MyClass(some_args)
> > can I somehow get info in MyClass __init__ function that user uses "z"
> > as name of the variable?
>
> > I.e. to have __init__ function that creates field z.name with value
> > "z".
>
> This has been debated to hell and back. To make a long story short, here
> are two common use cases:
>
> x = MyClass()
> y = x
> del x
>
> objects = [MyClass() for i in range(100)]
>
> If you can come with a meaningfull answer to "what's *the* name of any
> of the MyClass instance(s)" in both cases, then please let us know...

Hmmm, just thinking:

What about a function:

autoname( 'x= MyClass' )

which calls exec as well as determines the name?  That could use
'code' and 'ast' modules and 'parse', or just take the first \w
characters, assuming assignment, or:

autoname( 'x', MyClass() )

which executes assignment and sets an attr or calls a method on the
second arg.
--
http://mail.python.org/mailman/listinfo/python-list


Re: execute a function before and after any method of a parent class

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 9:03 am, TP <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> I would like to be able to specialize an existing class A, so as to obtain a
> class B(A), with all methods of B being the methods of A preceded by a
> special method of B called _before_any_method_of_A( self ), and followed by
> a special method of B called _after_any_method_of_A( self ).
>
> The goal is to avoid to redefine explicitly in B all methods of A.
>
> Is this possible in Python?
>
> Thanks a lot
>
> Julien
>
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
> (55l4('])"
>
> "When a distinguished but elderly scientist states that something is
> possible, he is almost certainly right. When he states that something is
> impossible, he is very probably wrong." (first law of AC Clarke)

Yes it's possible.  The exact solution depends on how much control you
want, and over what.  Do you want inheritance or delegation?  Do you
want the same pre and post method for all inherited methods?  Will you
always use single-inheritance?  Would you mind using a list of names,
as a sort of midpoint between complete redefinition and completely
dynamic?  Do you want class lookups to succeed?  If so, what do you
want them to do?

Generally, you could build the class dynamically with a metaclass, or
use __getattr__ a lookup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 5:10 am, "Tim Rowe" <[EMAIL PROTECTED]> wrote:
> 2008/9/30 Lie Ryan <[EMAIL PROTECTED]>:
>
> > Actually str.len and len(str) is just like saying "the string's length"
> > and "the length of the string". There is no difference between the two
> > except for personal preference. (I am no linguist-- not even a native
> > speaker of English --but I think there is a subtle difference on
> > emphasis, "the string's length" emphasizes on the length being string's
> > property, while "the length of the string" emphasizes on the length
> > itself, am I correct?)
>
> Well, I'm doing a linguistics degree, so I'm not a linguist /yet/, but
> I think I know this one. There is the difference in emphasis that you
> mention, but there may be something more significant. In both forms,
> "length" is what linguists call the "head" of the noun phrase: it's
> the actual thing being talked about.  In "The string's length" the
> head is only pre-modified ("the string's" comes before the head and
> there's nothing after the head). "The length of the string" has both
> pre- and post- modification ("The" before, "of the string" after).
> Post modification in noun phrases has been measured to be much less
> frequent in spoken English than in written English, and it gets
> progressively more common as the writing style gets more formal.  That
> suggests that "the string's length" is an easier phrase to produce and
> understand, but "the length of the string" sounds more official.
>
> --
> Tim Rowe

... Unless, there is some corresponding distinction in mechanics
between speaking and writing.  That is, if something about the process
of generating writing makes it, post-modification, easier.  I'm going
to assume that it's been observed across all modes of writing too, (in
addition to across all formality levels), where in all cases it was
equally easy to go back and edit, which is impossible in speech.  And,
in the cases where the entire process of writing was observed, that
neither kind of modification occurred more frequently in revisions.
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-10-03 Thread Aaron &quot;Castironpi" Brady
On Oct 3, 3:44 am, greg <[EMAIL PROTECTED]> wrote:
> jhermann wrote:
> > I didn't see this mentioned in the thread yet: the double-lambda is
> > unnecessary (and a hack).
>
> Well, the alternative -- abusing default argument values --
> is seen by many to be a hack as well, possibly a worse one.
> It doesn't work in general, e.g. it fails if the function
> needs to be called with a variable number of arguments.
>
> The double lambda is conceptually more sound in some
> ways, and can be made to work correctly in all cases.
>
> The root of the problem actually has nothing to do with
> lambdas or static vs. non-static scoping. It's the fact
> that Python's for-loop doesn't create a new environment
> for the loop variable each time around, but re-uses a
> slot in the containing environment.
>
> Contrast this with Scheme, where the equivalent of a
> for-loop *does* create a new environment for each
> value of the loop variable. Effectively it's using a
> double lambda, except that one of the lambdas is
> folded into the syntax of the loop, so you don't
> notice it.
>
> So if anything were to be done to the language to
> fix this, it really should be focused on fixing the
> semantics of the for-loop. Unfortunately, the
> fact that the loop variable leaks out of the scope
> of the loop is regarded as a feature, so anything
> which changes that seems to be a non-starter.
>
> --
> Greg

I agree that the default argument syntax is an abuse, but it
accomplishes exactly what I want: to create a copy of a namespace.  I
don't think there's a way to create a closure in Python without
another function, so you might need new syntax if you wanted to.

Otherwise, using function syntax, I want a new namespace on each
iteration that nests inside the old one, except for one variable which
overrides the outer scope.  I agree that a new variable isn't the
obviously correct meaning of a for loop, and functions are the same as
a new scope, just you have to call them, so why not use them as is?

(untested)
for i in range( 3 ):
  def f( n ):
def g( ):
  return n
  return g
  closures[ i ]= f( i )

Or:

(non-standard)
for i in range( 3 ):
  closure f( i ):
def g( ):
  return i
  return g
  closures[ i ]= f

Here the only difference is whether you call 'f' or not.  'closure'
would theoretically "call itself", and make a copy of its scope upon
execution of the definition, overriding the arguments.  So, functions
are the same.
--
http://mail.python.org/mailman/listinfo/python-list


2.6 multiprocessing and pdb

2008-10-02 Thread Aaron &quot;Castironpi" Brady
Hi,

I'm trying to step through a subprocess I launch with
multiprocessing.  Does anyone know what hack to add?  The actual call
comes in forking.Popen.__init__, Windows version, forking.py, line
222:

hp, ht, pid, tid = _subprocess.CreateProcess(
_python_exe, cmd, None, None, 1, 0, None, None, None
)

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


Re: Inheritance but only partly?

2008-10-02 Thread Aaron &quot;Castironpi" Brady
On Oct 2, 3:16 pm, process <[EMAIL PROTECTED]> wrote:
> Let's say I have a class X which has 10 methods.
>
> I want class Y to inherit 5 of them.
>
> Can I do that? Can I do something along the lines of super(Y, exclude
> method 3 4 7 9 10) ?

That implies that the 5 you do include don't rely on or call the 5 you
don't.  Otherwise you have to inherit them.  Then you can refactor
them into:

class X5YouDo: ...
class X5YouDont: ...
class X( X5YouDo, X5YouDont ): ...
class Y( X5YouDo ): ...

If you're looking for restricted visibility, Python does not have it.
It's just handcuffs, and makes things you can't do.

After all, nothing would stop you user from calling:

y= Y()
X5YouDont.DontInheritMe( y, args )

to get at the uninherited methods.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how best to use a dictionary in this function?

2008-10-02 Thread Aaron &quot;Castironpi" Brady
On Oct 2, 4:18 am, Terrence Brannon <[EMAIL PROTECTED]> wrote:
> Ok, here is some code:
>
> def calc_profit(std_clicks, vip_clicks, ad_rate=200,
> upline_status=None):
>     payout = {}
>     payout_std = std_clicks * rates['std'].per_click
>     payout_vip = vip_clicks * rates['vip'].per_click
>
> ... now note that std_clicks and vip_clicks are passed to the
> function.
>
> Now, I improved this function this way:
>
> def calc_profit(std_clicks, vip_clicks, ad_rate=200,
> upline_status=None):
>     clicks = {}
>     clicks['std'] = std_clicks
>     clicks['vip'] = vip_clicks
>
>     payout = {}
>     for member_type in rates:
>         payout[member_type] = clicks[member_type] *
> rates[member_type].per_click
>
> But it seems wasteful to have to re-bind the passed-in function args
> to a dictionary in the function. I think there must be some way to
> improve this code and get the dictionary built without me manually
> doing it...
>
> I know there is something like *args, or **args, but since
> docs.python.org is down, I cant check.

*args is for variable-length parameters, **args is for keyword
parameters.

>>> def f( **kwar ):
... print kwar
...
>>> f( a=2, b=3 )
{'a': 2, 'b': 3}
>>> f( 123 )
Traceback (most recent call last):
  File "", line 1, in 
TypeError: f() takes exactly 0 arguments (1 given)
>>> f( a='abc' )
{'a': 'abc'}
--
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can't pickle HASH objects?

2008-10-02 Thread Aaron &quot;Castironpi" Brady
On Oct 2, 4:03 am, est <[EMAIL PROTECTED]> wrote:
> On Oct 2, 4:22 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote:
>
> > > On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote:
>
> > > > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote:
> > > > > wow. It's giga-size file. I need stream reading it, md5 it. It may
> > > > > break for a while.
>
> > > > So use generators and consume the stream ?
>
> > > > --JamesMills
>
> > > > --
> > > > --
> > > > -- "Problems are solved by method"
>
> > > no, I need to serialize half-finished digest, not file stream.
>
> > > Anyone got solution?
>
> > I am looking at '_hashopenssl.c'.  If you can find the implementation
> > of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes
> > hack to store and write its state.- Hide quoted text -
>
> > - Show quoted text -
>
> http://cvs.openssl.org/fileview?f=openssl/crypto/evp/digest.c
>
> int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data,
>              size_t count)
>         {
> #ifdef OPENSSL_FIPS
>         FIPS_selftest_check();
> #endif
>         return ctx->digest->update(ctx,data,count);
>         }
>
> is this one?

Oops, I needed 'EVP_MD_CTX'.  I went Googling and found it.

http://www.google.com/codesearch?hl=en&q=struct+EVP_MD_CTX+show:mV3VBLQ3bJg:LiPTUi2tojQ:CERf4Pk7bsY&sa=N&cd=5&ct=rc&cs_p=http://freshmeat.net/redir/cyassl/67102/url_zip/cyassl-0.6.2.zip&cs_f=cyassl-0.8.5/include/openssl/evp.h#l51

But does Gabriel's work for you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can't pickle HASH objects?

2008-10-02 Thread Aaron &quot;Castironpi" Brady
On Oct 2, 2:44 am, est <[EMAIL PROTECTED]> wrote:
> On Oct 2, 1:51 pm, "James Mills" <[EMAIL PROTECTED]> wrote:
>
> > On Thu, Oct 2, 2008 at 3:34 PM, est <[EMAIL PROTECTED]> wrote:
> > > wow. It's giga-size file. I need stream reading it, md5 it. It may
> > > break for a while.
>
> > So use generators and consume the stream ?
>
> > --JamesMills
>
> > --
> > --
> > -- "Problems are solved by method"
>
> no, I need to serialize half-finished digest, not file stream.
>
> Anyone got solution?

I am looking at '_hashopenssl.c'.  If you can find the implementation
of EVP_DigestUpdate, I'll give it a shot to help you write a ctypes
hack to store and write its state.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Odd Errors

2008-10-02 Thread Aaron &quot;Castironpi" Brady
On Oct 2, 12:52 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message <[EMAIL PROTECTED]>, Steven
>
> D'Aprano wrote:
> > On Wed, 01 Oct 2008 22:14:49 +1300, Lawrence D'Oliveiro wrote:
>
> >> In message
> >> <[EMAIL PROTECTED]>,
> >> Aaron "Castironpi" Brady wrote:
>
> >>> Do you ever want to scream from the rooftops, "'append' operates by
> >>> side-effect!"?
>
> >> No. It's an effect, not a side-effect.
>
> > "Side-effect" has the technical meaning in functional languages of any
> > change of state that isn't the creation and return of a function result.
>
> "Side" means that it happens as the by-product of returning a function
> result. ".append" isn't a function, it's a procedure. Hence the
> modification of the list is the primary effect, not a side effect.

I was using the technical definition from functional languages, not
the literal "per word" definition.  Maybe the FL crowd chose their
words poorly, who knows?
--
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: can't pickle HASH objects?

2008-10-01 Thread Aaron &quot;Castironpi" Brady
On Oct 1, 2:50 pm, est <[EMAIL PROTECTED]> wrote:
> >>> import md5
> >>> a=md5.md5()
> >>> import pickle
> >>> pickle.dumps(a)
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\pickle.py", line 1366, in dumps
>     Pickler(file, protocol).dump(obj)
>   File "C:\Python25\lib\pickle.py", line 224, in dump
>     self.save(obj)
>   File "C:\Python25\lib\pickle.py", line 306, in save
>     rv = reduce(self.proto)
>   File "C:\Python25\lib\copy_reg.py", line 69, in _reduce_ex
>     raise TypeError, "can't pickle %s objects" % base.__name__
> TypeError: can't pickle HASH objects
>
> Why can't I pickle a md5 object? Is it because md5 algorithm needs to
> read 512-bits at a time?
>
> I need to md5() some stream, pause(python.exe quits), and resume
> later.  It seems that the md5 and hashlib in  std module could not be
> serialized?
>
> Do I have to implement md5 algorithm again for this special occasion?
>
> Or is there anyway to assige a digest when creating md5 objects?

Can you just pickle the stream, the part of it you've read so far?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Peek inside iterator (is there a PEP about this?)

2008-10-01 Thread Aaron &quot;Castironpi" Brady
On Oct 1, 3:14 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Luis Zarrabeitia wrote:
> > Hi there.
>
> > For most use cases I think about, the iterator protocol is more than enough.
> > However, on a few cases, I've needed some ugly hacks.
>
> > Ex 1:
>
> > a = iter([1,2,3,4,5]) # assume you got the iterator from a function and
> > b = iter([1,2,3])     # these two are just examples.
>
> > then,
>
> > zip(a,b)
>
> > has a different side effect from
>
> > zip(b,a)
>
> > After the excecution, in the first case, iterator a contains just [5], on 
> > the
> > second, it contains [4,5]. I think the second one is correct (the 5 was 
> > never
> > used, after all). I tried to implement my 'own' zip, but there is no way to
> > know the length of the iterator (obviously), and there is also no way
> > to 'rewind' a value after calling 'next'.
>
> Interesting observation.  Iterators are intended for 'iterate through
> once and discard' usages.  To zip a long sequence with several short
> sequences, either use itertools.chain(short sequences) or put the short
> sequences as the first zip arg.
>
> > Ex 2:
>
> > Will this iterator yield any value? Like with most iterables, a construct
>
> > if iterator:
> >    # do something
>
> > would be a very convenient thing to have, instead of wrapping a 'next' call 
> > on
> > a try...except and consuming the first item.
>
> To test without consuming, wrap the iterator in a trivial-to-write
> one_ahead or peek class such as has been posted before.
>
> > Ex 3:
>
> > if any(iterator):
> >    # do something ... but the first true value was already consumed and
> >    # cannot be reused. "Any" cannot peek inside the iterator without
> >    # consuming the value.
>
> If you are going to do something with the true value, use a for loop and
> break.  If you just want to peek inside, use a sequence (list(iterator)).
>
> > Instead,
>
> > i1, i2 = tee(iterator)
> > if any(i1):
> >    # do something with i2
>
> This effectively makes two partial lists and tosses one.  That may or
> may not be a better idea.
>
> > Question/Proposal:
>
> > Has there been any PEP regarding the problem of 'peeking' inside an 
> > iterator?
>
> Iterators are not sequences and, in general, cannot be made to act like
> them.  The iterator protocol is a bare-minimum, least-common-denominator
> requirement for inter-operability.  You can, of course, add methods to
> iterators that you write for the cases where one-ahead or random access
> *is* possible.
>
> > Knowing if the iteration will end or not, and/or accessing the next value,
> > without consuming it? Is there any (simple, elegant) way around it?
>
> That much is trivial.  As suggested above, write a wrapper with the
> exact behavior you want.  A sample (untested)
>
> class one_ahead():
>    "Self.peek is the next item or undefined"
>    def __init__(self, iterator):
>      try:
>        self.peek = next(iterator)
>        self._it = iterator
>      except StopIteration:
>        pass
>    def __bool__(self):
>      return hasattr(self, 'peek')
>    def __next__(self): # 3.0, 2.6?
>      try:
>        next = self.peek
>        try:
>          self.peek = next(self._it)
>        except StopIteration:
>          del self.peek
>        return next
>      except AttrError:
>        raise StopIteration
>
> Terry Jan Reedy

Terry's is close.  '__nonzero__' instead of '__bool__', missing
'__iter__',  'next', 'self._it.next( )' in 2.5.

Then just define your own 'peekzip'.  Short:

def peekzip( *itrs ):
while 1:
if not all( itrs ):
raise StopIteration
yield tuple( [ itr.next( ) for itr in itrs ] )

In some cases, you could require 'one_ahead' instances in peekzip, or
create them yourself in new iterators.

Here is your output: The first part uses zip, the second uses peekzip.

[(1, 1), (2, 2), (3, 3)]
5
[(1, 1), (2, 2), (3, 3)]
4

4 is what you expect.

Here's the full code.

class one_ahead(object):
"Self.peek is the next item or undefined"
def __init__(self, iterator):
try:
self.peek = iterator.next( )
self._it = iterator
except StopIteration:
pass
def __nonzero__(self):
return hasattr(self, 'peek')
def __iter__(self):
return self
def next(self): # 3.0, 2.6?
try:
next = self.peek
try:
self.peek = self._it.next( )
except StopIteration:
del self.peek
return next
except AttributeError:
raise StopIteration


a= one_ahead( iter( [1,2,3,4,5] ) )
b= one_ahead( iter( [1,2,3] ) )
print zip( a,b )
print a.next()

def peekzip( *itrs ):
while 1:
if not all( itrs ):
raise StopIteration
yield tuple( [ itr.next( ) for itr in itrs ] )

a= one_ahead( iter( [1,2,3,4,5] ) )
b= one_ahead( iter( [1,2,3] ) )
print list( peekzip( a,b ) )
print a.next()

There's one more option, which is to create your own 'push-backable'
class, which 

Re: Peek inside iterator (is there a PEP about this?)

2008-10-01 Thread Aaron &quot;Castironpi" Brady
On Oct 1, 9:46 am, Luis Zarrabeitia <[EMAIL PROTECTED]> wrote:
> Hi there.
>
> For most use cases I think about, the iterator protocol is more than enough.
> However, on a few cases, I've needed some ugly hacks.
>
> Ex 1:
>
> a = iter([1,2,3,4,5]) # assume you got the iterator from a function and
> b = iter([1,2,3])     # these two are just examples.
>
> then,
>
> zip(a,b)
>
> has a different side effect from
>
> zip(b,a)
>
> After the excecution, in the first case, iterator a contains just [5], on the
> second, it contains [4,5]. I think the second one is correct (the 5 was never
> used, after all). I tried to implement my 'own' zip, but there is no way to
> know the length of the iterator (obviously), and there is also no way
> to 'rewind' a value after calling 'next'.
>
> Ex 2:
>
> Will this iterator yield any value? Like with most iterables, a construct
>
> if iterator:
>    # do something
>
> would be a very convenient thing to have, instead of wrapping a 'next' call on
> a try...except and consuming the first item.
>
> Ex 3:
>
> if any(iterator):
>    # do something ... but the first true value was already consumed and
>    # cannot be reused. "Any" cannot peek inside the iterator without
>    # consuming the value.
>
> Instead,
>
> i1, i2 = tee(iterator)
> if any(i1):
>    # do something with i2
>
> Question/Proposal:
>
> Has there been any PEP regarding the problem of 'peeking' inside an iterator?
> Knowing if the iteration will end or not, and/or accessing the next value,
> without consuming it? Is there any (simple, elegant) way around it?
>
> Cheers,
>
> --
> Luis Zarrabeitia (aka Kyrie)
> Fac. de Matemática y Computación, UH.http://profesores.matcom.uh.cu/~kyrie

It wouldn't be that hard to make your own.

a = peekingiter([1,2,3,4,5])
b = peekingiter([1,2,3])

Just don't cross it with typing and get peking duck.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-10-01 Thread Aaron &quot;Castironpi" Brady
On Sep 30, 7:39 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano wrote:
> > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote:
>
> >>> Why isn't len implemented as a str.len and list.len method instead of a
> >>> len(list) function?
> >> Because postfix notation sucks.  The natural way of spelling is
> >> adjective+noun and verb+predicate.
>
> > "Natural"?
>
> > You mean phrases like "heir apparent" and "worst choice imaginable" are
> > unnatural?
>
> They are certainly far from normal usage, as my dog yellow would be
> certain to agree.
>
> > To say nothing of languages like Spanish, Albanian, Italian,
> > Cornish, Vietnamese, Hebrew...
>
> It's long been a convention in the Western programming world to pretend
> no other language than English and no other codes than ASCII exist.
>
> The fact that Python is beginning to come to terms with Unicode is a
> tribute to certain developers' persistence.
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/

How do you have a yellow dog, and what does s/he know about natural
noun-verb usage?
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-10-01 Thread Aaron &quot;Castironpi" Brady
On Oct 1, 5:43 am, jhermann <[EMAIL PROTECTED]> wrote:
> I didn't see this mentioned in the thread yet: the double-lambda is
> unnecessary (and a hack). What you should do when you need early
> binding is... early binding. ;)
>
> Namely:
>
> f = [lambda n=n: n for n in range(10)]
> print f[0]()
> print f[1]()
>
> Note the "n=n", this prints 0 and 1 instead of 9/9.

Yes it was mentioned earlier.  I think its similar.  They both create
ten new namespaces.  You could do something like this (I hit a bump
with eval and globals() when I tried it):

def early( string ):
   return eval( string, current_namespace )

f = [early( 'lambda: n' ) for n for n in range(10)]
print f[0]()
print f[1]()

Furthermore, I don't think the binding semantics of the language are
completely static binding.  What does that definition say about
mutating a value?  I think it's ambiguous and there's no obvious use
case that favors either one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Music knowledge representation

2008-09-29 Thread Aaron &quot;Castironpi" Brady
On Sep 29, 3:56 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> On Mon, 29 Sep 2008 20:29:44 +0200
>
> "Mr.SpOOn" <[EMAIL PROTECTED]> wrote:
> > > Couldn't the note class simply have a list of all the notes and have a
> > > simple method calculate the actual pitch?
>
> > That's not really how it works. There exists just 12 octave
> > independent pitch classes. This means that there is a pitch class C
> > with all possible Cs. There ambiguities with accidentals, because
> > different named notes fall in the same pitch class. The difference is
> > important for the musical theory, because C# and Db belongs to the
> > same pitch class (actually they are the same note, they sounds
> > completely identical -- because on the piano you play them pressing
> > the same key), but in a scale they have a very different role.
>
> Sure, they are enharmonically identical but in our tempered scale.
> That's why my example showed it as (note, octave, accidental) rather
> than a specific note.  It would differentiate between these.
>
> > For example, the interval C F# is an "augmented fourth", because what
> > really matters are the natural note (C and F), and their distance if
> > 4. Then it is augmented due to the #-
>
> > But the interval C Gb (Gb is the same as F#) is a "diminished fifth".
>
> This is true.  My simple example would not have dealt with this.  The
> arguments would have to be the full tuple rather than the actual pitch.
>
> > So I can't list all pitches.
>
> You can but you can't store them as raw pitches.
>
> > >    def interval(self, lower, higher)
> > >        if lower > higher:
> > >            # uncomment one of the two following lines depending
> > >            # on the behaviour you want
> > >            #lower,higher = higher,lower
> > >            #higher += 12
>
> > >        # could use some error trapping
> > >        return self.interval_name[higher - lower]
>
> > > Note that lower and higher could be a note object that you have to
> > > convert to integers first.
>
> > I can't estabilish which note is higher, because all the analysis part
> > is octave independent. Anyway thanks for the ideas.
>
> I'm not sure I understand this.  You either have to assume that the
> first note is the root or the lower one is.  What other options are
> there?  It sounds like your requirement is "higher += 12" or some
> variant.  It also depends on whether you need to deal with things like
> ninths and thirteenths.
>
> Anyway, I was just tossing out ideas.  You know what your requirements
> are better than I.
>
> --
> D'Arcy J.M. Cain <[EMAIL PROTECTED]>         |  Democracy is three 
> wolveshttp://www.druid.net/darcy/               |  and a sheep voting on
> +1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.

I like D'Arcy's tuples so far.  You could have a 4th element that
contains adjustment for temper.  Octave could be None.

You want ( 4, None, 1 ) "sharp 4th" == ( 5, None, -1 ) "flat 5th", but
you can't have it.  The closest ones are Note( 4, None, 1 )== Note( 5,
None, -1 ) or Note(4, None, 1 ).enh_cmp( Note( 5, None, -1 ) ).  More
elaborate code means more options for calling, though: Note(4, None,
1 ).cmp_enh( 5, None, -1 ), and just call the constructor on the 3
arguments.  You also want Note( 9, None, 0 ).cmp_octave( 2, Rel+ 1,
0 ), 9th== 2nd + 1 octave, and Note( 9, None, 0 ).cmp_nooctave( 2,
None, 0 ), where cmp_... functions return in ( -1, 0, 1 ), and the
middle term can be a class Relative instance, which indicates a
relative octave instead of absolute... or just start at 4.
--
http://mail.python.org/mailman/listinfo/python-list


Re: closures and dynamic binding

2008-09-29 Thread Aaron &quot;Castironpi" Brady
On Sep 29, 9:14 am, Paul Boddie <[EMAIL PROTECTED]> wrote:
> On 29 Sep, 05:56, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
>
>
> > As I understand it, partly from postings here years ago...
>
> > Lexical: The namespace scope of 'n' in inner is determined by where
> > inner is located in the code -- where is is compiled.  This is Python
> > (and nearly all modern languages).  Even without closures, the global
> > scope of a function is the module it is defined in.
>
> This is how I understand it, too. The confusing part involves the
> definition of any inner function and how any "external" names are
> bound or defined. As we've seen...
>
>   def f(x):
>     def g():
>       return x
>     x += 1 # added for illustration
>     return g
>
> ...it might look at first glance like the function known as g (within
> f) should return the initial value of x (as known within f), since
> that was the value x had when g was defined. The following is an
> example execution trace based on that mental model:
>
> fn = f(1)
> -> def f(1):
> ->   def g(): # g defined with x as 1
> ->     return x # would be 1
> ->   x += 1 # x becomes 2
> ->   return g
> fn()
> -> def g():
> ->   return x # would still be 1
>
> However, as we know, this isn't the case in real Python since g isn't
> initialised with the value of x at the time of its definition - it
> instead maintains access to the namespace providing x. We must
> therefore revise the example:
>
> fn = f(1)
> -> def f(1):
> ->   def g(): # g refers to x within f(1)
> ->     return x # would be the current value of x within f(1)
> ->   x += 1 # x becomes 2
> ->   return g
> fn()
> -> def g(): # g refers to x within f(1)
> ->   return x # would be the current value of x within f(1), which is
> 2
>
> This is the dynamic aspect of closures: values aren't used to
> initialise inner functions; names are looked up from their origin.
>
> > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is
> > determined by where inner is called from. This is what you seemed to be
> > suggesting -- look up 'n' based on the scope it is *used* in.
>
> Indeed. Dynamic scoping is confusing in that one has to set up an
> appropriate "environment" for the closure to access so that references
> to names can be meaningfully satisfied; obviously, this creates all
> sorts of encapsulation problems. The confusing aspect of lexical
> scoping, however, especially if non-local names can be changed, is
> that the effects of closures are potentially distant - one doesn't
> always invoke inner functions in the place where they were defined, as
> we see above - and such effects may thus happen within "abandoned
> namespaces" - that is, namespaces which can no longer be revisited and
> used in their original context. So, in the above, once f has been
> invoked, the namespace for that invocation effectively lives on, but
> that namespace is not a general one for f - if we invoke f again, we
> get another namespace as one should reasonably expect.
>
> A somewhat separate issue is illustrated by the modification of x
> within f. Although for most statements, we would expect the value of x
> to evolve following from a top-to-bottom traversal of the code within
> a unit, function definition statements do not behave like, say, "for",
> "if" or "while" statements. Now although this should be obvious at the
> module global level, I feel that it can be easy to overlook within a
> function where one normally expects to find plain old control-flow
> constructs, expressions, assignments and so on. It is pertinent to
> note, with respect to the original inquiry, that lambda functions are
> subject to the same caveats, and I believe that lexical scoping was
> introduced precisely to make lambda functions less cumbersome to
> employ, eliminating the need to explicitly initialise them using the
> "identity" default parameters trick, but obviously introducing the
> consequences and potential misunderstandings described above.
>
> Paul

I'm thinking of a comparison to try to see an example.

I tried this which still surprised me at first.

>>> g= [0]
>>> f= lambda: g
>>> del g
>>> f()
NameError: global name 'g' is not defined

It took a little thinking.  The namespace in 'f' is the global
namespace.  They are one in the same dictionary.  id( f.namespace ) ==
id( main.namespace ).  f.namespace is main.namespace.

When f gets a parameter, its namespace is different by one (or two
when two parameters, etc).

>>> g=[0]
>>> f= lambda h: lambda: h
>>> i= f( g )
>>> del g
>>> i()
[0]

The statement 'del g' removes 'g' from the module/global namespace,
but it lives on in the namespace of 'f', or more accurately, 'i'.

>>> g=[0]
>>> f= lambda h: lambda: h
>>> i= f( g )
>>> j= f( g )
>>> del g
>>> i().append(1)
>>> j()
[0, 1]

Here, the namespaces of 'main', 'i', and 'j', all have references to
'g'.  'i' and 'j' still have them when 'main' loses its.

The lambda might be confusing.  Take a simpler example of a namespace:

>>> g= [

Re: Odd Errors

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 7:13 pm, alex23 <[EMAIL PROTECTED]> wrote:
> The problem is with this:
>
> >         lines = lines.append(inLine)
>
> The append method of a list modifies the list in-place, it doesn't
> return a copy of the list with the new element appended. In fact, it
> returns None, which it then attaches the label 'lines' to, so the next
> iteration through it tries to call None.append...
>
> Replace the line with:
>
>     lines.append(inLine)

Do you ever want to scream from the rooftops, "'append' operates by
side-effect!"?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Not fully OO ?

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 4:41 pm, "Tim Rowe" <[EMAIL PROTECTED]> wrote:
> 2008/9/28 Aaron Castironpi Brady <[EMAIL PROTECTED]>:
>
> > Before I tried wxFormBuilder, I imagined that C# would be vastly
> > faster to develop than Python, for anything requiring any non-trivial
> > graphical interface.  I've done extensive VB, so I can attest to that
> > personally.  It is not.
>
> I'm confused about where VB comes in -- I find VB just *slightly*
> harder than INTERCAL. C# I find fairly easy.
>
> > You can come up with examples that favor either.  But the opposite of
> > statistical is anecdotal.  Sorry again.
>
> Yes, it's anecdotal, but development time isn't just about how fast
> the program is to type (otherwise, why aren't we all using APL?)
>
> > The last time I 'checked in' at your post, your claim was "an hour or
> > so" vs. "ages".  Hence my responses.  You could probably sneak by by
> > claiming a factor of *two*, but if you were exaggerating, please say
> > so at any time.
>
> Ok. I was exaggerating when I said that VB was harder than INTERCAL.
> It's marginally easier.
>
> As for the program I was working on, I worked for over a day on it in
> Python, and did it in about an hour in C#, although in fairness I
> didn't forget all the thinking I'd done on the previous day. I have a
> lot more Python experience than C# experience, but don't claim to be a
> guru in either. And no, I don't work two hour days (unfortunately). I
> have indicated that the GUI wasn't the only issue; in C# it was just
> easy in that case to find all the library bits I needed to in order to
> accomplish the task. It isn't always so.
>
> > on this, that it's "pretty generally applicable"
>
> I'm with you on that.
>
> > I do not believe that C# is pretty generally applicable.
>
> I agree on that, but *only* because it's a proprietary language with
> imperfect support once you move away from the .net platform. It's a
> generally applicable language to .net, but .net is not a general
> platform.
>
> > fact, outside of my VB, COM, and MFC experience, you could say I have
> > no clue.  Very tongue in cheek.)
>
> If you see C# as being in any way related to VB, it's no wonder you're
> down on it!
>
> > Python has a lot of things C# doesn't.  Can we agree on that?
>
> And C# has things that Python doesn't (such as static typing). Can we
> agree on that, too?
>
> --
> Tim Rowe

Maybe too much of my personal life is affecting my judgment of C#.
You mention tools (that are doing the work for you) and I think
incompatibility.  Maybe that part is just because I feel like tools
are like 'excuses'.  And maybe that part is just because... awkward.

I'm going to have to bow out of the dispute, sorry, because I am not a
person that knows both of them.  (How you decide who knows a language
isn't exactly clear, by the way.  It's been stated, for example, that
I don't know Python, as well as that I don't know English.)

You said C# = 1 hour, Python = ages.  I said I could see that if it
came to developing a GUI with a draw-on tool in one and not in the
other.  (Write that C# GUI spec by hand or position your controls from
scratch.)

You could make a case that you can get bad habits from developing in a
tightly-coupled ("tightly-integrated") framework, as you suggested C#
was.  I would agree to it.

I do not find that the Python library is particularly lacking, and the
VB6 library was.

If you're referring to documentation, though, I really like the win32
API docs.  They're precise and thorough.  The Python docs leave some
stuff unsaid; there's a lot of stuff you can do in Python that people
have to tell you or you have to discover on your own.  Which one are
the C# docs like?

Not to reopen the wound, or rather to reopen it patiently: I classify
'static-typing' as handcuffs.  C# has handcuffs and lots of kinds of
them.  "But static-typing lets you do ."  ?  Other
than that, I don't know of any examples, from which I won't infer that
there aren't any.  (That was -won't- infer.)  "Call," I guess; I'll
bite.  What?

If you're referring to library depth, there's a lot of stuff that
probably classifies as wheel reinvention that shouldn't necessarily go
in the library.  There was a good example today.  'Return a string of
5 random digits.'  You could put that in the library, and call it
'RandomDigitString( int length )'.  Doing it by hand only takes one
line though: '"%05i"%random.randint(0,9)'.  Does it belong in the
library?  Otherwise you're technically reinventing the wheel, right?

If you want to talk about your application, the day-to-hour ratio
example, please do.

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


Re: closures and dynamic binding

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 4:47 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > On Sep 28, 2:52 am, Steven D'Aprano <[EMAIL PROTECTED]
> >> As for why the complicated version works, it may be clearer if you expand
> >> it from a one-liner:
>
> >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n )
>
> >> inner = lambda: n
> >> outer = lambda n: inner
> >> f[n] = outer(n)
>
> >> outer(0) => inner with a local scope of n=0
> >> outer(1) => inner with a local scope of n=1 etc.
>
> For this to work, the 'expansion' has to be mental and not actual.
> Which is to say, inner must be a text macro to be substituted back into
> outer.
>
> >> Then, later, when you call inner() it grabs the local scope and returns
> >> the number you expected.
>
> > I must have misunderstood.  Here's my run of your code:
>
> I cannot speak to what Steven meant, but
>
> >>>> inner = lambda: n
>
> when inner is actually compiled outside of outer, it is no longer a
> closure over outer's 'n' and 'n' will be looked for in globals instead.
>
> >>>> outer = lambda n: inner
> >>>> outer(0)
> >  at 0x00A01170>
> >>>> a=outer(0)
> >>>> b=outer(1)
> >>>> a()
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "", line 1, in 
> > NameError: global name 'n' is not defined
>
> > Why doesn't 'inner' know it's been used in two different scopes, and
> > look up 'n' based on the one it's in?
>
> That would be dynamic rather than lexical scoping.

I couldn't find how those apply on the wikipedia website.  It says:
"dynamic scoping can be dangerous and almost no modern languages use
it", but it sounded like that was what closures use.  Or maybe it was
what 'inner' in Steven's example would use.  I'm confused.

Actually, I'll pick this apart a little bit.  See above when I
suggested 'late' and 'early' functions which control (or simulate)
different bindings.  I get the idea that 'late' bound functions would
use a dangerous "dynamic scope", but I could be wrong; that's just my
impression.

> >> inner = lambda: n
> >> outer = lambda n: inner
> >> f[n] = outer(n)
>
> >> outer(0) => inner with a local scope of n=0
> >> outer(1) => inner with a local scope of n=1 etc.

If you defined these as:

inner= late( lambda: n )
outer= lambda n: inner

You could get the right results.  It's not even clear you need
quotes.  Perhaps 'late' could carry the definition of 'n' with it when
it's returned from 'outer'.

In my proposal, it makes a copy of the "localest" namespace, at least
all the variables used below it, then returns its argument in an
original closure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: generate random digits with length of 5

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 4:08 pm, Michael Ströder <[EMAIL PROTECTED]> wrote:
> Gary M. Josack wrote:
> > Aaron "Castironpi" Brady wrote:
> >> On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
>
> >>> Wondering if there is a better way to generate string of numbers with
> >>> a length of 5 which also can have a 0 in the front of the number.
>
> >>> 
> >>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> >>> elements
> >>>  code = 'this is a string' + str(random_number[0]) +
> >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> >>> + str(random_number[4])
> >>> 
>
> >> '%05i'%random.randint(0,9)
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
> > This produces numbers other than 5 digit numbers. making the start
> > number 1 should be fine.
>
> Why do you think it's wrong?
>
>
>
> >>> import random
> >>> '%05i'%random.randint(0,9)
> '09449'
>
> IMO it's exactly what was required.
>
> Ciao, Michael.

As you read, there isn't agreement on whether the OP wanted
replacement.  His original code didn't; his spec seemed to.
--
http://mail.python.org/mailman/listinfo/python-list


Re: generate random digits with length of 5

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 3:44 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Sep 28, 3:11 pm, "Gary M. Josack" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Chris Rebert wrote:
> > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
>
> > >> Wondering if there is a better way to generate string of numbers with
> > >> a length of 5 which also can have a 0 in the front of the number.
>
> > >> 
> > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >> elements
> > >> code = 'this is a string' + str(random_number[0]) +
> > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >> + str(random_number[4])
>
> > > code = ''.join(str(digit) for digit in random_number)
>
> > > Regards,
> > > Chris
>
> > >> 
>
> > >> --
> > >>http://mail.python.org/mailman/listinfo/python-list
>
> > will random.randint(1,9) work for you?
>
> It doesn't meet the OP's requirement that the number
> can start with 0. Also, the method the OP asks about
> returns a list of unique numbers, so no number can
> be duplicated. He can get 02468 but not 13345.
>
> Now, IF it's ok to have an arbitrary number of leading
> 0s, he can do this:
>
> >>> str(random.randint(0,9)).zfill(5)
> '00089'
> >>> str(random.randint(0,9)).zfill(5)
> '63782'
> >>> str(random.randint(0,9)).zfill(5)
> '63613'
> >>> str(random.randint(0,9)).zfill(5)
>
> '22315'

Is a while loop until there are 5 distinct digits best otherwise?

while 1:
  a= '%05i'% random.randint( 0, 9 )
  if len( set( a ) )== 5: break

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


Re: generate random digits with length of 5

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
> Wondering if there is a better way to generate string of numbers with
> a length of 5 which also can have a 0 in the front of the number.
>
> 
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
>  code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])
> 

'%05i'%random.randint(0,9)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Music knowledge representation

2008-09-28 Thread Aaron &quot;Castironpi" Brady
On Sep 28, 2:08 pm, Mr.SpOOn <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady
>
> <[EMAIL PROTECTED]> wrote:
> > Here is a link to someone else's design they asked about on the
> > newsgroup a couple weeks ago.
>
> >http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> :D
> It's always me.
>
> I think my question is more specific. I need some sort of cycle.
>
> So if I have a list with A, B, C, D, when I iter over it I need to get
> an A after the D.

This one was an easy guess:

cycle( iterable)

Make an iterator returning elements from the iterable and saving a
copy of each. When the iterable is exhausted, return elements from the
saved copy. Repeats indefinitely.

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


  1   2   3   4   5   6   7   8   9   10   >