how to get selected filename in FileSelectBox

2008-07-04 Thread wilson
hi
i am using tix FileSelectBox in my application .I want to get the
selected filename as a string

i do this as follows

fselectbox=FileSelectBox(someframe)
fselectbox.__setitem__("dir",join(fselectbox.cget("dir"),".."))
fselectbox.pack(side=LEFT)
...
selectedfile=fselectbox.selection.cget("value")
fselectbox.selection.selection_clear()
print "file=",selectedfile

i did these by going thru the docs in tix ,actually i couldn't find an
example  so i am not sure if this is the right way..it does print the
filename  but i want to know if this is the way..Can someone  comment?
Wilson
--
http://mail.python.org/mailman/listinfo/python-list


Limits of Metaprogramming

2008-08-04 Thread Wilson
Hi all,

I have an interesting problem that I'm hoping can be solved with
metaprogramming, but I don't know how far Python supports code
generation (and I don't know if I'm taking the correct approach
either... hence why I'm asking on this group):

I'd like to write a program that writes/manipulates a statemachine. My
idea was that I would define states in a .py file along with their
transitions and other metadata. I could then write a suite of programs
that would manipulate these states in interesting ways, such as
generate diagrams and documentation, test suites, do verifications and
also edit them. These programs would import the .py file and use
introspection upon the module's classes (states would be modelled as
classes). For example, a documentation tool could use graphviz to draw
the statediagram with the transition table and docstring...

My problem is that I don't know if it's possible to edit these states
and then write them back to .py. Firstly, if my editing tool was to
create a new state, I would want to create the class (using type) and
attach it to the imported state module somehow. I can't find
information on whether this is possible. Secondly, I'd like to
manipulate the class and then use the inspect module to get the source
and write it back to file. Now I'm pretty sure the inspect module will
only write the source code as found in the original .py file. Is there
a way to generate the code for a class or other python objects in a
generic way? Or will I have to bite the bullet and write to custom
file and generate code from that (like glade with XML)? Or is there
another solution with templates that I'm over looking?

Having the classes in memory, editing their attributes, adding methods
and then serialising them to code has an elegance to it in my mind and
would hopefully simplify things. The result would be directly
executable by the interpreter itself and editable by python
developers. But I fear that I may need an intermediary notation/format
for storage. Any advice/hints would be very useful.

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


Re: Limits of Metaprogramming

2008-08-04 Thread Wilson
On 4 Aug, 12:55, Jeff <[EMAIL PROTECTED]> wrote:
> You could write a class composed of states and then use the pickle
> module to serialize it to disk.

Thanks Jeff.

I guess this is my intermediary format!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Limits of Metaprogramming

2008-08-04 Thread Wilson
On 4 Aug, 14:47, Tomasz Rola <[EMAIL PROTECTED]> wrote:
> On Mon, 4 Aug 2008, Wilson wrote:
> > Hi all,
>
> Howdy,
>
> I am not sure if my remarks will be of any use for you, but here it goes.
>
> > I have an interesting problem that I'm hoping can be solved with
> > metaprogramming, but I don't know how far Python supports code
> > generation (and I don't know if I'm taking the correct approach
> > either... hence why I'm asking on this group):
>
> > I'd like to write a program that writes/manipulates a statemachine. My
> > idea was that I would define states in a .py file along with their
> > transitions and other metadata. I could then write a suite of programs
> > that would manipulate these states in interesting ways, such as
> > generate diagrams and documentation, test suites, do verifications and
> > also edit them. These programs would import the .py file and use
> > introspection upon the module's classes (states would be modelled as
> > classes). For example, a documentation tool could use graphviz to draw
> > the statediagram with the transition table and docstring...
>
> Maybe you have actually two problems.
>
> One problem is processing source code into something useful, but
> not executable. So it does not necessarily need metaprogramming to be
> solved, just some "code comprehension" (like get a python grammar,
> lex/yacc and read a lot of docs how to use them).

I do want my resultant code to be executable; I want to be able to use
"import" to get programmatical access to the classes and structures it
contains, such that they can be manipulated, added to, exercised and
drawn (using graphviz) via introspection... After any manipulation,
i'd like to be able to flatten them back into a .py file (as source
such that they are readable as Python code).

> > My problem is that I don't know if it's possible to edit these states
> > and then write them back to .py. Firstly, if my editing tool was to
> > create a new state, I would want to create the class (using type) and
> > attach it to the imported state module somehow. I can't find
> > information on whether this is possible. Secondly, I'd like to
> > manipulate the class and then use the inspect module to get the source
> > and write it back to file. Now I'm pretty sure the inspect module will
> > only write the source code as found in the original .py file. Is there
> > a way to generate the code for a class or other python objects in a
> > generic way? Or will I have to bite the bullet and write to custom
> > file and generate code from that (like glade with XML)? Or is there
> > another solution with templates that I'm over looking?
>
> Well, "everything" is doable in a Turing-complete language :-). However,
> this one problem - code generation and using it on the fly - may be better
> solved with some other language, perhaps?
>
> Not that I want to dissuade you (or anyone else) from using Python, but
> last time I checked the state of things (was a good couple of years ago, I
> wanted to solve some math-related problem with metaprogramming in Python)
> I decided I would do better if I learned Scheme. At least in Scheme,
> program structure is so simple, it is just a list (or a sequence of them),
> so manipulating code is IMHO much easier.
>
> I mean, even if in theory every language in Turing-complete class is equal
> to each other (one can do the same kind of stuff in one as in the other),
> in practice they are not equal at all. So doing everything in one ultimate
> language of choice is not very wise from my point of view.
>
> It does not mean you should immediately go to
>
> http://en.wikipedia.org/wiki/Scheme_(programming_language)
>
> but you may do so, and then make an informed choice by yourself. To be
> better informed, you may also google for more material - introductions,
> opinions, comparisons and some first-hand experience.
>
> On the other hand, writing "metafiles" and interpreters for them - ugh...
> :-). I have read somewhere, that some programmers resist using Scheme
> (or some other Lisp) for solving their problem and end up with writing
> their own Lisp-like (language|file format) and interpreter(s) for it. So
> you better watch yourself. If this effort is going to be something more
> permament than "done and go", then you will probably find yourself in the
> situation of reinventing the wheel, as your project goes more and more
> complex. If this is going to happen, you might use existing wheels and
> save some time for thinking on something better.

I appreciate these comments, and I know the

Re: Limits of Metaprogramming

2008-08-04 Thread Wilson
On 4 Aug, 16:50, John Nagle <[EMAIL PROTECTED]> wrote:
> Wilson wrote:
> > Hi all,
>
> > I have an interesting problem that I'm hoping can be solved with
> > metaprogramming, but I don't know how far Python supports code
> > generation (and I don't know if I'm taking the correct approach
> > either... hence why I'm asking on this group):
>
> > I'd like to write a program that writes/manipulates a statemachine. My
> > idea was that I would define states in a .py file along with their
> > transitions and other metadata.
>
>     You're probably better off coming up with a representation for a
> state machine (which might be a pickled collection of Python objects)
> then providing a "compile" operation which cranks out a .py file
> with code to implement the state machine.
>
>                                 John Nagle

I agree. I guess my 'representation' is the big question!

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


Re: Limits of Metaprogramming

2008-08-04 Thread Wilson
On Aug 4, 6:49 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Aug 4, 4:48 am, Wilson <[EMAIL PROTECTED]> wrote:
>
> > Hi all,
>
> > My problem is that I don't know if it's possible to edit these states
> > and then write them back to .py. Firstly, if my editing tool was to
> > create a new state, I would want to create the class (using type) and
> > attach it to the imported state module somehow. I can't find
>
> > Thanks,
> > Paul
>
> Yes it's possible, using type, but you can't attach it to the module
> in any persistent way.  The next time you load the module, it's back
> to the way it was.
>
> I think this may be the hang-up in your design: if you think about
> generating lines of code directly from the user's actions, you might
> stay on the right track.  At that point, you can place them in the .py
> file.  Then you can reimport it, or just execute the new lines
> directly.
>
> If this is your class,
>
> class Auto54701:
>   def next( self, input ):
>      if( something ):
>        return value1
>      return value2
>
> Here's how to work with it at the interactive prompt:
>
> >>> s= """class Auto54701:
>
> ...   def next( self, input ):
> ...      if( something ):
> ...        return value1
> ...      return value2
> ... """>>> s
>
> 'class Auto54701:\n  def next( self, input ):\n     if( something ):
> \n       ret
> urn value1\n     return value2\n'>>> exec( s )
> >>> Auto54701
>
> 
>
>
>
> And by the way, you can't use pickle to store types.  There needs to
> be some fleshed-out code to back them up.
>
> Two more alternatives, which I can discuss more later, one where you
> implement code as data, but it ends up being a lot like Python
> anyway.  It only works if your classes' methods are going to be
> simple, probably sequential if-s and assignments at most.
>
> class Auto54701:
>   def next( self, input ):
>      if( something1 ):
>        return value1
>      elif( something2 ):
>        return value2
>      elif( something3 ):
>        return value3
>      elif( something4 ):
>        return value4
>     return value5
>
> can be stored in data as
>
>   [ ( something1, value1 ), ( something2, value2 ), ... ]
>
> , and just checked in a loop, that you only have in code once, rather
> than many times.
>
> class GenericAuto:
>   def next( self, input ):
>     for something, value in conditionpairs:
>       if( something ):
>         return value
>     return valuen
>
> Two, if all your methods will have uniform signatures and closures,
> you can store class methods as only their co_code objects:
>
> >>> C.g.im_func.func_code.co_code
>
> 'd\x00\x00S'
>
> And fabricate them dynamically into full live types as needed.

Thanks for your comments and advice. This second option intrigues me;
could you elaborate further, I don't follow you...

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


Re: Limits of Metaprogramming

2008-08-06 Thread Wilson
On Aug 4, 9:23 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Aug 4, 1:57 pm, Wilson <[EMAIL PROTECTED]> wrote:
>
> > On Aug 4, 6:49 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
> > > Two, if all your methods will have uniform signatures and closures,
> > > you can store class methods as only their co_code objects:
>
> > > >>> C.g.im_func.func_code.co_code
>
> > > 'd\x00\x00S'
>
> > > And fabricate them dynamically into full live types as needed.
>
> > Thanks for your comments and advice. This second option intrigues me;
> > could you elaborate further, I don't follow you...
>
> > Thanks Paul
>
> Depending on the complexity of the functions, a code string could be
> all you need to store to determine (redetermine) a function's
> behavior.  For something moderately simple,
>
> def trans1( self, prev, trans ):
>         if prev== 0 and trans== 'a':
>                 return 1
>         if prev== 1 and trans== 'b':
>                 return 0
>         return prev
>
> I found you need to store code.co_nlocals, code.co_code, and
> code.co_consts, to distinguish from a blank stub.  With extra
> variables, I needed code.co_names and code.co_varnames too.  To
> recreate a code object completely, you need 12 variables (14 to
> include closures), some of which are composite objects and would need
> to be pickled to be stored.
>
> Then you can build a new code object, then a new function object, then
> a new method object, then you can call it.  Instead of a module of
> code, perhaps you could have a datafile containing only these values,
> up to twelve per record, one record for each different function you
> have.
>
> Here is the benefit:
>
> newcode= dupecode( oldcode, codet1 )
> newfun= FunctionType( newcode, {} )
> stub.stub= MethodType( newfun, stub )
> prev= stub.stub( prev, trans )
> print prev
>
> You can loop over these five lines, re-loading function data with
> 'dupecode', executing it, then reloading the next one, and you have a
> different function.  Additions to your database of functions would
> start in source first (unless you construct each parameter, in
> particular co_code, by hand, which you may want), then get compiled,
> then go in.
>
> Here is the complete constructor for a code object:
>
> >>> help(_)
>
> Help on code object:
>
> class code(object)
>  |  code(argcount, nlocals, stacksize, flags, codestring, constants,
> names,
>  |        varnames, filename, name, firstlineno, lnotab[, freevars[,
> cellvars]])
>
> Here's the constructor in Python 3.0:
>
> class code(object)
>  |  code(argcount, kwonlyargcount nlocals, stacksize, flags,
> codestring,
>  |        constants, names, varnames, filename, name, firstlineno,
>  |        lnotab[, freevars[, cellvars]])
>
> I defined Stub.stub like this:
>
> class Stub:
>         def stub( self, prev, trans ):
>                 return prev
> stub= Stub( )
>
> You need imports from the types module:
>
> from types import MethodType, FunctionType, CodeType
>
> And here is 'dupecode', which currently only replaces five of the old
> function's members with new ones:
>
> def dupecode( old, new ):
>
>         newcode= CodeType( old.co_argcount, new.co_nlocals, old.co_stacksize,
>                 old.co_flags,
>                 new.co_code,
>                 new.co_consts, new.co_names,
>                 new.co_varnames, old.co_filename, old.co_name, 
> old.co_firstlineno,
>                 old.co_lnotab )
>
>         return newcode

Still don't really understand this so I'm going to admit defeat.
Thanks all for your advice... Very much appreciated!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Limits of Metaprogramming

2008-08-07 Thread Wilson
On Aug 6, 6:04 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On Aug 6, 7:24 am, Wilson <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Aug 4, 9:23 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
> > > On Aug 4, 1:57 pm, Wilson <[EMAIL PROTECTED]> wrote:
>
> > > > On Aug 4, 6:49 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
> > > > > Two, if all your methods will have uniform signatures and closures,
> > > > > you can store class methods as only their co_code objects:
>
> > > > > >>> C.g.im_func.func_code.co_code
>
> > > > > 'd\x00\x00S'
>
> > > > > And fabricate them dynamically into full live types as needed.
>
> > > > Thanks for your comments and advice. This second option intrigues me;
> > > > could you elaborate further, I don't follow you...
>
> > > > Thanks Paul
>
> > > Depending on the complexity of the functions, a code string could be
> > > all you need to store to determine (redetermine) a function's
> > > behavior.  For something moderately simple,
>
> > > def trans1( self, prev, trans ):
> > >         if prev== 0 and trans== 'a':
> > >                 return 1
> > >         if prev== 1 and trans== 'b':
> > >                 return 0
> > >         return prev
>
> > > I found you need to store code.co_nlocals, code.co_code, and
> > > code.co_consts, to distinguish from a blank stub.  With extra
> > > variables, I needed code.co_names and code.co_varnames too.  To
> > > recreate a code object completely, you need 12 variables (14 to
> > > include closures), some of which are composite objects and would need
> > > to be pickled to be stored.
>
> > Still don't really understand this so I'm going to admit defeat.
> > Thanks all for your advice... Very much appreciated!
>
> I was describing an alternative to storing functions in a way that
> wasn't in serial in plain text.  It was off-topic from state-machine
> transitions.
>
> Can you start with this?
>
> # state, input, next state
> transitions= [
>   ( 0, 'a', 1 ),
>   ( 1, 'a', 2 ),
>   ( 2, 'a', 0 ),
>   ( 0, 'b', 0 ),
>   ( 1, 'b', 0 ),
>   ( 2, 'b', 2 )
> ]
>
> What further?

My problem relates to the states really. I'd like to import a file
containing the state classes into a "state editor" that is just a
class editor really. Then, at *runtime* I'd like to add and remove
methods from this class and change its attributes (__dict__). I'd also
like to be able to add and remove classes from the module. When done,
I was hoping to do introspection upon which classes were associated
with this module and write back the modified class definitions to the
same module. Next time the module is imported, the changes would
remain intact. Unfortunately, inspect.getsource() reads the original
file and does not magically return source from the runtime objects.

Hope that makes sense!
Paul
--
http://mail.python.org/mailman/listinfo/python-list


Re: Limits of Metaprogramming

2008-08-08 Thread Wilson
On 8 Aug, 13:30, Iain King <[EMAIL PROTECTED]> wrote:
> On Aug 4, 5:13 pm, Tomasz Rola <[EMAIL PROTECTED]> wrote:
>
> > On Mon, 4 Aug 2008, Wilson wrote:
> > > " Every sufficiently large application has a poor/incomplete
> > > implementation ofLISPembedded within it ".
>
> > Yep, this is either exact or very close copy of what I have read.
>
> It's Greenspun's Tenth Rule of Programming:
>
> "Any sufficiently complicated C or Fortran program contains an ad-hoc,
> informally-specified bug-ridden slow implementation of half of Common
> Lisp."
>
> Iain

Thanks for that. Makes my attempt look pathetic! :)
--
http://mail.python.org/mailman/listinfo/python-list


Manipulating Python Source

2008-08-12 Thread Wilson
Hi,

I'm wondering if there are any tools available or simple methods for
taking a python source file and parsing into some hierarchical format,
like the ConfigParser. I'd like to be able to do something like the
following:

test.py:
---

""" This is an example """

class MyClass(ParentA, ParentB):
def some_func(self, foo, bar):
 self.baz = "batman"

class MyClass2(object):
""" This is an example class """
def __init__(self):
 self.a = "Blablabla"

And from the interpreter:

>>> import magicalParser
>>> parsed = magicalParser.parse(test.py)
>>> parsed.getClasses()
["MyClass", "MyClass2"]
>>> parsed.docString
" This is an example "
>>> parsed.removeClass("MyClass2")
>>> parsed.getClasses()
["MyClass"]
>>> parsed.MyClass.getFuncs()
["some_func"]
>>> parsed.MyClass.some_func.addParam("baz")
>>> parsed.printSource()
""" This is an example """

class MyClass(ParentA, ParentB):
def some_func(self, foo, bar, baz):
 self.baz = "batman"
>>> exit()

Or something that would yield the above effect. Any ideas?

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


Re: Manipulating Python Source

2008-08-13 Thread Wilson
On 12 Aug, 15:53, Bruno Desthuilliers  wrote:
> Kay Schluehr a écrit :> On 12 Aug., 16:35,Wilson<[EMAIL PROTECTED]> wrote:
> >> Hi,
>
> >> I'm wondering if there are any tools available or simple methods for
> >> taking a python source file and parsing into some hierarchical format,
> >> like the ConfigParser.
>
> >http://docs.python.org/lib/module-parser.html
> >http://docs.python.org/lib/compiler.html
>
> And eventually:http://docs.python.org/lib/module-inspect.html

Very interesting! Thanks for the hints.
--
http://mail.python.org/mailman/listinfo/python-list


displaying pgm file in python

2008-04-04 Thread wilson
i converted an 8bit rgb .jpg file into .pgm using adobe photoshop and
a plugin from 
http://photoshop.pluginsworld.com/plugins/adobe/362/richard-rosenman/portable-pixmap-importer-exporter.html
I want to check if this file can be properly displayed.
Image opening and show() in PIL fails to do it so i tried Tkinter

i created a canvas in a tkinter gui and tried
self.myimg=PhotoImage(file="mytestpic.pgm")
 
self.selimgtag=self.canvorig.create_image(70,100,image=self.myimg)
self.canvorig.update_idletasks()

this causes AttributeError snd says can't identify image file
I checked the asci text of .pgm file ,it starts with a line P2 and
then several lines with integers..can someone tell me if there is a
way to display this properly

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


removing extension

2008-04-27 Thread wilson
i was trying to convert all images in a folder to another type and
save the new images in a separate folder.for that i wrote a class and
coded some part

class ConvertImgs:
def __init__(self,infldr,outfldr):
if os.path.isdir(infldr):
self.infldr=infldr
self.outfldr=outfldr
else:
print "no such folder,exits program"
exit(1)
if not os.path.isdir(self.outfldr):
os.mkdir(self.outfldr)
print "made:",self.outfldr

for x in os.listdir(infldr):
self.origlist=[os.path.normpath(os.path.join(self.infldr,x)) for x in
os.listdir(infldr)]

...
the self.origlist  returns a list of filenames in infolder.I would
like to get them as 'C:\\myimages\\imageone'  instead of 'C:\\myimages\
\imageone.jpg' sothat i can add a diff extension to all those strings
in the list and save in diff format(ie change 'C:\\myimages\\imageone'
to 'C:\\myimages\\imageone.gif ' and save in gif format).but i don't
know how to remove those extension from the namestring ..can someone
help?
W
--
http://mail.python.org/mailman/listinfo/python-list


convert images

2008-04-27 Thread wilson
hi
i converted some P5 type .pgm images to .jpg using
x=Image.open("oldimage.pgm")
imsz=x.size
newimg=Image.new('L',imsz)
newimg.putdata(x.getdata())
newimg.save("newimg.jpg")

when i again check the pixel data for these images using getdata()
method i,I find that they are slightly different

ie if oldimage.pgm has pixels
[29 31 38 ..., 10  4 18]
then the corresponding jpg image has
[29 31 38 ..., 10  3 17]

why this difference? shouldn't they be identical?can someone pls
explain this?

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


Re: Parsing and Editing Source

2008-08-15 Thread Wilson
On Aug 15, 3:45 pm, eliben <[EMAIL PROTECTED]> wrote:
> On Aug 15, 4:21 pm, "Paul Wilson" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all,
>
> > I'd like to be able to do the following to a python source file
> > programmatically:
> >  * Read in a source file
> >  * Add/Remove/Edit Classes, methods, functions
> >  * Add/Remove/Edit Decorators
> >  * List the Classes
> >  * List the imported modules
> >  * List the functions
> >  * List methods of classes
>
> > And then save out the result back to the original file (or elsewhere).
>
> > I've begun by using the tokenize module to generate a token-tuple list
> > and am building datastructures around it that enable the above
> > methods. I'm find that I'm getting a little caught up in the details
> > and thought I'd step back and ask if there's a more elegant way to
> > approach this, or if anyone knows a library that could assist.
>
> > So far, I've got code that generates a line number to token-tuple list
> > dictionary, and am working on a datastructure describing where the
> > classes begin and end, indexed by their name, such that they can be
> > later modified.
>
> > Any thoughts?
> > Thanks,
> > Paul
>
> Consider using the 'compiler' module which will lend you more help
> than 'tokenize'.
>
> For example, the following demo lists all the method names in a file:
>
> import compiler
>
> class MethodFinder:
>     """ Print the names of all the methods
>
>         Each visit method takes two arguments, the node and its
>         current scope.
>         The scope is the name of the current class or None.
>     """
>
>     def visitClass(self, node, scope=None):
>         self.visit(node.code, node.name)
>
>     def visitFunction(self, node, scope=None):
>         if scope is not None:
>             print "%s.%s" % (scope, node.name)
>         self.visit(node.code, None)
>
> def main(files):
>     mf = MethodFinder()
>     for file in files:
>         f = open(file)
>         buf = f.read()
>         f.close()
>         ast = compiler.parse(buf)
>         compiler.walk(ast, mf)
>
> if __name__ == "__main__":
>     import pprint
>     import sys
>
>     main(sys.argv)

Thanks! Will I be able to make changes to the ast such as "rename
decorator", "add decorator", etc.. and write them back out to a file
as Python source?

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


Re: Parsing and Editing Source

2008-08-15 Thread Wilson
On Aug 15, 4:16 pm, Rafe <[EMAIL PROTECTED]> wrote:
> On Aug 15, 9:21 pm, "Paul Wilson" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all,
>
> > I'd like to be able to do the following to a python source file
> > programmatically:
> >  * Read in a source file
> >  * Add/Remove/Edit Classes, methods, functions
> >  * Add/Remove/Edit Decorators
> >  * List the Classes
> >  * List the imported modules
> >  * List the functions
> >  * List methods of classes
>
> > And then save out the result back to the original file (or elsewhere).
>
> > I've begun by using the tokenize module to generate a token-tuple list
> > and am building datastructures around it that enable the above
> > methods. I'm find that I'm getting a little caught up in the details
> > and thought I'd step back and ask if there's a more elegant way to
> > approach this, or if anyone knows a library that could assist.
>
> > So far, I've got code that generates a line number to token-tuple list
> > dictionary, and am working on a datastructure describing where the
> > classes begin and end, indexed by their name, such that they can be
> > later modified.
>
> > Any thoughts?
> > Thanks,
> > Paul
>
> I can't help much...yet, but I am also heavily interested in this as I
> will be approaching a project which will require me to write code
> which writes code back to a file or new file after being manipulated.
> I had planned on using the inspect module's getsource(), getmodule()
> and getmembers() methods rather than doing any sort of file reading.
> Have you tried any of these yet? Have you found any insurmountable
> limitations?

The inspect module's getsource() returns the source code as originally
defined. It does not return any changes that have been made during
runtime. So, if you attached a new class to a module, I don't belive
that getsource() would be any use for extracting the code again to be
saved. I have rejected this approach for this reason. getmembers()
seems to be fine for this purpose, however I don't seen anyway to get
class decorators and method decorators out.

> It looks like everything needed is there. Some quick thoughts
> regarding inspect.getmembers(module) results...
>  * Module objects can be written based on their attribute name and
> __name__ values. If they are the same, then just write "import %s" %
> mod.__name__. If they are different, write "import %s as %s" % (name,
> mod.__name__)
>
>  * Skipping built in stuff is easy and everything else is either an
> attribute name,value pair or an object of type 'function' or 'class'.
> Both of which work with inspect.getsource() I believe.

True, but if you add a function or class at runtime,
inspect.getsource() will not pick it up. It's reading the source from
a file, not doing some sort of AST unparse magic as I'd hoped. You'll
also have to check getsource() will return the decorator of an object
too.

>  * If the module used any from-import-* lines, it doesn't look like
> there is any difference between items defined in the module and those
> imported in to the modules name space. writing this back directly
> would 'flatten' this call to individual module imports and local
> module attributes. Maybe reading the file just to test for this would
> be the answer. You could then import the module and subtract items
> which haven't changed. This is easy for attributes but harder for
> functions and classes...right?

Does getmodule() not tell you where objects are defined?

> Beyond this initial bit of code, I'm hoping to be able to write new
> code where I only want the new object to have attributes which were
> changed. So if I have an instance of a Person object who's name has
> been changed from it's default, I only want a new class which inherits
> the Person class and has an attribute 'name' with the new value.
> Basically using python as a text-based storage format instead of
> something like XML. Thoughts on this would be great for me if it
> doesn't hijack the thread ;) I know there a quite a few who have done
> this already.

You want to be able to make class attribute changes and then have some
automated way of generating overriding subclasses that reflects this
change? Sounds difficult. Be sure to keep me posted on your journey!

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


Re: Parsing and Editing Source

2008-08-16 Thread Wilson
On Aug 16, 3:51 am, Benjamin <[EMAIL PROTECTED]> wrote:
> On Aug 15, 9:21 am, "Paul Wilson" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi all,
>
> > I'd like to be able to do the following to a python source file
> > programmatically:
> >  * Read in a source file
> >  * Add/Remove/Edit Classes, methods, functions
> >  * Add/Remove/Edit Decorators
> >  * List the Classes
> >  * List the imported modules
> >  * List the functions
> >  * List methods of classes
>
> > And then save out the result back to the original file (or elsewhere).
>
> > I've begun by using the tokenize module to generate a token-tuple list
> > and am building datastructures around it that enable the above
> > methods. I'm find that I'm getting a little caught up in the details
> > and thought I'd step back and ask if there's a more elegant way to
> > approach this, or if anyone knows a library that could assist.
>
> > So far, I've got code that generates a line number to token-tuple list
> > dictionary, and am working on a datastructure describing where the
> > classes begin and end, indexed by their name, such that they can be
> > later modified.
>
> Look at the 2to3 tool which is good at this sort of thing. It lets you
> define custom "fixers" that work on a fairly high-level representation
> of the parse tree and then write the source back exactly unchanged.
>
>
>
> > Any thoughts?
> > Thanks,
> > Paul
>
>

Thanks for the hint. I've looked at lib2to3 and there might be some
useful stuff in there!

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


file I/O and arithmetic calculation

2013-05-22 Thread Keira Wilson
Dear all,

I would appreciate if someone could write a simple python code for the
purpose below:

I have five text files each of 10 columns by 10 rows as follows:

file_one = 'C:/test/1.txt'
file_two = 'C:/test/2.txt' . . .
file_five = 'C:/test/5.txt'

 I want to calculate the mean of first row (10 elements) for each file (5
files), if mean of first column (10 elements) of each file (5 files) is 50.

Thank you in advance.

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


Re: file I/O and arithmetic calculation

2013-05-23 Thread Keira Wilson
Dear all who involved with responding to my question - Thank you so much for 
your nice code which really helped me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: file I/O and arithmetic calculation

2013-05-23 Thread Keira Wilson
not exactly for the homework, but as my starting point of learning
thank you so much.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: except clause syntax question

2012-01-30 Thread Mel Wilson
Charles Yeomans wrote:

> To catch more than one exception type in an except block, one writes
> 
> except (A, B, C) as e:
> 
> I'm wondering why it was decided to match tuples, but not lists:
> 
> except [A, B, C] as e:
> 
> The latter makes more sense semantically to me -- "catch all exception
> types in a list" as opposed to "catch this single thing composed of three
> exception types".

I've always been perfectly fine with sometimes treating tuples as immutable 
sequences, so I'm +0 on saying "more sense semantically", but given that the 
exception list can be a variable, I'm not sure what the gain is by keeping 
it immutable.

#---
#!/usr/bin/env python
# -*- coding: ASCII -*-
'''Demonstrate catching variable exceptions.
'''
def excepter (a, exceptions):
try:
1.0/a
'Number ' + a
except exceptions as e:
print '!!! *** EXCEPTER CAUGHT ONE *** !!!'
print repr (e)

#~ excepter (0, [ZeroDivisionError])
excepter (0, (ZeroDivisionError,))
excepter (1, (ZeroDivisionError,TypeError))
excepter (1, (ZeroDivisionError,))

 #---

excepter called with the list catches nothing, of course.


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


Re: except clause syntax question

2012-01-31 Thread Mel Wilson
Charles Yeomans wrote:

> To catch more than one exception type in an except block, one writes
> 
> except (A, B, C) as e:
> 
> I'm wondering why it was decided to match tuples, but not lists:
> 
> except [A, B, C] as e:
> 
> The latter makes more sense semantically to me -- "catch all exception
> types in a list" as opposed to "catch this single thing composed of three
> exception types".

On reflection, it seems to hint at a style that Python extensions were made 
in.  (IIRC) the first operand in an `except` statement was originally just 
an arbitrary marker to identify the exception.  Unique string values were 
customary, although the Python library defined things with standard 
exception names.  Using a string means that general exceptions weren't to be 
collected in general sequences; `except "Serious Error"` was never meant to 
catch `raise "r"`.  If only tuples were used for collections, it would 
create havoc for fewer of any weirdos who had used strange markers of their 
own devising.

It looks like tuples were chosen as the most "lightweight", or maybe least 
intrusive, sequence type to require to denote a collection of exceptions.

You see a similar decision, with the opposite emphasis, with the string 
modulo operator.  The second operand is supposed to be a tuple, but if the 
template string needs only one value, then the rules are relaxed and any 
single non-tuple value is used as-is.


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


Re: except clause syntax question

2012-01-31 Thread Mel Wilson
Chris Angelico wrote:

> On Wed, Feb 1, 2012 at 9:03 AM, Duncan Booth
>  wrote:
>> Abitrarily nested tuples of exceptions cannot contain loops so the code
>> simply needs to walk through the tuples until it finds a match.
> 
> Is this absolutely guaranteed? The C API for CPython provides:
> (Py2) http://docs.python.org/c-api/tuple.html#PyTuple_SetItem
> (Py3) http://docs.python.org/dev/c-api/tuple.html#PyTuple_SetItem
> 
> which doesn't have massive warnings on it saying "USE THIS ONLY TO
> INITIALIZE A TUPLE" (compare, for instance, _PyTuple_Resize which does
> carry a similar warning). Is the assumption then that we're all
> adults, and that mutating a tuple is like passing a null pointer to an
> API function (aka "loaded gun in proximity to foot")?

Unfortunately, I can't remember the details now, but I once set out to 
create a recursive tuple by using the C API, and it turned out then that the 
C API went to some lengths to prevent anyone being able to do that.  I did 
finally do it in some peculiar way, but it wasn't simple.  The c.l.python 
archives might still have the post where I described it.

Mel.

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


Re: Question about name scope

2012-02-01 Thread Mel Wilson
Dave Angel wrote:

> I tried your experiment using Python 2.7 and Linux 11.04
> 
> 
> def f(a):
>  from math import sin, cos
>  return sin(a) + cos(a)
> 
> print f(45)
> 
> Does what you needed, and neatly.  The only name added to the global
> namspace is f, of type function.
> 
> I was a bit surprised that using   from math import * inside the
> function worked, but it generates  a warning:
> olive.py:2: SyntaxWarning: import * only allowed at module level
>def f(a):

I guess they want local symbols in functions to be pre-compiled.  Similar to 
the way you can't usefully update the dict returned by locals().  Strangely, 
I notice that

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...   exec x
...   exec 'print a'
... 
>>> f('a=4')
4
>>> 

works, but I really cannot explain why.

Mel.

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


Re: python reliability with EINTR handling in general modules

2012-02-02 Thread Mel Wilson
Dennis Lee Bieber wrote:

> On Wed, 1 Feb 2012 23:25:36 -0800 (PST), oleg korenevich
>  wrote:
> 
> 
>>Thanks for help. In first case all vars is python integers, maybe
>>math.floor is redundant, but i'm afraid that same error with math
>>module call will occur in other places of app, where math is needed.
>>Strange thing here is that math library call is not a system call, and
>>strange exception ValueError (all values have right values) and why in
>>braces i have (4, Interruted system call).
>>
> math.floor() may still be a system call of some sort if access to
> the math processor requires synchronization between processes (that is,
> the math processor/registers are maintained as a separate structure
> apart from the task status during process switches). {Yes -- that is a
> wild hypothesis}

One thing to remember about errno is that C library code will set it to a 
non-zero value when an error is encountered, but (I believe) there's no 
requirement to clear it in the absence of an error.  EINTR might just be 
left over from some long-gone I/O call, then reported "just in case" in 
handling an exception that didn't involve the C library at all.

As a C coder there are times when it's wise to clear errno yourself to make 
sure your code doesn't get fooled.

Mel.

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


Re: difference between random module in python 2.6 and 3.2?

2012-02-06 Thread Mel Wilson
Steven D'Aprano wrote:

> A more explicit note will help, but the basic problem applies: how do you
> write deterministic tests given that the random.methods (apart from
> random.random itself) can be changed without warning?

Biting the bullet would mean supplying your own PRNG, under your control.  
Jon Bentley somewhere, sometime, published a portable PRNG for that exact 
reason.  (I wish I could find that article.)  Specifically he wanted 
portability across various manufacturer's O/Ss.

Mel.

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


Re: M2crypto

2012-02-12 Thread Mel Wilson
zigi wrote:

> Hello,
> M2crypto
> 
> __init__(self, alg, key, iv, op, key_as_bytes=0, d='md5',
> salt='12345678', i=1, padding=1)
> 
> I wont write app, using M2crypto and I can not understand what are the
> arguments:
> key, iv, op, salt ?
> What they do ?

I assume you're reading in  
about M2Crypto.EVP.Cipher.

Epydoc claims another victim.

I'm having a lot of trouble finding documentation.  The obvious OpenSSL 
pages are kind of thin, too.  You might see some useful code in the EVP unit 
tests m2crypto/tests/test_evp.py in the m2crypto installation.

Good hunting,   Mel.

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


Re: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Jabba Laci wrote:
> Could someone please tell me what the following sorting algorithm is
> called?
> 
> Let an array contain the elements a_1, a_2, ..., a_N. Then:
> 
for i in xrange (N-1):
for j in xrange (i, N):
if a[j] < a[i]:
a[i], a[j] = a[j], a[i]
> 
> It's so simple that it's not mentioned anywhere. I guess it's called
> "selection sort" but I'm not sure. The minimum selection sort is an
> improvement of this one.

It's what Wikipedia says a selection sort is: put the least element in [0], 
the least of the remaining elements in [1], etc.

Mel.

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


RE: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Prasad, Ramit wrote:

>> 
> for i in xrange (N-1):
> for j in xrange (i, N):
> if a[j] < a[i]:
> a[i], a[j] = a[j], a[i]
>> It's what Wikipedia says a selection sort is: put the least element in
>> [0], the least of the remaining elements in [1], etc.
> 
> If your only requirement to match to selection sort is the end result,
> then every sort would be selection sort. If you meant "put the least
> element in [0] in the first pass" then that would indeed be selection
> sort, but that is not what the above code does. The above code is bubble
> sort.

Well, the classic bubble sort swaps adjacent elements until the extreme one 
gets all the way to the end.  This sort continually swaps with the end 
element during one pass until the end element holds the extreme.  Then it 
shrinks the range and swaps then next less extreme into the new end element.  
It does extra swaps because it combines the swap operation with recording 
the temporary extreme while it searches the subrange.

Mel.

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


Re: name of a sorting algorithm

2012-02-14 Thread Mel Wilson
Den wrote:

> I disagree.  In a bubble sort, one pointer points to the top element,
> while another descents through all the other elements, swapping the
> elements at the pointers when necessary.

'When I use a word,' Humpty Dumpty said, in rather a scornful tone, 'it 
means just what I choose it to mean — neither more nor less.' (_Through the 
Looking Glass, Lewis Caroll).  And you, too, have that ability.  
Contrariwise see Knuth, _The Art of Computer Programming_ Section 5.2.2, 
Algorithm B.

Mel.


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


Re: atexit.register in case of errors

2012-02-15 Thread Mel Wilson
Andrea Crotti wrote:

> I have the following very simplified situation
> 
> from atexit import register
> 
> 
> def goodbye():
>  print("saying goodbye")
> 
> 
> def main():
>  while True:
>  var = raw_input("read something")
> 
> 
> if __name__ == '__main__':
>  register(goodbye)
>  main()
> 
> 
> But in my case the "goodbye" function is deleting the logging file which
> was created
> during the application execution.
> Now the problem is that it *always* executes, even when the applications
> quits for
> some bad errors.
> 
> Is there a way to have an exit hook, which doesn't execute in case of
> errors?
> I've seen the code of atexit and it apparently doesn't know anything
> about the current
> status and why the application is actually quitting, is that correct?

That's sort of the point: to do things that simply *have* to happen, even if 
you've lost control of the program.

The usual way to do what you're asking is

if __name__ == '__main__':
main()
goodbye()

and write main so that it returns after it's done all the things it's 
supposed to do.  If you've sprinkled `sys.exit()` all over your code, then 
don't do that.  If you're forced to deal with a library that hides 
`sys.exit()` calls in the functions, then you have my sympathy.  Library 
authors should not do that, and there have been threads on c.l.p explaining 
why they shouldn't.

Mel.

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


Re: PyWart: Language missing maximum constant of numeric types!

2012-02-24 Thread Mel Wilson
Rick Johnson wrote:

> I get sick and tired of doing this!!!
> 
> if maxlength == UNLIMITED:
> allow_passage()
> elif len(string) > maxlength:
> deny_passage()
> 
> What Python needs is some constant that can be compared to ANY numeric
> type and that constant will ALWAYS be larger!

Easily fixed:



class Greatest (object):
def __cmp__ (self, other):
if isinstance (other, Greatest):
return 0
return 1

def __hash__ (self):
return id (Greatest)

class Least (object):
def __cmp__ (self, other):
if isinstance (other, Least):
return 0
return -1

def __hash__ (self):
return id (Least)



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


Re: Is it necessary to call Tk() when writing a GUI app with Tkinter?

2012-03-02 Thread Mel Wilson
Terry Reedy wrote:

> The problem was another subtle bug in the current example":
>  self.hi_there["text"] = "Hello",
> 
> The spurious comma at the end makes the value of the 'text' attribute a
> one-elememt tuple and not just a string. I presume tcl-based tk handles
> that in the manner appropriate for the tcl equivalent. I believe tcl
> uses spaces rather than commas to separate items, so the braces serve as
> 'quotes' to indicate that the contents are one item, not three. Removing
> the comma solves the problem.

That looks like it.  Tcl is the 'LISP of strings'  Composite-object things 
like indexing work on space-separated strings.


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


Re: A 'Python like' language

2012-03-03 Thread Mel Wilson
Paul Rubin wrote:

> dreamingforw...@gmail.com writes:
>>> hanging out on the Prothon list now and then, at least until we get
>>> the core language sorted out?
>>
>> Haha, a little late, but consider this a restart.
> 
> It wasn't til I saw the word "Prothon" that I scrolled back and saw you
> were responding to a thread from 2004.  Prothon was pretty cool in some
> ways but I think it's been inactive for a very long time.  I don't see
> much point to developing a "slightly improved but incompatible
> Python-like language" anyway though.  Why make superficial changes that
> break working code and mentally overload programmers?  Python is a
> relatively mature language by now, so it shouldn't be messed with unless
> the changes produce drastic benefits, not minor ones.

A website still exists, but I don't see signs of a new language; looks like 
a watering hole for some techies.

Prothon looked interesting as long as it promised to be about Python that 
used prototypes instead of classes to organize objects.  What happened, 
though, was that it turned into a crusade to remove every Python wart that a 
bunch of people could imagine.  The band of developers might have had the 
steam for the new object model, but they didn't have the steam to do 
everything.

Mel.

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


Re: Python is readable

2012-03-16 Thread Mel Wilson
Steven D'Aprano wrote:

> On Fri, 16 Mar 2012 17:53:24 +, Neil Cerutti wrote:
> 
>> On 2012-03-16, Steven D'Aprano 
>> wrote:
>>> Ah, perhaps you're talking about *prescriptivist* grammarians, who
>>> insist on applying grammatical rules that exist only in their own
>>> fevered imagination. Sorry, I was talking about the other sort, the
>>> ones who apply the grammatical rules used by people in real life. You
>>> know the ones: linguists. My mistake.
>> 
>> I am not pedantic. You are wrong.
> 
> 
> Whether you like it or not, it simply is a fact that in English (I won't
> speak for other languages) people use colons without the first clause
> *necessarily* being a complete sentence. They write things like this:
> 
> Star Wars Episode IV: A New Hope

Come to think of it, just about every "serious" book title works this way.

Mel.

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


Re: Programming D. E. Knuth in Python with the Deterministic Finite Automaton construct

2012-03-17 Thread Mel Wilson
Antti J Ylikoski wrote:

> 
> In his legendary book series The Art of Computer Programming,
> Professor Donald E. Knuth presents many of his algorithms in the form
> that they have been divided in several individual phases, with
> instructions to GOTO to another phase interspersed in the text of the
> individual phases.
> 
> 
> 
> I. e. they look like the following, purely invented, example:  (Knuth is
> being clearer than me below.)
> 
> 
> 
> A1.  (Do the work of Phase A1.)  If  then go to Phase A5,
> otherwise continue.
> 
> A2.  (Do some work.) If  go to Phase A4.
> 
> A3.  (Some more work.)
> 
> A4.  (Do something.)  If  go to Phase A1.
> 
> A5.  (Something more).  If  then go to Phase A2, otherwise
> end.
> 
> 
> 
> I came across the problem, which would be the clearest way to program
> such algorithms with a programming language such as Python, which has
> no GOTO statement.  It struck me that the above construction actually
> is a modified Deterministic Finite Automaton with states A1 -- A5 +
> [END], transferring to different states, not on read input, but
> according to conditions in the running program.
> 
> So one very clear way to program Knuth with Python is the following
> kind of a construct.

Yeah.  This is an idea that came up during the '70s after Dijkstra published 
his "GOTO Considered Harmful".  Model the execution pointer as a state, and 
then explicit changes to the execution pointer (prohibited in GOTO-less 
languages) get replaced by assignments to the state.  It preserves the 
objectionable part of GOTO: that there's no easy way to predict the 
conditions that any statement might execute under.  You can't understand any 
of the program until you understand all of the program.

I think Knuth kept the assembly-language model for his algorithms because it 
promotes his real goal, which is mathematical analysis of the performance of 
the algorithms.  It helps that his algorithms are very short.

As "the quickest way to get a Knuth algorithm running in Python", this is a 
pretty good idea.  My own preference is to get the algo "really" coded in 
Python, but that usually takes a fair bit of time and effort.

Mel.

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


Re: Python Book for a C Programmer?

2012-05-24 Thread Jim Wilson
On 05/23/2012 07:45 PM, hsa...@gmail.com wrote:
> I am trying to join an online class that uses python. I need to brush up on 
> the language quickly. Is there a good book or resource that covers it well 
> but does not have to explain what an if..then..else statement is?
> 
> Thanks.

My opinion: Martelli's "Python in a Nutshell" is the K&R of Python.

Alas, it does discuss if statements, but it doesn't slap you silly with them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Mutable defaults

2021-02-10 Thread Ross Wilson
On Thu, 11 Feb 2564 BE at 12:52 Grant Edwards 
wrote:

> On 2021-02-11, J. Pic  wrote:
>
> > I just meant removing the whole "default value mutating" story, not
> > removing mutable variables. Really, I was wondering if there was a use
> case
> > where this actually turns to an advantage,
>
> I've seen people show how it can be used to provide function-scope
> persistent storage -- the equivalent of declaring a static variable in
> a C function. I don't think I've seen that done in the wild, though.


Not sure this qualifies as "use in the wild", but the memoized naive
Fibonacci is very nice when written this way:

def fib(n, memo={0: 0, 1: 1}):
if n not in memo:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meaning of abbreviated terms

2018-05-12 Thread Ross Wilson
The "plist" abbreviation goes back to at least 1958 as it was used in 
the Lisp implementation [0].  And it may even predate Lisp.  I'm very 
sure that what actually went into a plist has often changed over the 
years, but the name persists.


Lisp also used "association lists" [1] which were a key/value data 
structure, usually called an "alist" or "a-list".


Ross

[0] https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node108.html
[1] https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node153.html


On 12/5/2561 BE 13:45, Bob Martin wrote:

in 793617 20180511 072806 Steven D'Aprano 
 wrote:

On Fri, 11 May 2018 07:20:36 +, Bob Martin wrote:


in 793605 20180511 044309 T Berger  wrote:

On Saturday, May 5, 2018 at 6:45:46 PM UTC-4, MRAB wrote:

On 2018-05-05 17:57, T Berger wrote:

What does the "p" in "plist" stand for? Is there a python glossary
that spells out the meanings of abbreviated terms?


"plist" is "property list". It's listed in the Python documentation.

Thanks for the answer. Missed it till now.

In IBM-speak it was parameter list.



But that's not where plists came from, was it? As I understand it, the
plist data format was invented by Apple, and they called it a property
list.

How old is Apple?
I was using plist for parameter list in OS/360 in 1965.


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


Re: How to start gnuradio

2018-07-31 Thread Ross Wilson
I had a paddle through the manual at
https://www.gnuradio.org/doc/doxygen/page_python_blocks.html and apparently
some DSP operations use numpy.

Ross

On Wed, 1 Aug 2018 at 11:56  wrote:

>
>
> After some research I found out that "sudo apt-get install python-numpy"
> solved the problem.
>
> Can anyone clarify how python-numpy solves the problem?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Client support automation and self service

2016-05-03 Thread musoke wilson
Hi Guys

Currently working with a team to automate business operations and client 
support for a small enterprise.

Key requirements:
Clients to register, log queries and initiate service request through The Web 
and/or Mobile APP
Clear tracking by the CRM team (SR alert through email/mobile APP)
Real time support (IM/email/mobile phone APP)
Analysis & Visualization of enrollment/Usage stats 

We are considering using possibility of using the Python-twisted framework

Kindly advise if python & twisted framework are appropriate tools and any other 
possible open source solutions to avoid re-inventing the wheel

regards


Wilson
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: can't add variables to instances of built-in classes

2016-07-17 Thread Wilson Ong

> Use this feature sparingly, only when you know that there are going to be 
> many (millions rather than thousands) of Test instances.

Why use it sparingly? Is it for extensibility? What if I'm pretty sure that my 
class is going to have exactly these attributes only?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Wind Rose Plotting in Python

2019-09-05 Thread Ross Wilson
On Thu, 5 Sep 2562 at 22:00 Madhavan Bomidi  wrote:

> Hi,
>
> Can someone help me on how to make the wind rose plotting (similar to the
> figure 2 in the paper:
> https://agupubs.onlinelibrary.wiley.com/doi/epdf/10.1029/2011JD016386) in
> Python?
>
> The input file contains the data in 4 columns:
>
> [date, time, wind_speed, wind_direction]
>
> Look forward to your support and suggestions.
>

Hi Madhavan,

I can only see the first page of the paper you linked, so this might not
help.

Try looking at the "windrose" third-party library for matplotlib at
https://github.com/python-windrose/windrose .  The matplotlib page of
third-party libraries is at
https://matplotlib.org/3.1.1/thirdpartypackages/index.html#windrose .

Ross
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: vi and python

2005-01-09 Thread David Wilson
km wrote:
Is there a way to display inbuilt function syntax as the user starts typing a function name with 'Vi' editor in console mode? 
 

Hi there,
Unfortunately due to the highly dynamic nature of Python, this is 
difficult to do reliably. It is one benefit that static typing, to a 
certain extent, would bring to the language. Sadly we don't have that, 
yet. :)

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


Re: Newbie question: Explain this behavior

2005-07-14 Thread Ross Wilson
On Thu, 14 Jul 2005 15:46:40 -0700, David Smith wrote:

> Why does code snippet one work correctly, but not two.  The only
> difference is the placement of the "else".  I know that indentation
> affects execution, but how does it change behavior in the following
> examples?  Thank you.
> 
> 1. for n in range(2, 10):
>for x in range(2, n):
>   if n % x == 0:
>  print n, 'equals', x, '*', n/x
>  break
>else:
>   # loop fell through without finding a factor
>  print n, 'is a prime number'


A quote from "Python: Essential Reference (2/e)" (p56) says it best:

"The 'else' clause of a loop executes only if the loop runs to completion.
This either occurs immediately (if the loop wouldn't execute at all) or
after the last iteration.  On the other hand, if the loop is terminated
early using the 'break' statement, the 'else' clause is skipped."

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


Re: How to connect to UNIX machine from windows box

2005-08-08 Thread Ross Wilson
> I want to connect to unix machine using ssh to run some commands .
> 

I have not tried this, but it might be useful.

http://www.lag.net/paramiko/

HTH,
Ross


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


Re: list insertion

2005-08-24 Thread Ross Wilson
On Tue, 23 Aug 2005 20:58:11 -0700, Randy Bush wrote:

> i am trying to insert into a singly linked list
> 
> hold = self.next
> self.next = DaClass(value)
> self.next.next = hold
> 
> but i suspect (from print statement insertions) that the result
> is not as i expect.  as the concept and code should be very
> common, as i am too old for pride, i thought i would ask.
> 
> mahalo,
> randy

The example above looks like it would work, as long as other
stuff you _don't_ show is fine.  Specifically, how do you 
handle the case when the list is empty?

Better to show a more complete example with output and how that
is not what you expect.

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


Re: Python in C integration and WxPython

2005-09-15 Thread David Wilson
It sounds like your C program and Python script are running under
different interpreters. Your C program almost certainly is using a
Python version that comes with Cygwin, while the script is probably
using a native win32 Python that has wxPython installed.

Assuming this is true, then compiling your C program natively on
Windows should solve the problem. Alternatively, if wxPython is
available for cygwin (possibly via cygwin's X server) then installing
it would also help.


David.


Alain Paschoud wrote:
> Hi all,
>
> I made a small dialog in WxPython. I can run the python script with a
> double-click or through command line, and everything goes fine (dialog
> appears, which means that wx module has been found).
> Then, I decided to write a C program (under Windows, with Cygwin) that
> will read my script (through PyRun_SimpleFile() function) and run it.
> But the system doesn't find the wx module to import...
>
> Traceback (most recent call last):
>   File "Dialog.py", line 2, in ?
> import  wx
> ImportError: No module named wx
>
> How can I say to my program where to search for this module ? I tried to
> set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything.
>
> More generally : Does a C program that embedded python run an external
> executable (interpreter), or does it only load libraries ?
> 
> Thank you very much for any help on this topic.
> 
> Best regards.

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


Re: MySQLdb UPDATE does nothing

2005-09-15 Thread David Wilson
>> sql="UPDATE product_attribute SET index_column = "+str(index)+" WHERE id = 
>> "+str(record2[0])
>> ..
>> cursor.execute(sql)

To allow the DB-API adaptor to correctly take care of value conversion
and SQL escaping for you, this should be written as:

cursor.execute("UPDATE product_attribute SET col1 = %s WHERE id = %s",
(index, record2[0]))


As for why the UPDATE has no effect, which version of MySQL are you
using?


David.

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


Re: python optimization

2005-09-15 Thread David Wilson
For the most part, CPython performs few optimisations by itself. You
may be interested in psyco, which performs several heavy optimisations
on running Python code.

http://psyco.sf.net/

Defining a function inside a loop in CPython will cause a new function
object to be created each and every time the loop runs. No such
automatic optimisation is performed there. For the most part, this lack
of opimisation not only simplifies the CPython implementation, but also
causes code to act much more closely to how it was defined, which is
good for new and advanced users alike.

Other than psyco, IronPython and PyPy are two projects which you might
be interested in if execution performance is of interest to you.

http://www.ironpython.com/
http://codespeak.net/pypy/


David.

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


Re: Looking for system/network monitoring tool written in Python

2005-09-22 Thread David Wilson
See http://pynms.sourceforge.net/
Also see Google. :)


David.

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


Re: Calling python scripts from C# programs

2005-09-22 Thread David Wilson
You should also be aware of IronPython, although it is not suitable for
production use due to its reliance on a beta version of the .NET
runtime. In some future time, IronPython will probably be the cleanest
and simplest way to integrate Python with existing .NET code.

http://www.ironpython.com/

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


ElementTree/DTD question

2005-03-15 Thread Greg Wilson
I'm trying to convert from minidom to ElementTree for handling XML,
and am having trouble with entities in DTDs.  My Python script looks
like this:

--

#!/usr/bin/env python

import sys, os
from elementtree import ElementTree

for filename in sys.argv[1:]:
ElementTree.parse(filename)

--

My first attempt was this XML file:

--



]>


 
  Write an introduction&ldots;
 



--

Running "python validate.py first.xml" produces:

--

Traceback (most recent call last):
  File "validate.py", line 7, in ?
ElementTree.parse(filename)
  File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py",
line 865, in parse
tree.parse(source, parser)
  File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py",
line 589, in parse
parser.feed(data)
  File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py",
line 1160, in feed
self._parser.Parse(data, 0)
  File "C:\Python23\Lib\site-packages\elementtree\ElementTree.py",
line 1113, in _default
raise expat.error(
xml.parsers.expat.ExpatError: undefined entity &ldots;: line 9, column
27

--

All right, pull the DTD out, and use this XML file:

--





 
  Write an introduction&ldots;
 



--

with this minimalist DTD (saved as "swc.dtd" in the same directory as
both the XML file and the script):

--



--

Same error; only the line number changed.  Anyone know what I'm doing
wrong?  (Note: minidom loads it just fine...)

Thanks,
Greg Wilson
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assymetry between a == b and a.__eq__(b)

2004-12-03 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Steven Bethard <[EMAIL PROTECTED]> wrote:
>I believe what Peter Otten was pointing out is that calling __eq__ is
>not the same as using ==, presumably because the code for == checks the
>types of the two objects and returns False if they're different before
>the __eq__ code ever gets called.

Doesn't seem to:



Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class EQ(object):
... def __eq__ (self, other):
... return True
...
>>> eq = EQ()
>>> eq == 3
True
>>> 3 == eq
True
>>> class NEQ(object):
... def __eq__ (self, other):
... return False
...
>>> neq=NEQ()
>>> eq == neq
True
>>> neq == eq
False
>>>



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


Re: assymetry between a == b and a.__eq__(b)

2004-12-04 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Steven Bethard <[EMAIL PROTECTED]> wrote:
>Mel Wilson wrote:
>> In article <[EMAIL PROTECTED]>,
>> Steven Bethard <[EMAIL PROTECTED]> wrote:
>>
>>>I believe what Peter Otten was pointing out is that calling __eq__ is
>>>not the same as using ==, presumably because the code for == checks the
>>>types of the two objects and returns False if they're different before
>>>the __eq__ code ever gets called.
>>
>>
>> Doesn't seem to:
>[snip]
>
>Hmm... maybe it only shows up with subclassing?

:) Seems to:


Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Eq(object):
... def __eq__(self, other):
... return True
...
>>> class Neq(Eq):
... def __eq__(self, other):
... print "(according to Neq)"
... return False
...
>>> eq,neq=Eq(),Neq()
>>> eq==neq
(according to Neq)
False
>>> neq==eq
(according to Neq)
False
>>>



Regards.Mel.














































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


Re: assymetry between a == b and a.__eq__(b)

2004-12-05 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Peter Otten <[EMAIL PROTECTED]> wrote:
>Tim Peters wrote:
>
>> See the Python (language, not library) reference manual, section 3.3.8
>> ("Coercion rules"), bullet point starting with:
>>
>> Exception to the previous item: if the left operand is an
>> instance of a built-in type or a new-style class, and the right
>> operand is an instance of a proper subclass of that type or
>> class, ...
>
>So that is settled then. Not the most likely place to investigate when one
>has just read that "Arguments to rich comparison methods are never coerced"
>in 3.3.1 ("Basic customization"), though.

   At some point Python will cease to be a simple language.

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


Re: exec'ing functions

2004-12-09 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Steven Bethard <[EMAIL PROTECTED]> wrote:
>Jeff Shannon wrote:
>> I was referring to functions which have an internal exec statement, not
>> functions which are created entirely within an exec -- i.e., something
>> like this:
>
>Thanks for the clarification.  Here's the results for some functions
>with internal exec statements:
>
> > cat fib.py
>def fib1(n):
> a, b = 0, 1
> while True:
> a, b = b, a + b
> yield a
>
>
>exec """\
>def fib2(n):
> a, b = 0, 1
> while True:
> a, b = b, a + b
> yield a
>"""
>
>def fib3(n):
> a, b = 0, 1
> while True:
> exec "a, b = b, a + b"
> yield a
>
>def fib4(n):
> exec "a, b = 0, 1"
> while True:
> exec "a, b = b, a + b"
> yield a
>
> >
> > python -m timeit -s "import fib" "fib.fib1(100)"
>100 loops, best of 3: 0.71 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib2(100)"
>100 loops, best of 3: 0.678 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib3(100)"
>100 loops, best of 3: 0.826 usec per loop
>
> > python -m timeit -s "import fib" "fib.fib4(100)"
>100 loops, best of 3: 0.821 usec per loop
>
>I'm not sure I'd say they're *much* slower, but you're right; they're
>definitely slower.

   The thing is, that once you drop local-namespace
optimization, the entire function gets slowed down, possibly
by 40%:



def fib5 (n):
a, b, i = 0, 1, n
while i > 0:
a, b = b, a+b
yield a
i -= 1


def fib6 (n):
exec "a, b, i = 0, 1, n"
while i > 0:
a, b = b, a+b
yield a
i -= 1



f:\home\mwilson\projects\python>python  e:\bin\python23\lib\timeit.py -s "import
 fib" "[i for i in fib.fib5(100)]"
1000 loops, best of 3: 1.95e+003 usec per loop

f:\home\mwilson\projects\python>python  e:\bin\python23\lib\timeit.py -s "import
 fib" "[i for i in fib.fib6(100)]"
100 loops, best of 3: 2.82e+003 usec per loop


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


Re: newbie questions

2004-12-11 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
"houbahop"  wrote:
>Thank you everyone, but I still not understand why such a comon feature like
>passing parameters byref that is present in most serious programming
>languages is not possible in a clean way,here in python.
>
>I have the habit to never use globals as far as possible and this involve
>that my main function is passing some parameters by reference to subs to
>allow them to modify the vars.
>
>I would be sad to break my structured programming scheme because a lack of
>feature.
>
>In others languages you can use things like pointers to strings or
>Mysub(byref MyVar) 
>
>and it does the trick :)

   It isn't a problem with passing by reference.  The
passing-by-reference part works just fine.  Putting in a
print statement to trace what's actually happening:


Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5]
>>> def X(s):
... for i in xrange (len (s)):
... del s[i]
... print 'X:', s
...
>>> X(a)
X: [2, 3, 4, 5]
X: [2, 4, 5]
X: [2, 4]
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in X
IndexError: list assignment index out of range
>>> a
[2, 4]
>>>


   As the last line shows, lots of things got removed from
`a` .. but not everything.  Roel Schroeven explained why.

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


Re: Suggestion for "syntax error": ++i, --i

2004-12-13 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Christian Ergh <[EMAIL PROTECTED]> wrote:
>Ah, ok, i misunderstood you. Well, to mark it as a syntax error sounds
>good, and at the Moment I would not know a case where this conflicts
>with a implementation.

   Well, you can overload prefix `+` and `-` operators on an
object by defining __pos__ and __neg__ methods, so --a, ++a,
+-a, -+a, +-+a and other similar combinations are actually
good syntax, and as useful as you want them to be.

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


Re: exec'ing functions

2004-12-10 Thread Mel Wilson
In article <[EMAIL PROTECTED]>,
Peter Otten <[EMAIL PROTECTED]> wrote:
>Mel Wilson wrote:
>> The thing is, that once you drop local-namespace
>> optimization, the entire function gets slowed down, possibly
>> by 40%:
>It's not that bad as most of the extra time is spend on compiling the
>string.
[ ... ]
>def fib7(n, c=compile("a, b, i = 0, 1, n", "", "exec")):
>exec c
[ ... ]

!


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


Re: change extensions

2005-04-04 Thread David Wilson
Bob Then wrote:
> how can i change all files from one extension to another within a
direcory?

This should work:

import os

def change_exts(suffix, new_suffix, dir_name):
for name in os.listdir(dir_name):
if name.endswith(suffix):
old_pathname = os.path.join(dir_name, name)
new_pathname = old_pathname[:-len(suffix)] + new_suffix
os.rename(old_pathname, new_pathname)



David.

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


compound strip() string problem

2005-04-08 Thread Dylan Wilson
Hi,
I'm new to python and i have a string problem.
My problem is this
--
>>>import time
>>>time = time.asctime()
>>>time
'Fri Apr 08 22:14:14 2005'
>>>ti = time[0:13]
>>>me = time[14:16]
>>>time = ti + me
>>>time
'Fri Apr 08 2214'
--
Now i need to compond that string remove the whitespace if you will.Well
i read up on strip(), lstrip() and rstrip() and all i could deduce was 
that they striped the whitespace from the start and/or end of the 
string.But I tried that anyway and failed.Is there an easier way than i 
did it below? I'm sorry it's ugly and tedious.
--
#!/bin/bash/env python

import os, time
#Figure out what os this is
platform = os.name
#Create string with date, time and extension for our pcap file
ext = '.out'
time = time.asctime()
ti = time[0:13]   #
me = time[14:16] #
time = ti + me  #There has to be a better way to do this?
fo = time[0:3]   #
rm = time[4:7]#
at  = time[11:18]
time = fo + rm + at + ext
#Get rid of yukkies
del ti, me, ext, fo, rm, at
#create command string
flag = '-w'
wincommand = 'c:/progra~1/ethereal/tethereal'
lincommand = '/usr/sbin/./tethereal'
#run tethereal and send the output to a pcap file DDDMMMHHMM.out
if platform == 'nt':
os.system('%s %s %s' % (wincommand, flag, time))
if platform == 'posix':
os.system('%s %s %s' % (lincommand, flag, time))
--
Thanks,
Dylan
--
http://mail.python.org/mailman/listinfo/python-list


parsing RSS XML feed for item value

2013-11-19 Thread Larry Wilson
Wanting to parse out the the temperature value in the "http://rss.weather.com.au/nsw/newcastle";
===


http://rss.weather.com.au/w.dtd";>

Weather.com.au - Newcastle Weather
http://www.weather.com.au/nsw/newcastle
Current conditions and forecast for Newcastle, New 
South Wales.
en-au
Copyright 2013 - Weather.com.au Pty Ltd
Tue, 19 Nov 2013 05:00:00 GMT
Tue, 19 Nov 2013 05:00:00 GMT
15

Newcastle Current Conditions

http://www.weather.com.au/nsw/newcastle/current



Tue, 19 Nov 2013 05:00:00 GMT
C1384837200



...etc
===
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: parsing RSS XML feed for item value

2013-11-20 Thread Larry Wilson
>>> feed.entries[0].w_current
{'temperature': u'20.3', 'dewpoint': u'18.6', 'windgusts': u'29.6', 'rain': 
u'0.6', 'humidity': u'90', 'pressure': u'0.0', 'windspeed': u'22.2', 
'winddirection': u'SSW'}
>>>

in the above I get the subitem as shown. How do I extract the label, values 
pairs?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: parsing RSS XML feed for item value

2013-11-20 Thread Larry Wilson
Thank you folks, now I know what I don't know and have a solution. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best search algorithm to find condition within a range

2015-04-08 Thread Mel Wilson
On Tue, 07 Apr 2015 23:19:49 -0700, jonas.thornvall wrote:

> And you have just created 429496729 unique symbols ;), in a pencil
> stroke.

No.  You did that, when you said base 429496729.  Representing the 
symbols in a computer is no problem, any Python long int can do that.  To 
display the symbols, you can use PIL to make up glyphs out of coloured 
pixels 864x864.  You can keep your glyphs in GIFs.  Where you keep them 
is up to you.  Keeping them in Tumbolia and computing them out as 
required will work well.

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


Re: Best search algorithm to find condition within a range

2015-04-08 Thread Mel Wilson
On Wed, 08 Apr 2015 07:56:05 -0700, jonas.thornvall wrote:

> There is no need for inventing a new set of characters representing
> 32-bit numbers. You will not be able to learn them by heart anyway,
> unless they build on a interpretation system binaries, decimals.

See Jorge Luis Borges, _Funes the Memorious_.  Gotta keep up with the 
literature.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New to Python - block grouping (spaces)

2015-04-19 Thread Mel Wilson
On Sun, 19 Apr 2015 09:03:23 -0700, Rustom Mody wrote:

> Now if Thomson and Ritchie (yeah thems the guys) could do it in 1970,
> why cant we revamp this 45-year old archaic program=textfile system
> today?

Dunno.  Why not?  There's half of you right there.

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


Re: New to Python - block grouping (spaces)

2015-04-19 Thread Mel Wilson
On Mon, 20 Apr 2015 03:53:08 +1000, Steven D'Aprano wrote:

> On Mon, 20 Apr 2015 02:03 am, Rustom Mody wrote:

>> Well evidently some people did but fortunately their managers did not
>> interfere.
> 
> You are assuming they had managers. University life isn't exactly the
> same as corporate culture.

IIRC Thompson, Ritchie, et al. were working at Bell Labs.  Legend has it 
that management would not buy them a Multics, so they were forced to 
write their own using the hardware they had.

Mel.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to properly apply OOP in the bouncing ball code

2015-05-08 Thread Mel Wilson
On Fri, 08 May 2015 08:40:34 -0700, Tommy C wrote:

> I'm trying to apply OOP in this bouncing ball code in order to have
> multiple balls bouncing around the screen. The objective of this code is
> to create a method called settings, which controls all the settings for
> the screen and the bouncing behaviour of multiple balls, under the class
> Ball. However, I keep on getting errors related to attributes (e.g.,
> speed). I'm new to OOP in Python so your help will be much appreciated.
> Thanks in advance.

I did something similar, with little characters running around the screen 
under joystick control.  What I think:

1. Each instance of the Ball class should control the behaviour of one 
ball.
2. The screen settings and global environment generally should be global, 
not stuffed inside the behaviour of a Ball.
3. Keeping the list of Ball instances should be something the main 
section of your program does, not stuffed inside the behaviour of a Ball.

Each of my little GamePlayer objects is subclassed from 
pygame.sprite.Sprite .  I forget what I got by doing this (it's old code) 
but looking up the docs for that class might give you some insights.  
Each GamePlayer object has an "update" method which accepts info from the 
joystick and updates the player's movements, and a "draw" method which 
the main loop calls on displaying every frame, to show the player's new 
position and attitude.

You might be able to do something along these lines.

Mel.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: functions, optional parameters

2015-05-08 Thread Mel Wilson
On Sat, 09 May 2015 03:49:36 +1000, Chris Angelico wrote:

> Yes, but can you *distinguish* them in terms of default argument versus
> code object creation? How do you know that the function's code object
> was created when compile() happened, rather than being created when the
> function was defined? Is there anything that lets you in any way show
> different behaviour based on that timing difference?

This might show that default objects are fixed at run time:

Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = []
>>> def b (arr=a):
...   arr.append ('c')
... 
>>> print repr(a)
[]
>>> b()
>>> print repr(a)
['c']
>>> b()
>>> print repr(a)
['c', 'c']
>>> 

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


Re: Instead of deciding between Python or Lisp for a programming intro course...What about an intro course that uses *BOTH*? Good idea?

2015-05-10 Thread Mel Wilson
On Sun, 10 May 2015 13:43:03 -0700, Chris Seberino wrote:

> Instead of learning only Scheme or only Python for a one semester intro
> course, what about learning BOTH?  Maybe that could somehow get the
> benefits of both?
> 
> I'm thinking that for the VERY beginning, Scheme is the fastest language
> to get beginners up and running writing code due to the extremely
> minimal simple syntax.
> 
> I'm thinking half way into the semester, instead of moving into
> intermediate Scheme, perhaps that is a good time to switch to Python?
> 
> Would a little strong intro to 2 nice languages in one semester be
> same/good/worse/better than just 1?

The first course I took, we learned Algol-60, then when we couldn't get 
computer time for compiles, we were asked to pick up FORTRAN-IV on the 
side.  So we "published" our solutions to the class problems in Algol and 
re-wrote them to be run in FORTRAN.  It was a fine first-hand look at 
what the "general purpose" in General Purpose Computer really meant.  
There was no confusing the machine and the language after that.  Scheme/
Python would be even more radical, I think.  If you can put them across 
effectively, I say go for it.

Mel.
> 
> cs

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


Re: anomaly

2015-05-11 Thread Mel Wilson
On Sun, 10 May 2015 14:12:44 -0500, boB Stepp wrote:

> I have to admit being surprised by this, too. I am just now studying on
> how to write my own classes in Python, and have come to realize that
> doing this is *possible*, but the *surprise* to me is why the language
> design allowed this to actually be done.

Read Cory Doctorow lately on the War Against General Purpose Computing, 
where a bunch of people who don't really understand are trying to make it 
impossible for any computer to do something that is The Wrong Thing.  Or 
gently approach the relevant computing theory through Doug Hofstadter's 
_Goedel, Escher, Bach_, or some essays in _Metamagical Themas_.  
Generally speaking, making a computer totally incapable of doing Wrong 
Things leaves it incapable of doing anything at all.

Mel.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: anomaly

2015-05-11 Thread Mel Wilson
On Tue, 12 May 2015 02:35:23 +1000, Steven D'Aprano wrote:

> On Mon, 11 May 2015 11:37 pm, Mel Wilson wrote:
> 
>> On Sun, 10 May 2015 14:12:44 -0500, boB Stepp wrote:
>> 
>>> I have to admit being surprised by this, too. I am just now studying
>>> on how to write my own classes in Python, and have come to realize
>>> that doing this is *possible*, but the *surprise* to me is why the
>>> language design allowed this to actually be done.
>> 
>> Read Cory Doctorow lately on the War Against General Purpose Computing,
>> where a bunch of people who don't really understand are trying to make
>> it impossible for any computer to do something that is The Wrong Thing.
> 
> I think you are conflating two different ideas of "the Wrong Thing".

I don't think so.  A formal solution to a problem, i.e. a solution coded 
as a computer program, is limited to the things that can be done using 
formal techniques.  Whether it's people trying to enact their social 
standards in code, or whether it's people trying to nail the door shut 
against everything they "don't expect", or "think is illogical", the 
limits will still be there.

Mel.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use and usefulness of the as syntax

2011-11-12 Thread Mel Wilson
candide wrote:

> First, could you confirm the following syntax
> 
> import foo as f
> 
> equivalent to
> 
> import foo
> f = foo
> 
> 
> 
> Now, I was wondering about the usefulness in everyday programming of 
the
> as syntax within an import statement. [ ... ]

It gives you an out in a case like

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> os = 5  # number of 'o's
>>> import os as opsys
>>> os
5
>>> opsys


(This is an instance of what arnaud mentioned.)

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


Re: Close as Many Files/External resourcs as possible in the face of exceptions

2011-11-21 Thread Mel Wilson
GZ wrote:
> Here is my situation. A parent object owns a list of files (or other
> objects with a close() method). The close() method can sometimes 
fail
> and raise an exception. When the parent object's close() method is
> called, it needs to close down as many files it owns as possible, 
even
> if the close() function of some files fail. I also want to re-raise 
at
> least one of the original exceptions so that the outer program can
> handle it.
[ ... ]
> 
> It will re-raise the first exception and preserve the context and
> close as many other files as possible while ignoring any further
> exceptions.
> 
> But this looks really awkward. And in the case that two files fail 
to
> close, I am not sure the best strategy is to ignore the second
> failure.

I imagine you could save any caught exception instances in a list and 
study them later.

Mel.

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


Re: correct usage of a generator?

2011-11-28 Thread Mel Wilson
Tim wrote:

> Hi, I need to generate a list of file names that increment, like 
this:
> fname1
> fname2
> fname3 and so on.
> 
> I don't know how many I'll need until runtime so I figure a 
generator is
> called for.
> 
> def fname_gen(stem):
> i = 0
> while True:
> i = i+1
> yield '%s%d' % (stem,i)
> 
> blarg = fname_gen('blarg')
> boo = fname_gen('boo')
> 
> n = 3
> for w in range(0,n):
> in_name = blarg.next()
> out_name = boo.next()
> 
> 
> This works, but is it the 'normal' way to accomplish the task when 
you
> don't know 'n' until run-time? thanks,

It's kind of overkill in the toy demo example, but if the main loop is 
a little more abstract, e.g.

for task in task_supplier():
in_name = blarg.next()
out_name = boo.next()
handle_task (task, in_name, out_name)

then it's obviously a good thing.

One quibble (that Peter Otten also suggested): if your business rules 
expect that files blarg25 and boo25 (for example) work together, then 
you'd be better off generating them together as a pair in a single 
generator call.  As it is, there's a chance of the blarg and boo 
generators getting out of step and supplying mismatched names.

Mel.

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


Re: Making the case for "typed" lists/iterators in python

2011-12-16 Thread Mel Wilson
Chris Angelico wrote:

> It's no more strange than the way some people omit the u from colour. :)

Bonum Petronio Arbiteri, bonum mihi.

Mel.

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Mel Wilson
Chris Angelico wrote:

> On Fri, Dec 23, 2011 at 1:13 AM, Hans Mulder  wrote:
>> How about:
>>
>> 
>> ...
>> 
>>
>> More more readable!  And it's a standard!
> 
> Unfortunately it's not Pythonic, because indentation is insignificant.

Easy-peasy:

 
 

Mel.

> We need to adopt a more appropriate form. Eliminate all the 
> tags and use indentation to mark the ends of elements.
> 
> ChrisA
> PS. Brilliant, sir, brilliant! I take off my cap to you.

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


Re: Early and late binding [was Re: what does 'a=b=c=[]' do]

2011-12-23 Thread Mel Wilson
Steven D'Aprano wrote:
> On Fri, 23 Dec 2011 13:13:38 +, Neil Cerutti wrote:
>> On 2011-12-23, Neil Cerutti  wrote:
>> ...you know, assuming it wouldn't break existing code. ;)
> 
> It will. Python's default argument strategy has been in use for 20 years.
> Some code will rely on it. I know mine does.

In a tool that's meant for other people to use to accomplish work of their 
own, breaking workflow is a cardinal sin.

In a research language that's meant always to be up-to-date with the concept 
of the week, not so much.

Mel.

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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Mel Wilson
Adam Funk wrote:

> (Warning: this question obviously reflects the fact that I am more
> accustomed to using Java than Python.)
> 
> Suppose I'm creating a class that represents a bearing or azimuth,
> created either from a string of traditional bearing notation
> ("N24d30mE") or from a number indicating the angle in degrees as
> usually measured in trigonometry (65.5, measured counter-clockwise
> from the x-axis).  The class will have methods to return the same
> bearing in various formats.
> 
> In Java, I would write two constructors, one taking a single String
> argument and one taking a single Double argument.  But in Python, a
> class can have only one __init__ method, although it can have a lot of
> optional arguments with default values.  What's the correct way to
> deal with a situation like the one I've outlined above?

Cleanest from the point of view of the class source code would be factory 
functions at the module level, or special classmethods to deal with the less 
common cases.  You see this a lot in wxPython when they have to deal with 
overloaded C++ constructors.

Most like the Java would be to check within __init__ for a string argument 
that could be parsed as a bearing, and failing that fall back to treating 
the argument as a numeric angle.

Neither fish nor fowl would be to accept named arguments for the different 
kinds of values.

Mel.

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


Re: verify the return value of a function

2012-01-20 Thread Mel Wilson
Jean-Michel Pichavant wrote:

> isinstance is fine, if you could find the source where it is
> discouraged... Could be a consequence of some specific context.
> However, checking types in OOP is in general a failure. Unitary tests
> are possibly an exception.

I think it's discouraged when people try to write big overloaded functions 
that check the types of the arguments to decide what they should be doing.
In diagnostics and tests like the OP's there should be no problem.

Mel.

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


Re: Newline at EOF Removal

2006-01-09 Thread Dylan Wilson
Do you mean somthing like this?

>>> f = open("file.txt")
>>> w = open('outfile.txt', 'w')
>>> for line in f.split('\n'):
...w.write(line)
...
>>> w.close()
>>> '\n' in open('/home/wandleg/outfile.txt').read()
False

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


Re: how to improve this simple block of code

2006-01-11 Thread Mel Wilson
py wrote:
> Say I have...
> x = "132.00"
> 
> but I'd like to display it to be "132" ...dropping the trailing
> zeros...

print '%g' % (float(x),)

might work.

Mel.

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


Warning when new attributes are added to classes at run time

2006-07-19 Thread Matthew Wilson

I sometimes inadvertently create a new attribute on an object rather
update a value bound to an existing attribute.  For example:

In [5]: class some_class(object):
   ...:  def __init__(self, a=None):
   ...:  self.a = a
   ...:

In [6]: c = some_class(a=1)

In [7]: c.a
Out[7]: 1

In [8]: c.A = 2

I meant to update c.a but I created a new c.A.  I make this mistake
probably hourly.

I suspect adding attributes at run time can be a beautiful thing, but in
this particular instance, I'm only using this feature to hurt myself.

I wrote a simple class that will warn me when I make this mistake in the
future:

import warnings

class C(object):

warn_on_new_attributes = True

standard_attributes = []

def __setattr__(self, name, value):

if self.warn_on_new_attributes \
and name is not 'warn_on_new_attributes' \
and name not in self.standard_attributes:

warnings.warn("%s has no standard attribute %s."
  % (self.__class__.__name__, name))


self.__dict__[name] = value


class C1(C):

standard_attributes = ['a1', 'a2']


class C2(C):

warn_on_new_attributes = False

# Do some simple testing.
c11 = C1()
c11.a1 = 1
c11.a2 = 2
c11.a3 = 3
c11.a4 = 4

# Disable warnings for this instance.
c12 = C1()
c12.warn_on_new_attributes = False
c12.a1 = 1
c12.a2 = 2
c12.a3 = 3
c12.a4 = 4

c11.a5 = 5

# Use an object that has warnings disabled by default.
c2 = C2()
c2.a1 = 1
c2.a2 = 2
c2.a3 = 3
c2.a4 = 4

# enable warnings for this object.
c2.warn_on_new_attributes = True
c2.a1 = 1
c2.a5 = 5


All comments are welcome.  Is there a better way of implementing the
above class, OR, is this approach generally wrong-headed?  Am I the only
one that makes this mistake?

TIA

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Warning when new attributes are added to classes at run time

2006-07-20 Thread Matthew Wilson
On Thu 20 Jul 2006 04:32:28 AM EDT, Bruno Desthuilliers wrote:
>> self.__dict__[name] = value
> Make it:  
>   object.__setattr__(self, name, value)
>
> Your approach will lead to strange results if you mix it with properties
> or other descriptors...

Thanks!

>> class C1(C):
>> 
>> standard_attributes = ['a1', 'a2']
>
> DRY violation here. And a potential problem with inheritance (as always
> with class attributes).

Considering I had to look up what DRY meant before replying to this
message, I may be missing your point.  Is the repeat here that each
subclass has to define its own list of standard attributes?   Or, is it
that the standard_attributes list holds strings, but I could build that
list up by looking at my existing attributes?

If you're feeling charitable, can you explain what you mean a little
more?

TIA


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Need advice on how to improve this function

2006-08-20 Thread Matthew Wilson
I wrote a function that converts a tuple of tuples into html.  For
example:

In [9]: x
Out[9]:
('html',
 ('head', ('title', 'this is the title!')),
 ('body',
  ('h1', 'this is the header!'),
  ('p', 'paragraph one is boring.'),
  ('p',
   'but paragraph 2 ',
   ('a', {'href': 'http://example.com'}, 'has a link'),
   '!')))


In [10]: as_html(x, sys.stdout)




this is the title!





this is the header!

paragraph one is boring.

but paragraph 2 http://example.com";>has a link!






I'd like to know ways to make it better (more efficient, able to deal
with enormous-size arguments, etc).  How would I write this as a
generator?

Here's the definition for as_html:

def as_html(l, s):
"Convert a list or tuple into html and write it to stream s."
if isinstance(l, (tuple, list)):
tagname = l[0]
if isinstance(l[1], dict):
attributes = ' '.join(['%s="%s"' % (k, l[1][k]) for k in l[1]])
s.write('<%s %s>' % (tagname, attributes))
else:
s.write('<%s>' % tagname)
if tagname in ('html', 'head', 'body'):
s.write('\n\n')
for ll in l[1:]:
as_html(ll, s)
s.write('' % tagname)
if tagname not in ('a', 'b', 'ul'):
s.write('\n\n')
elif isinstance(l, str):
s.write(l)


All comments welcome. TIA

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using import * with GUIs?

2006-05-31 Thread Mel Wilson
John Salerno wrote:
> Hi all. Quick question (but aren't they all?) :)
> 
> Do you think it's a good idea to use the 'from  import *' 
> statement when using a GUI module? It seems on wxPython's site, they 
> recommend using import wx nowadays, but I wonder if that advice is 
> followed. Also, I'm still reading some Tkinter docs that seem to use 
> 'from Tkinter import *' a lot.
> 
> I understand the danger of doing this, but is it safer in these cases, 
> given the more specific names that GUI frameworks tend to use 
> (sometimes!)? Or should you still qualify all your calls with the module?
More specific?  I dunno, I have trouble thinking of that
huge multitude of names in wx as specific.  Who knows what
in all that might collide with names you devise?

My formative experience came when I was looking at Python
Imaging Library Demo code.  Somebody did a simple call to
open and got returned an entire Jpeg image object.  I knew
that open was destined to take arguments other than simple
file paths, and return things other than simple files, but
it seemed awfully soon.  Then I got suspicious, looked at
the top of the code, and saw "from Image import *"

So a word, too, to people writing demo programs.  Writing
"from mycode import *" obscures which code is actually yours
in the code following.  Kind of defeats the purpose.

 Cheers,Mel.

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


Re: carshing the interpreter in two lines

2006-06-03 Thread Mel Wilson
sam wrote:
> tomer:
> 
> It is my opinion that you would loose performance if the Python
> interpreter had the additional task of verifying byte code. It might be
> more appropriate to have a preprocessor that did the verifying as it
> compiled the byte code.

Possibly.  A good book on the topic is Douglas Hofstadter's 
_Goedel, Escher, Bach: an Eternal Golden Braid_.

Particularly starting from the chapter "Contracrostipunctus".

 Cheers,Mel.



> Sam Schulenburg
> 
> gangesmaster wrote:
>> the following (random) code crashes my interpreter
>> (python 2.4.3/winxp):
>>
>> from types import CodeType as code
>> exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
>>
>> i would expect the interpreter to do some verifying, at least for
>> sanity (valid opcodes, correct stack size, etc.) before executing
>> artbitrary code... after all, it was the BDFL who said """I'm not
>> saying it's uncrashable. I'm saying that if you crash it, it's a
>> bug unless proven harebrained."""
>>
>>
>> -tomer
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: carshing the interpreter in two lines

2006-06-04 Thread Mel Wilson
sam wrote:
> Mel:
> Wow that book brings back memories. I scanned my copy to review the
> subject covered, and came to the conclusion that mind reading
> algorithms are the answer.
> 
I gathered from somewhere (but not the index to Andrew 
Hodges' biography) that Turing was toying with an idea for 
"oracles", where a computation would be allowed to call out 
sometimes to a non-computational process to obtain some 
required result.  Used maybe by  interactive debugging programs.

     Cheers,Mel.

> Mel Wilson wrote:
[ ... ]
>>Douglas Hofstadter's _Goedel, Escher, Bach: an Eternal Golden Braid_.
[ ... ]
>> "Contracrostipunctus".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposed new PEP: print to expand generators

2006-06-04 Thread Mel Wilson
Terry Reedy wrote:
> "James J. Besemer" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> I propose that we extend the semantics of "print" such that if the object 
>> to
>> be printed is a generator then print would iterate over the resulting
>> sequence of sub-objects and recursively print each of the items in order.
> Iterating over an iterator is usually destructive.  So you would be 
> printing what it was but no longer is.  This is why iterators are printed 
> differently from sequences.

I guess the motivation is the case of people who would set 
up an iterator specifically to print from it.

print-as-debug-aid would get badly broken by the proposal, 
and I'd find that painful.

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


random.jumpahead: How to jump ahead exactly N steps?

2006-06-21 Thread Matthew Wilson
The random.jumpahead documentation says this:

Changed in version 2.3: Instead of jumping to a specific state, n steps
ahead, jumpahead(n) jumps to another state likely to be separated by
many steps..

I really want a way to get to the Nth value in a random series started
with a particular seed.  Is there any way to quickly do what jumpahead
apparently used to do?

I devised this function, but I suspect it runs really slowly:

def trudgeforward(n):
'''Advance the random generator's state by n calls.'''
for _ in xrange(n): random.random()

So any speed tips would be very appreciated.

TIA


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


I wish I could add docstrings to vars.

2006-09-12 Thread Matthew Wilson

I build a lot of elaborate dictionaries in my interpreter, and then I
forget exactly how they work.  It would be really nice to be able to add
notes to the dictionary.

Is there some way to do this now?

Matt


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Code to add docstrings to classes

2006-09-12 Thread Matthew Wilson
On Tue 12 Sep 2006 10:06:27 AM EDT, Neil Cerutti wrote:
> Writing a thin wrapper around the dictionary might be beneficial,
> and would also furnish a place for the docstrings. 

I wrote a function that hopefully does just that.  I'm not very savvy at
doing this class-factory stuff, so any advice would be welcome.

def vd(C):

"""

Return a subclass of class C that has a instance-level attribute _vardoc.

"""

class VDC(C):

def __init__(self, *args, **kwargs):

vardoc = kwargs.get('vardoc')
if vardoc:
assert isinstance(vardoc, str), "vardoc must be a
string!"
kwargs.pop('vardoc')
self._vardoc = vardoc

C.__init__(self, *args, **kwargs)

def __repr__(self):

if self._vardoc:
return self._vardoc + "\n" + C.__repr__(self)

else:
return C.__repr__(self)

return VDC


def test_vd():

i = vd(int)(6)
i._vardoc = "integer!"
assert isinstance(i, int)

d = vd(dict)(a=1, b=2, c=i, vardoc="dict!")
assert d['a'] == 1
assert d['c'] == 6
assert isinstance(d, dict)



-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


eval(repr(object)) hardly ever works

2006-09-13 Thread Matthew Wilson

I understand that idea of an object's __repr__ method is to return a
string representation that can then be eval()'d back to life, but it
seems to me that it doesn't always work. 

For example it doesn't work for instances of the object class:

In [478]: eval(repr(object()))

   File "", line 1
 
 ^
SyntaxError: invalid syntax

It seems to work for types like integers and dictionaries and lists,
but not for much else.

Any thoughts?


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval(repr(object)) hardly ever works

2006-09-13 Thread Matthew Wilson
On Wed 13 Sep 2006 10:38:03 AM EDT, Steve Holden wrote:
> That's intentional. Would you have it return the code of all the methods 
> when you take the repr() of a class?

I don't think that would be required.  Couldn't you return a string with
a call to the constructor inside?  That's what sets.Set seems to do:

In [510]: from sets import Set

In [511]: s = Set()

In [512]: s.add('baloney')

In [513]: repr(s)
Out[513]: "Set(['baloney'])"

In [514]: eval(repr(s))
Out[514]: Set(['baloney'])

> regards
>   Steve

PS: I read your python web programming book a few years ago.



-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


How to iterate through a sequence, grabbing subsequences?

2006-09-29 Thread Matthew Wilson
I wrote a function that I suspect may already exist as a python builtin,
but I can't find it:

def chunkify(s, chunksize):
"Yield sequence s in chunks of size chunksize."
for i in range(0, len(s), chunksize):
yield s[i:i+chunksize]

I wrote this because I need to take a string of a really, really long
length and process 4000 bytes at a time.

Is there a better solution?

Matt

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


How to query a function and get a list of expected parameters?

2006-09-29 Thread Matthew Wilson
I'm writing a function that accepts a function as an argument, and I
want to know to all the parameters that this function expects.  How can
I find this out in my program, not by reading the source?

For example, I would want to know for the function below that I have to
pass in two things:

def f(x1, x2): return x1 * x2

It would be nice to get the names also.

All help is welcome.

TIA

Matt



-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


How to coerce a list of vars into a new type?

2006-10-02 Thread Matthew Wilson

I want to verify that three parameters can all be converted into
integers, but I don't want to modify the parameters themselves.

This seems to work:

def f(a, b, c):

a, b, c = [int(x) for x in (a, b, c)]

Originally, I had a bunch of assert isinstance(a, int) statements at the
top of my code, but I decided that I would rather just check if the
parameters can be converted into integers.

The new a, b, and c are all different objects, with different id values.
Anyhow, this all seems like black magic to me.  Can anyone explain what
is going on?

Is it as simple as call-by-value?




-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I make a class that can be converted into an int?

2006-10-02 Thread Matthew Wilson
What are the internal methods that I need to define on any class so that
this code can work?

c = C("three")

i = int(c) # i is 3

I can handle the part of mapping "three" to 3, but I don't know what
internal method is called when int(c) happens.

For string conversion, I just define the __str__ method.  What's the
equivalent for int?  For float, too, while I'm at it?

TIA

Matt

-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >