Re: What's in a name?

2011-08-09 Thread Ron
On Aug 1, 10:11 am, Andrew Berg  wrote:
> Hmm
> How about Rainbow Video Encoder Wrapper (Rainbow View for short - RView
> is taken, possibly multiple times)?
> I added an arbitrary word to a generic name, and the result doesn't seem
> to be taken by anything software-related. It wraps more than just video
> encoders (in fact, x264 will likely be the only one it wraps until it's
> matured quite a bit :P ), but I didn't want the name to get too long.
> The module itself will likely be called just rainbow.py.
>
> --
> CPython 3.2.1 | Windows NT 6.1.7601.17592 | Thunderbird 5.0
> PGP/GPG Public Key ID: 0xF88E034060A78FCB

Andrew

How about SuperMux

with a command line interface called Cyclops
and a GUI fornt end called VisualMux
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Segmentation Fault on exit

2011-08-10 Thread ron
On Aug 6, 6:35 am, Vipul Raheja  wrote:
> Hi,
>
> I have wrapped a library from C++ to Python using SWIG. But when I
> import it in Python, I am able to work fine with it, but it gives a
> segmentation fault while exiting. Following is the log:
>
> vipul@vipul-laptop:~/ossim-svn/src/pyossim/swig$ python
> Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
> [GCC 4.4.5] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> import pyossim
>
> * Do some stuff *
> >>> exit()
>
> Segmentation fault
> vipul@vipul-laptop:~/ossim-svn/src/pyossim/swig$
>
> Kindly help.
>
> Thanks and Regards,
> Vipul Raheja

Check out Valgrind.  It's easy to set up, runs like gdb, but keeps
track and flags any offending memory use at the c level. Then just
need to find the calling python code.
-- 
http://mail.python.org/mailman/listinfo/python-list


learnpython.org - an online interactive Python tutorial

2011-04-20 Thread Ron
Hey everyone.

I've written an online interactive Python tutorial atop Google App Engine: 
http://www.learnpython.org.

All you need to do is log in using your Google account and edit the wiki to add 
your tutorials.

Read more on the website.

Thanks for your help, and I would appreciate if you help me spread the word, 
and give me feedback on the website.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: learnpython.org - an online interactive Python tutorial

2011-04-20 Thread Ron
Thanks! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Tix BUG? Where to submit?

2005-11-14 Thread Ron
I've been developing a piece of software using Tix.  In particular, I'm 
using the HList widget.  I was attempting to use the info_bbox() mentod of 
that class to get the bounding box of a list entry.  I'm using the release 
version Python 2.4.2.  When I look in Tix.py I see that info_bbox() is not 
available.

Well, I don't know much about the library, Tk or Tix but it appears that all 
the other methods are implemented.  Using those as templates I attempted to 
add the function just to see what would happen.  I added the folloing to 
Tix.py line 961.

def info_bbox( self, entry ):
   coords = self.tk.call( self._w, 'info', 'bbox', entry ).split( ' ')
   return map( int, coords )


Surprising to myself, this was all that it took to make this work.  So I'm 
not sure why this method was left out.  Could it have been an oversight?

Anyway, where would I subit this report to have it considered that this be 
added to Tix?

Thanks for your help.

Ron Provost 


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


Application Plugin Framework

2005-11-21 Thread Ron
Hello,

I'm attempting to develop a  plugin framework for an application that I'm 
working on.  I wish to develop something in which all plugins exist in a 
directory tree.  The framework need only be given the root of the tree.  The 
framework then uses os.path.walk to search all for all files named 
'plugin.pyc'.  These are then loaded using imp.load_compiled().  They need 
contain only one variable called 'plugin' which is a reference to an 
instance of the plugin object.  This is extrated from the loaded module 
using getattr.  After that, the plugins are easy to work with since they 
implement a standard interface.  Or so the theory goes.  And this does work 
fine provided the plugin is implemented entirely within that one file.  If 
there are support modules that the main plugin module imports, which exist 
in the plugin's directory, then I get problems.  The imports fail.  I get 
"ImportError:  No module named "

Here's PluginManager.py:


import os


class PluginManager( object ):
   def __init__( self, pluginDir ):
  self._plugins = { }

  os.path.walk( pluginDir, self._addPlugin, None )

   def _addPlugin( self, arg, dirname, names ):
  import imp

  for filename in names:
 fullFilename = os.path.join( dirname, filename )
 if os.path.isfile( fullFilename ) and (filename == 'plugin.pyc'):
module = imp.load_compiled( 'plugin', fullFilename )
self._plugins[ plugin.name ] = getattr( module, 'plugin' )
return

PM = PluginManager( r'C:\Personal\SWDev\ModuleTest' ) # Root of the 
plugin directory tree

print 'Plugin List: ', PM._plugins.keys()

for name,plugin in PM._plugins.iteritems():
   plugin.doSomething( )

print 'done!'

###
My plugin.py file is in C:\Personal\SWDev\ModuleTest\Plugins\MyPlugin.  It's 
called plugin.pyc (which I compiled from the following source by importing 
it into the interactive python shell.
###

import work


class MyPlugin( object ):
   def __init__( self ):
  self.name  = 'MyPlugin'

   def doSomething( self ):
  work.foo( )


plugin = MyPlugin( )

###
Finally, work.py is in the same directory as plugin.py
###

def foo( ):
   print 'foo called'

##
Does anybody have any thoughts on how to get this, or something similar, to 
work?  I really just want to be able to load plugins into my app without 
having to modify my app's source code, or modify some list of plugins.  I 
also would like to allow each plugin to have its own subdirectory so they 
are easily installed or removed.

Thanks for your help.




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


Getting the process list on win98

2005-03-14 Thread Ron
I've written a screen saver which opens multiple copies on windows 98. 
I'm trying to check the process list to determine if it is already running.

So far all the example win32 routines I've found, through google, only 
work on newer xp and nt versions of windows. This is the current attempt 
to get the process list on windows 98:

def GetProcessNameList():
from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
names = []
for process in processes:
names += [process.Properties_('Name').Value]
return names
def IsRunning( filename ):
n = 0
for process in GetProcessNameList():
if process.lower() == filename.lower():
n += 1
return n
Then in the startup section:
filename = os.path.basename(sys.argv[0])
# Wait for preview window to exit.
t = clock()
while IsRunning( filename) > 1 and clock() < t + 3:
sleep(.01)
# Start screen saver if only self is running.
if IsRunning( filename)==1:
saver = Screensaver()
saver.launchScreenSaver()
Results in this error on windows 98, works fine on windows xp:
Traceback (most recent call last):
  File "Aztec.pyw", line 255, in ?
  File "Aztec.pyw", line 38, in IsRunning
  File "Aztec.pyw", line 29, in GetProcessNameList
  File "win32com\client\__init__.pyc", line 73, in GetObject
  File "win32com\client\__init__.pyc", line 88, in Moniker
pywintypes.com_error: (-2147221014, 'Moniker cannot open file', None, None)
The program is in python v2.3 and packaged using pyexe, and inno setup.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beware complexity

2005-03-14 Thread Ron
Philip Smith wrote:
I wonder if anyone has any thoughts not on where Python should go but where 
it should stop?
My feelings on this is, it's a problem of organization and 
documentation.  Do both of these well, and things will be manageable.

I would like to see a bit cleaner file organization framework. I think 
keeping the different parts/modules/utilities/etc.  Seperate and in 
their own place would solve a lot of distribution/installation problems.

Having a central distribution place for people to download third party 
modules in a standard install/uninstall package format would also help.

# Example directory structure.
python24
main
core# interpreter, dll's, and min.
tools   # test scripts
examples
docs
standard_modules# modules included in distribution
module name
core# standard module dlls
tools
examples
docs
next module name
core
tools
examples
docs

extend_modules  # 3rd party extension modules
"module name"
core# dlls
tools   # helpfull scripts
examples
docs

tools
idle
core
tools
examples
docs
py2exe
core
tools
examples
docs
document_reader 
# script to read and search all doc files
# and run related examples scripts.
core
tools
examples
docs
Ron
--
http://mail.python.org/mailman/listinfo/python-list


__getitem__ method on (meta)classes

2005-03-14 Thread ron

Why doesn't this work?

>>> def foo(lst):
...   class baz(object):
... def __getitem__(cls, idx): return cls.lst[idx]
... __getitem__=classmethod(__getitem__)
...   baz.lst = lst
...   return baz
...
>>> f = foo([1,2,3])
>>> f[0]
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsubscriptable object
>>> f.__getitem__(0)
1
>>>


I thought x[y] and x.__getitem__(y) were supposed to always be
synonymous.

Thanks,
rg

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


Re: Getting the process list on win98

2005-03-15 Thread Ron
Thanks for the reply Roger,
Since will put this on my web site for general use, I don't want users 
to have to install additional software.

I'll try win32com.client.Dispatch('Wbemscripting.Swbemlocator') see what 
that does.

As a last resort, I use a registry key as a run status varable.  Not my 
first choice, but I think it will work for all win9x systems.

Roger Upole wrote:
   WMI didn't come installed on Win98.  You can download the
addon for win98 from Microsoft.
   If I recall correctly from when I last used it on 98, GetObject
didn't work for wmi.  You might have to use
win32com.client.Dispatch('Wbemscripting.Swbemlocator')
to create the object.
hth
 Roger
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting current variable name

2005-03-16 Thread Ron
pl wrote:
Hi all,
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.
Use the locals() function instead of globals().
Thanks by the way, I was wondering how to do this also, your post, and 
Daniel pointing out 'is', helped me work this out.  There should be an 
easier way that doesn't require stepping though the name list.

This doesn't use lists in the same way, but I think it answers your 
question.

def getvinfo(vars, v):
"""
vars is locals()
v is [varable]
Use an one item list to pass single varables by reference.
"""
for n in vars.keys():
if vars[n] is v[0]:
return n, v[0], type(v[0])
a = 101
b = 2.3
c = True
print getvinfo(locals(), [a])
print getvinfo(locals(), [b])
print getvinfo(locals(), [c])
>>>
('a', 101, )
('b', 2.2998, )
('c', True, )
This could be useful for printing error messages and debugging info.
Ronald Adam
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting current variable name

2005-03-17 Thread Ron
Jeff Shannon wrote:
Are you sure that you really need that single-element list?
No I'm not sure, I thought I found a concdition where it made a 
difference while playing with it, but I don't recall just what 
circumstance it was?

Don't forget, in Python, all names are references.  You only have to be 
careful when you start re-binding names...
Since more than one name can bind to an object, this would be better.
def getvinfo( vars, v ):
names = []
for n in vars.keys():
if vars[n] is v:
names.append(n)
return names, v, type(v)
a = [2]
b = [2]
c = b
print getvinfo( locals(), a )
print getvinfo( locals(), b )
print getvinfo( locals(), c )
>>>
(['a'], [2], )
(['b', 'c'], [2], )
(['b', 'c'], [2], )
>>>






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


Re: Simple account program

2005-03-17 Thread Ron
Igorati wrote:
Hello all, I am still needing some help on this code, I have gone a bit
further on it. Thank you for the help. I am trying to understand how to
make the file searchable and how I am to make the deposit and withdrawl
interact with the transaction class. 
I need to just search the file only for the deposits and withdrawls and
the amount in the account with a time stamp. Thank you for your
assistance.
Hi Igorati,
In a ledger program I wrote, I setup the account classes something like 
below.  I'm not sure what you mean by searching a file.  Are you trying 
to read an already existing file?

class Transaction:
   def __init__(self):
self.name = ''
self.amount = 0.0
self.type = ''
class Account:
   def __init__(self, name=''):
self.name = name
self.ledger = []
   def newtransaction(self, name, amount, type):
transaction = Transaction()
transaction.name = name
transaction.amount = amount
transaction.type = ''
self.ledger.append(transaction)
   def getbalance(self):
balance = 0.0
for transaction in self.ledger:
balance += transaction.amount
return balance
# Within your main program somewhere.
myaccount = Account( 'Savings Account')
#  get transaction data from user or file
name = 'cash'
amount = 20.0
type = 'deposite'
myaccount.newtransaction( name, amount, type)
print "%s Balance is $ %.2f" % (myaccount.name, myaccount.getbalance())


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


Re: Simple account program

2005-03-17 Thread Ron
The indentation got messed up a bit, it should look like this.
class Transaction:
def __init__(self):
self.name = ''
self.amount = 0.0
self.type = ''
class Account:
def __init__(self, name=''):
self.name = name
self.ledger = []
def newtransaction(self, name, amount, type):
transaction = Transaction() # Create transaction instance.
transaction.name = name
transaction.amount = amount
transaction.type = ''
self.ledger.append(transaction)
def getbalance(self):
balance = 0.0
for transaction in self.ledger:
balance += transaction.amount
return balance
# Within your main program somewhere.
# Create an instance of the account object.
myaccount = Account( 'Savings Account')
#  get transaction data from user or file
name = 'cash'
amount = 20.0
type = 'deposite'
myaccount.newtransaction( name, amount, type)
print "%s Balance is $ %.2f" % (myaccount.name, myaccount.getbalance())
--
http://mail.python.org/mailman/listinfo/python-list


Re: survey of modules to be added to stdlib

2005-03-18 Thread Ron
On 18 Mar 2005 14:16:01 -0800, "Alia Khouri" <[EMAIL PROTECTED]>
wrote:

>This is an informal survey to gauge the community's interest in adding
>popular modules to the python standard library.

I would prefer to have a install utility included that retrieves a
list of modules we can install, update, or uninstall, from the web in
a consistent easy way.  It would really be nice if they listed what
modules they were dependant on also.

If the updater listed them by who distributes and maintains them, it
could include many third party modules as well and not need to include
them in the standard library.

But I think something like this would be quite always off  Python
3000?  4000?   

Not everyone needs the same modules.  I use win32, py2exe, pmw/blt,
visual, and ctypes,  and numeric because I think it needed by either
blt or visual.


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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Ron
On 19 Mar 2005 11:33:20 -0800, "Kay Schluehr" <[EMAIL PROTECTED]>
wrote:

>Raymond Hettinger wrote:
>> I would like to get everyone's thoughts on two new dictionary
>methods:
>>
>> def count(self, value, qty=1):
>> try:
>> self[key] += qty
>> except KeyError:
>> self[key] = qty
>>
>> def appendlist(self, key, *values):
>> try:
>> self[key].extend(values)
>> except KeyError:
>> self[key] = list(values)
>
>-1 form me.
>
>I'm not very glad with both of them ( not a naming issue ) because i
>think that the dict type should offer only methods that apply to each
>dict whatever it contains. count() specializes to dict values that are
>addable and appendlist to those that are extendable. Why not
>subtractable, dividable or right-shiftable? Because of majority
>approval? I'm mot a speed fetishist and destroying the clarity of a
>very fundamental data structure for speedup rather arbitrary
>accumulations seems to be a bad idea. I would move this stuff in a
>subclass.
>
>Regards Kay

-1 for me too.

I agree with this.  The other dictionary functions are all data
nuetral.  Adding special methods to handle data should be in a
durrived class and not a built in.  imho.

# Roll your own specialized dictionaries.

class NumDict( dict):
def count(self, key, qty=1):
try:
self[key] += qty
except KeyError:
self[key] = qty
def appendlist(self, key, *values):
try:
self[key].extend(values)
except KeyError:
self[key] = list(values)

mydict = NumDict()

n = 0
for k in list('abcdefg'):
n += 1
mydict[k] = n

print mydict
# {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6}

mydict.count('c')
mydict['e'] = ['a']
mydict.appendlist('e', 'bcdef')
print mydict
# {'a': 1, 'c': 4, 'b': 2, 'e': ['a', 'bcdef'], 'd': 4, 'g': 7, 'f':
6}


This isn't that hard to do.  I don't think the extra methods should be
added to the base class.

Ron

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-19 Thread Ron
On Sat, 19 Mar 2005 01:24:57 GMT, "Raymond Hettinger"
<[EMAIL PROTECTED]> wrote:

>def count(self, value, qty=1):
>try:
>self[key] += qty
>except KeyError:
>self[key] = qty
>
>def appendlist(self, key, *values):
>try:
>self[key].extend(values)
>except KeyError:
>self[key] = list(values)


Why is it better than this? 

dict[key]+=n
dict[key]+=list  

Ron

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


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Ron
On Sun, 20 Mar 2005 15:14:22 -0800, David Eppstein
<[EMAIL PROTECTED]> wrote:

>In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Aahz) 
>wrote:
>
>> >I am surprised nobody suggested we put those two methods into a
>> >separate module (say dictutils or even UserDict) as functions:
>> >
>> >from dictutils import tally, listappend
>> >
>> >tally(mydict, key)
>> >listappend(mydict, key, value)
>> 
>> That seems like a reasonable compromise.
>
>The more messages I see on this thread, the more I think adding a 
>different new method for each commonly used kind of update is the wrong 
>solution.
>
>We already have methods that work pretty well and, I think, read better 
>than the new methods:
>  mydict[key] += 1
>  mydict[key].append(value)
>The problem is merely that they don't work when key is missing, so we 
>need to resort to setdefault circumlocutions instead.  A better solution 
>seems to be the one I've seen suggested here several times, of changing 
>the dict's behavior so that the setdefault is automatic whenever trying 
>to access a missing key.  If this would be in a separate module or 
>separate subclass of dict, so much the better.


I think that the setdefault behavior needs to be done on an per
application basis because whose to say what default is best?.

With a preset default mode, it then becomes possible to  inadvertently
create default values that will cause problems without knowing it.  So
then we have to remember to change the setdefault value to None or
null to avoid problems.  Ouch!

Also pythons normal behavior for retrieving objects that are not
defined is to give an error.  So having dictionaries that auto
defaults to a mode that doesn't behave that way is inconsistent with
the rest of the language.

Yet,  I'm all for the creation of specialized containers in a standard
module!  :)  Then we can have string dicts, and int dicts, and card
dicts, account dicts, etc, as well as specialized lists.  Call them
'smart containers'.  But they should not be built into the base class.

Ron

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


Re: For loop extended syntax

2005-03-21 Thread Ron
On Sun, 20 Mar 2005 13:16:37 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:

>I'm sure there must have been a past thread about this topic but I don't know 
>how to find it: How
>about extending the "for  in" syntax so that X can include default 
>arguments ? This would be very
>useful for list/generator comprehensions, for example being able to write 
>something like:
>
>[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>
>instead of the less elegant explicit loop version that has to check for the 
>length of each sequence.
>What do you think ?
>
>George
>

How would this examples work?

for x=5,y,z in (123),(4,5),(6,7,8,9)

Would the x default over ride the first value?
Should, the 4 element in the third tuple be dropped without an error?


A  general reusable function might be something like this:

def formatlistofargs(arglist, nargs=1, defvalue=0):
returnvalues = []
for i in arglist:
ii = list(i)
while len(ii)http://mail.python.org/mailman/listinfo/python-list


Re: missing? dictionary methods

2005-03-21 Thread Ron
On 21 Mar 2005 08:21:40 GMT, Antoon Pardon <[EMAIL PROTECTED]>
wrote:

>Well at least I find them missing.
>
>For the moment I frequently come across the following cases.
>
>1) Two files, each with key-value pairs for the same dictionary.
>However it is an error if the second file contains a key that
>was not in the first file.
>
>In treating the second file I miss a 'set' method.
>dct.set(key, value) would be equivallent to dct[key] = value,
>except that it would raise a KeyError if the key wasn't
>already in the dictionary.
>
>
>2) One file with key-value pairs. However it is an error
>if a key is duplicated in the file.
>
>In treating such files I miss a 'make' method.
>dct.make(key, value) would be equivallent to dct[key] = value.
>except that it would raise a KeyError if the key was
>already in the dictionary.
>
>
>What do other people think about this?


There is a has_key(k) method that helps with these.

Adding these wouldn't be that hard and it can apply to all
dictionaries with any data.  

class newdict(dict):
def new_key( self, key, value):
if self.has_key(key):
raise KeyError, 'key already exists'
else:
self[key]=value
def set_key( self, key, value):
if self.has_key(key):
self[key]=value
else:
raise KeyError, 'key does not exist'

d = newdict()
for x in list('abc'):
d[x]=x
print d
d.new_key('z', 'z')
d.set_key('a', 'b')
print d

Which is faster?  (has_key()) or (key in keys())?


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


Re: getting text from WinXP console

2005-03-21 Thread Ron
On Mon, 21 Mar 2005 12:06:03 -0800, Jeff Shannon
<[EMAIL PROTECTED]> wrote:

>Actually, there's probably a second way -- capture the window image as 
>a bitmap, and then run OCR software on it.

There's also OCR aware clipboard software that can cut a selected area
from the screen, convert the graphic image to text and put it on the
clipboard.  They work fairly well.

Most of them aren't free.  But a shareware version with a limited
trial period might work just fine for this one purpose.

Ron

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


Re: For loop extended syntax

2005-03-21 Thread Ron
On Mon, 21 Mar 2005 15:56:26 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:


>It has already been clarified twice in the thread that the default values 
>would be allowed *only in
>the end*, exactly as default function arguments.

Was just asking if there should be other special general cases.  What
programmers want usually depend on the problem at hand. imho  :)

>Of course there are ways to have a function fill in the defaults, but 
>syntactically I would find
>"for (x,y,z=0) in (1,2,3), (4,5), (6,7,8): print x,y,z" more obvious and 
>concise.
>
>By the way, I don't think it's a good idea in general to drop the extra values 
>implicitly, as you do
>in your recipe, for the same reason that calling a function foo(x,y,z) as 
>foo(1,2,3,4) is an error.
>A generalization of the 'for .. in' syntax that would handle extra arguments 
>the same way as
>functions would be:
>
>for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
> print x, y, z, rest
>
>I'd love to see this in python one day; it is pretty obvious what it would do 
>for anyone familiar
>with function argument tuples.
>
>George

I would probably do it this way myself:

def padlist(alist,length,pad):
alist[length:]=[pad]*(length-len(alist))
return alist

for xyz in [1,2,3],[3,4],[5,6,7]:
x,y,z = padlist(xyz, 3, 0)
print x,y,z

# or this if it's faster:

for x,y,z in [padlist(xyz,3,0) for xyz in [1,2,3],[3,4],[5,6,7]]:
print x,y,z


Which isn't too different from what you are suggesting.  I think
someone may have already suggested using list comprehensions.

Ron






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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On 21 Mar 2005 22:37:42 -0800, "Kay Schluehr" <[EMAIL PROTECTED]>
wrote:

>Mappings like that:
>
>   ((x,y),z)   -> x+y-z
>
>   ((x,y=0),z) -> None
>
>should be valid actions too.
>
>What is the audience thinking about that?

I think that there's too much implied,  and that in the long run it,
if we keep addding in special shortcuts, it will lead to very dificult
to read code.  


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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On Tue, 22 Mar 2005 15:05:55 +0100, bruno modulix <[EMAIL PROTECTED]>
wrote:

>bruno modulix wrote:
>> Kay Schluehr wrote:
>> 
>>> Since George Sakkis proposed a new way of doing list comprehensions

>>> letting tuples-like objects (x,y,z=0) acting as functions on other
>>> tuples I wonder why this would not be a good starting point of
>>> rethinking anonymus functions?
>>>
>>> In Georges proposition the action is
>>>
>>>(x,y,z=0) -> (x,y,z)


What about a safe exec as a replacement to lamba but witht he
flexability of exec in a safe and limeted way?  

safe_exec  (  (*inputs) , (expressionstring) ,  ( *outputs)  )

Functon to return a default value:
>> def dfv( arg = value):
  return arg

Safe exec command:
>> x, y = 1, 2
>> safeexec  ( (x, y, dfv(z=0)), "# do nothing", ( x, y, z) ) 
(1, 2, 0)

What could we do, not do with this?



*   I actually started this reply here,  so below is how I got to the
above exression.


I'm trying to put my finger on the basic inconsistency here.  It has
something to do with the z=0 as a way to defining a default .  

Then there's the lamba which I hear may be removed,  but is difficult
to understand for beginners, and isn't readable in that the name
doesn't say what it does.   An alternative name, and possibly a
simpler syntax would be a plus.

Another concept that this touches is the indirect execution of an
expression.  Exec and eval do that, but then you introduce security
issues.

I'm wondering if there's a fundamental concept under these issues such
as a base function class or command that can evaluate the contents of
a tuple in a secure way?  

value = fn(arg, returnvalue) 

>> x = 1
>> fn( x, x*2)
2

Use lists or tuples for multiple arguments and return expressions:

>> x, y, z = 1, 2, 3
>> fn( (x,y,z=0), (x,y,z) ) 
(1, 2, 3)

But it's that "z=0" causes problems here.   In a tuple it's equivalent
to saying 1=2.   or 'a'='b'

So we need a way to say 'if name is undefined, bind it to object'.

# function to give a default value
def dfv( arg = value):
return arg

>> x, y = 1, 2
>> fn( (x, y, dfv(x=0)), ( x, y, z ))
(1, 2, 3)

Now since this could execute in it's own private space, it might also
offer a way to use exec or eval() indirectly in a very limited and
safe way.  

>> estring = \
""" 
result = ''
data = 'abcdefghigklmnop'
for ch in data:
if ch != filterc:
result.join(ch)
"""
>> fn( ( dfv(filterc='d'), evalstring), (exec estring) )

So we need to use a three item tuple:

safe_exec  (  (*inputs) , (expressionstring) ,  ( *outputs)  )

>> def dfv( arg = value):
 return arg
>> x, y = 1, 2
>> safeexec( (x, y, dfv(z=0)), "# do nothing", ( x, y, z) ) 
(1, 2, 0)
 
Long way around to here,  but is this something that has potential?
It would have to be a built in to ensure it's safe to use.   But with
an exec string,  it can possibly do a lot more than lamba, and it
probably wouldn't be as fast.  But the flexibility could be useful.

Ron







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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On Tue, 22 Mar 2005 21:43:48 +0100, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

>Ron a écrit :
>(snip)
>>>>def dfv( arg = value):
>> 
>>  return arg
> >
> >>> def dfv( arg = value):
>... return arg
>...
>Traceback (most recent call last):
>   File "", line 1, in ?
>NameError: name 'value' is not defined
>
>And sorry, but -1 for using exec here.


Yes, I cought that myself.  So...

try: z=z
except: z=0

or 

if 'z' not in locals():
z = 0

Ok, thinking in more incremental terms...

Why should a function not create a local varable of an argument if the
varable doesn't exist and a default value is given?

So when:

Def dfv( v=0):
return v

>>dfv()
0   ;it creates the local copy in this case.

>>a = 25
>>dfv(a)
25  ;It used the given value as expected.

>>dfv(b)
Traceback (most recent call last):
  File "", line 1, in -toplevel-
dfv(b)
NameError: name 'b' is not defined

Why not let it set the local varable v to the default as it does when
no varable is specified?  

A function without a default would still give an error as expected.


:)
Ok no exec,  but what about the general syntax?

value = keyword (inputargs, command, outputargs)

I was thinking if it can be done with standard tuples, it has the
potential to be passed around easily and work from lists and
dictionaries. 

Ron

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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On Tue, 22 Mar 2005 21:56:57 GMT, Ron <[EMAIL PROTECTED]> wrote:

>Why should a function not create a local varable of an argument if the
>varable doesn't exist and a default value is given?

ok... thought it out better. :)

Getting a default into a function isn't the problem. Returning the
value to a varable that doesn't exist is.

So then the question is ... is there a way for a function to create a
varable in it's parents namespace that persists after the function is
done?



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


Regular Expressions

2005-03-22 Thread Ron
This is probably a repeated question, but try as I might I was unable
to find something similar in the archives.

I'm trying to develop a regular expression for recognizing a simplified
C-Style string syntax.  I need it to be able to handle escape sequences
of the form \x where x is any character including ".

Here's what I'm trying:

  \"([^"\\]|(\\.))*\"

When I try to get it to recognize something like:

   "I said, \"Hello!\""

It stops at the first quote after the \.

I've used this very same regular expression in a parser generator I
have for C++ and it works just fine.

Any thoughts on what I'm doing wrong in the Python Reg Ex world?

Thanks for the comments & help.

Ron

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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On Tue, 22 Mar 2005 18:15:25 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:

>"Ron" <[EMAIL PROTECTED]> wrote:
>> On Tue, 22 Mar 2005 21:56:57 GMT, Ron <[EMAIL PROTECTED]> wrote:
>>
>> >Why should a function not create a local varable of an argument if the
>> >varable doesn't exist and a default value is given?
>>

>
>Yeap.. a simple one-liner can do the trick:
>
>def makeVars(**nameVals):
>sys._getframe(1).f_locals.update(nameVals)
>
>try: b
>except NameError: print "Before makeVars: NameError"
>else: print "Before makeVars: Not NameError"
>makeVars(b=2)
>try: b
>except NameError: print "After makeVars: NameError"
>else: print "After makeVars: Not NameError"
>
>George
>

Cool! Thanks George,  so I can do this:

# Set a varable to a default value if it doesn't exist.
# Return the same value back if it does.
# Use: varable = dfvalue( varable=object)
def defvalue(**var):
if var.keys()[0] not in sys._getframe(1).f_locals.keys():
return var.values()[0]
return  sys._getframe(1).f_locals[var.keys()[0]]

f = defvalue(f=0)  
print f   # 0

g = 19
g = defvalue(g=0)
print g   # 19


Would there be any problems with using this function?  

Not sure where I need it.  Was thinking it could be used inside
expressions somehow, and it was an iteresting problem. ;)

Ron


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


Re: Anonymus functions revisited

2005-03-22 Thread Ron
On Tue, 22 Mar 2005 21:45:42 +0100, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

>Ron a écrit :
>> On 21 Mar 2005 22:37:42 -0800, "Kay Schluehr" <[EMAIL PROTECTED]>
>> wrote:
>> 
>> 
>>>Mappings like that:
>>>
>>>  ((x,y),z)   -> x+y-z
>>>
>>>  ((x,y=0),z) -> None
>>>
>>>should be valid actions too.
>>>
>>>What is the audience thinking about that?
>> 
>> 
>> I think that there's too much implied,  and that in the long run it,
>> if we keep addding in special shortcuts, it will lead to very dificult
>> to read code.  
>> 
>Don't like Perl ?-)

I tried it..  Wrote a html reformatter in it a long time ago. Wasn't
tempted to do anything else with it. It was good for that, but I went
a month later and had trouble figuring out how it worked. :)

>The problem here is that Kay's proposition mixes two points: flexible 
>tuple unpacking and a new syntax for anonymous functions.

Yes, two different problems. I don't think anything needs to be done
to tuples myself.  I tend to use lists more anyway.


As far as anonymous functions go...  What if there where a container
type to hold unexecuted python code until it is asked to do it. And to
be able to assign it a name, so it would have an object class and
type. But be defined by like a tuple. No addition syntax to make
things confusing.

>>sum = (* a = b+c *)

The (* and *) could be something more appropriate. As long as it's
easy to identify and can't be confused with anything else.


There would be an order of precedence to it also so you could do:

>>my_button_action = (*a+=c (*if b:c=1 (*if not z: b=False*) *) *)

It would execute from the inside (*_*) outward and use the local name
space it's executed in, so no passing arguments or return values.

Nesting and order of precedence has worked for a long time. to
evaluate it you would need a keyword...  

>>newlamba  my_button_action
 

or this could be valid:
>>newlamba (* a+=c (* if b:c=1 (* if not z:b=False *) *) *)

or left to right order of execution:
>>newlamba (* a = b+c+d, if a>limit:done=True *)

If argument passing is really needed, I suppose there could be an
export/inport method attached to it.

>>newlamba (* sum = a+b *).import(a,b).export(sum)

or
>>newlamba (* sum = a+b *).in_out(a,b -> sum)

>>newlamba my_button_action.in_out(a,b ->sum)


A differnt name would be nice...  code, docode, dothis, process... ?

or if you require the in_out method to start it, you don't need the
keyword.


>> mybutton = (* sum = a+b *)# does not execute, but binds it to a

>> b = mybutton.in_out(a,b -> sum)   # This evaluates first, the sum is bound 
>> to b.

>> b = (* sum = a+b *).in_out(a,b -> sum)   # Is the same as above.


Yes,  there are probably loads of stuff wrong with this.  ;-)

Ron Adam

(Looks like another Ron joined the group.)


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


Re: Anonymus functions revisited

2005-03-23 Thread Ron
On 23 Mar 2005 10:13:16 GMT, Duncan Booth
<[EMAIL PROTECTED]> wrote:

>Do I really need to mention that the whole concept here is broken. This 
>only works if you call it from global scope. If you call it from inside a 
>function it [usually] won't work:


That's only becuase it was asked to go up 1 frame, and not 2.  


def makeVars(**nameVals):
sys._getframe(2).f_locals.update(nameVals) # <- get 2 frames up.


def test():
try: b
except NameError: print "Before makeVars: NameError"
else: print "Before makeVars: Not NameError"
makeVars(b=2)
try: b
except NameError: print "After makeVars: NameError"
else: print "After makeVars: Not NameError"


import sys
test()

>>> 
Before makeVars: NameError
After makeVars: Not NameError
>>> 

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


Re: Anonymus functions revisited

2005-03-23 Thread Ron
On 23 Mar 2005 10:13:16 GMT, Duncan Booth
<[EMAIL PROTECTED]> wrote:

>Do I really need to mention that the whole concept here is broken. This 
>only works if you call it from global scope. If you call it from inside a 
>function it [usually] won't work:

Ok... you can get globals this way if you know how many frames up it
is. Not terrable useful. :/


def frame0():
print 'frame0 (locals): ',sys._getframe(0).f_locals
print '\nframe1 (parent): ',sys._getframe(1).f_locals
print '\n(Global) : ',sys._getframe(2).f_locals

def frame1():
frame0()

import sys
frame1()


>>>
frame0 (locals):  {}

frame1 (parent):  {}

(Global) :  {'__builtins__': , 'sys':
, '__name__': '__main__', 'frame1': , 'frame0': ,
'__doc__': None}
>>> 

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


Re: Anonymus functions revisited

2005-03-23 Thread Ron
On 23 Mar 2005 14:47:30 GMT, Duncan Booth
<[EMAIL PROTECTED]> wrote:

>Kay Schluehr wrote:
>
>> A working makeVars seems not to be different from
>> 
>> def makeVars(**nameVals):
>>globals().update(nameVals)
>
>Not quite. If Ron can come up with a working makeVars it would update the 
>caller's globals whereas what you just posted updates makeVar's globals so 
>there is a difference (when the makeVars and the calling function are in 
>different modules), just not a very useful one.

How about this one?   The only reliable way I found to do it is to
pass locals() to the function.

def defvalue(**args):
args = args.items()
a1 = args[0]
a2 = args[1]
if type(a1[1]) == type({}):
vv, names = a2, a1[1]
else:
vv, names = a1, a2[1]
if names.has_key(vv[0]):
return names[vv[0]]
return vv[1]

f = defvalue(f=1, v=locals())  
print f   # 0

g = 19
g = defvalue(g=2, v=locals())
print g   # 19

z = 6
def f1():
#z = 4
z = defvalue(z=3, v=locals())
print z
f1()

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


Re: Anonymus functions revisited : tuple actions

2005-03-23 Thread Ron
On Wed, 23 Mar 2005 06:21:30 +0100, Kay Schluehr <[EMAIL PROTECTED]>
wrote:

>I think my proposal was more in mind of Rons modified exec than
>Pythons lambda.
>
>When George proposed his unpacking behavoir for list-comps as a pack of
>suggar:
>
>1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>
>I interpreted it in a subsequent posting in lambda fashion:
>
>2. [(lambda x,y,z=0:x*y-z)(*v) for v in (1,2,3), (4,5), (6,7,8)]

Thank you Kay,  All of this is really intersting and I'm learning a
lot about the language through these discussions.


The following is an experiment I did this morning. :-)

I was surprised it worked as well as it did, although I don't think it
should be used in any real production code.  Not in it's present form
anyway.

The idea is to have a container class like a tuple for program code
that can be moved around and used when needed.  Very flexable, maybe
if it could be done without the strings and the exec/eval() functions
in it?

Ron_Adam


# codedo.py
import types

class code(tuple):
"""
Inline Code Storage Class

name = code(('expression','expression',...))
varables = name.do([locals()],['invars'],'outvars')

This is experimental.

Warning:  This is experimental! This class has not
been tested.  It also uses exec, and eval(), which
can be a security risk.
"""
def do(self, *args ):
if type(args[0]) == type({}):
parentnames = args[0]
else:
parentnames = globals()
if len(args)>1:
argslist = args[1].split(',')
else:
argslist = args
for a in argslist:
if parentnames.has_key(a):
exec a+'=parentnames[a]'
for c in self:
exec(c)
return eval(args[-1])  # The last argument are the return
varable(s).


if __name__ == '__main__':
"""
Test it.  This is only what works, not what doesn't.
"""

# Left to Right order.
y=3
print code(('y=y*2','x=y**2')).do('x')

# *** Define and use later! ***
mybutton_action = code(('z=y*2','x=z**2','result=x+2'))
y = 1
print mybutton_action.do('y','result')
y = 10
print mybutton_action.do('y','result')
y = 100
print mybutton_action.do('y','result')

# Return multiple values.
toxyz = code(('x*=2','y*=2','try:z\nexcept:z=0','z*=2'))
x = 2
y = 3
#z = 4
a, b, c = toxyz.do('x,y,z')
print a, b, c

# 1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
print code(('r=[]','for x,y,z in
[(1,2,3),(4,5,0),(7,8,9)]:r.append(x*y-z)')).do('r')

# or...  trailing comma needed here to make a uni-tuple.
print code(('r=list([x*y-z for x,y,z in
(1,2,3),(4,5,0),(7,8,9)])',)).do('r')

# post process list before returning.
print code(('r = [ x for x in range(1,11) ]','r=r*2')).do('r')

# From within a function:
# We need to pass locals() to so it can find the variables.
def fn1():
x = 5
y = 10
lfunction = code(('z = x*2+y',)).do(locals(),'x,y','z')
print lfunction
fn1()


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


Re: Changing the value of a for loop index on the fly

2005-03-23 Thread Ron
On Wed, 23 Mar 2005 23:27:54 +0100, "Gabriel F. Alcober"
<[EMAIL PROTECTED]> wrote:

>Hi! There goes a newbie trouble:
>
>for i in range(0, len(subject)):
>if subject[i] in preps:
>psubject.append(noun_syn_parser(subject[0:i]))
>subject[0:i] = []
>
>Since the last line eliminates some elements of the list, I'm wondering 
>if it's somehow possible to change the value of "i" to 0 in order not to 
>get an index error. Any other ideas?
>Thanks in advance.
>

I going to guess that you probably want something more like below.
The routine you have because of the deletions, the index and the
subjects list get way out of sync, which is why you get the index
error on 'subject[i]'.  

Try this which uses no indexes, it should be closer to what you want.

for subj in subjects:
sub2.append(subj)
if subj in preps:
psubject.append(noun_sys_parser(subj2))
subj2 = []


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


Re: Changing the value of a for loop index on the fly

2005-03-23 Thread Ron
On Thu, 24 Mar 2005 03:42:04 GMT, Ron <[EMAIL PROTECTED]> wrote:

>On Wed, 23 Mar 2005 23:27:54 +0100, "Gabriel F. Alcober"
><[EMAIL PROTECTED]> wrote:
>
>>Hi! There goes a newbie trouble:
>>
>>for i in range(0, len(subject)):
>>if subject[i] in preps:
>>psubject.append(noun_syn_parser(subject[0:i]))
>>subject[0:i] = []
>>
>>Since the last line eliminates some elements of the list, I'm wondering 
>>if it's somehow possible to change the value of "i" to 0 in order not to 
>>get an index error. Any other ideas?
>>Thanks in advance.
>>
>
>I going to guess that you probably want something more like below.
>The routine you have because of the deletions, the index and the
>subjects list get way out of sync, which is why you get the index
>error on 'subject[i]'.  
>
>Try this which uses no indexes, it should be closer to what you want.
>

Correcting a type and an omission:

subj2 = []
for subj in subjects:
subj2.append(subj)
if subj in preps:
psubject.append(noun_sys_parser(subj2))
subj2 = []


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


Re: Anonymus functions revisited

2005-03-24 Thread Ron
On 24 Mar 2005 09:20:52 GMT, Duncan Booth
<[EMAIL PROTECTED]> wrote:

>Ron wrote:
>
>>>> A working makeVars seems not to be different from
>>>> 
>>>> def makeVars(**nameVals):
>>>>globals().update(nameVals)
>>>
>>>Not quite. If Ron can come up with a working makeVars it would update
>>>the caller's globals whereas what you just posted updates makeVar's
>>>globals so there is a difference (when the makeVars and the calling
>>>function are in different modules), just not a very useful one.
>> 
>> How about this one?   The only reliable way I found to do it is to
>> pass locals() to the function.
>
>Yes, but you are still missing the fundamental point. The locals() 
>dictionary is not guaranteed to do anything useful if you update it. The 
>current C implementation will reflect changes in the locals dictionary if 
>you call locals() from global scope or in a few other circumstances, but 
>this is simply an implementation detail.

Nope, Didn't miss the point.  The functions return a value, not create
it from within.

>If you want to update global variables then use globals() or setattr on the 
>module. Only use locals() to access local variables indirectly, never to 
>try and set them.

Good advise. :)

One of pythons weak points is it is sometimes difficult to 'monitor
and confirm' what is happening leading to confusing try/except
constructions.

Having the function is_defined() and if_not_defined() have the
advantage that they can be use in expressions where try/except can't.
And the source code could be more compact and more readable. 

The disadvantage is the functions are quite a bit slower than
try/except, probably due to the function call over head.

If they were built in, they may be as fast as the try/except and there
wouldn't be issues with having to passing locals() or globals() name
dictionaries.


It's interesting that there is a whole is_"type"_() group of functions
in the inspect module, but not a is_defined().  Maybe I just haven't
found it yet.


#

def if_not_defined(v, dv=None, lv=locals()):
if lv.has_key(v):
return lv[v]
return dv

def is_defined(v, lv=locals()):
if lv.has_key(v):
return True
False

# Shorten names and pass locals() with lambas for 
# convenience.   (This needs to be in the function 
# where they are used or it will break.  
# Another use for lamba!   ;)

ifnd = lambda v, dv, lv=locals(): if_not_defined(v,dv,lv)
isa = lambda v, lv=locals(): is_defined(v, lv)

# Totally useless routine. ;)
import random
for n in range(10):

# Delete a random x,y,z coordinate to
# simulate an unreliable data source. 
d = random.choice([1,2,3])
if d==1:
if isa('x'): del x
elif d==2:
if isa('y'): del y
else:
if isa('z'): del z

# Replace the missing variable with a random number.
r = int(random.random()*100)
x, y, z = ifnd('x',r), ifnd('y',r), ifnd('z',r)
print x, y, z 

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


Re: Anonymus functions revisited : tuple actions

2005-03-24 Thread Ron
On Thu, 24 Mar 2005 12:07:44 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:

>"Kay Schluehr" <[EMAIL PROTECTED]> wrote:
>> [snipped]
>>
>> Wouldn't it be fun to use in Python?
>>
>> Only drawback: does not look like executable pseudo-code anymore :(
>>
>>
>> Regards Kay
>
>I don't know if it would be fun, but it certainly doesn't look accessible to 
>mere mortals :-) I'm
>not sure if the mind boggling is more due to the syntax with the '->' and all 
>or the semantics, but
>it goes in the oppposite direction from my initial proposal (having defaults 
>in for loops) with
>respect to readability.
>
>Regards,
>George
>

Hi George, I think I got the default variable functions working now.

if isa('name'): do something

Checks locals, globals, and builtins for the varable name.

variable = ifno('name', object)

Sets a variable name to an object if it does not exist, or sets it to
the 'variable name's object if it does.  (The target doesn't have to
match.) 

They are slower than try/except, but can be used in expressions. Like:

x,y,z = x,y, ifno('z',0) 


#---Here's the code-

import sys

def isa(v):
"""
Check if a varable exists in the current 
(parent to this function), global, or 
builtin name spaces.

use: bool = isa( str )
 returns True or False
"""
plocals = sys._getframe(1).f_locals
if plocals.has_key(v) or globals().has_key(v) or \
   __builtins__.locals().has_key(v):
return True
return False


def ifno(v, obj=None):
"""
Check if a varable does not exists, return a
default value, otherwise return the varable obj.

use: obj = ifno( str [,obj=None] )
 if str exist, returns str's object
 if str does not exist, returns specified object
"""
plocals = sys._getframe(1).f_locals
if plocals.has_key(v):
return plocals[v]
if globals().has_key(v):
return globals()[v]
if __builtins__.locals().has_key(v):
return __builtins__.locals()[v]
return obj


def test():
"""
Test isa() and ifno() functions:
"""

# Totally useless routine. ;)
import random
for n in range(25):

# Delete a random x,y,z coordinate to
# simulate an unrealiabe data source. 
d = random.choice([1,2,3])
if d==1:
if isa('x'): del x
elif d==2:
if isa('y'): del y
else:
if isa('z'): del z

# Replace the missing Varible with a random number.
r = int(random.random()*100)
x, y, z = ifno('x',r), ifno('y',r), ifno('z',r)
print x, y, z


if __name__ == '__main__':
test()

#-

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


serial module NEWBE HELP!

2005-03-29 Thread Ron
Is this built into any of the python versions? Need it! Using 2.3.5 and 
doesn't seem to have it.Newbe needs help!email[EMAIL PROTECTED]  Thanks Ron 


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


Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-19 Thread Ron
Kay Schluehr wrote:
Steven Bethard wrote:

So the object of a "where" is then always an ordered dict?

Yes.

If so, then
I guess I like this proposal best so far.
However, it does seem to have the problem that you can't have any
additional local variables so, for example, list comprehensions are
probably not usable...
Or can you still drop the argument to "where" and just use the names
directly?  E.g.:
x = property(fget=fget, doc=doc) where:
doc = "I'm the 'x' property."
def fget(self):
return self.__x

I can't see why this shouldn't work?
The specifiers behind "where" are present to determine the matching
behaviour. The order of a dict is caused by different specifiers i.e. a
dict- or tuple-like specifier. If a specifier is not present only names
can be matched regardless of a sequence and this is always possible
because we still have a dict with names as keys.
What should not be possible are statements like this:
 x = property(a, b) where:
  doc = "I'm the 'x' property."
  def fget(self):
  return self.__x
because there is no rule to match doc and fget onto a and b. In this
case we would need specifiers:
 x = property(a, b)
 where **a:
doc = "I'm the 'x' property."
 where **b:
def fget(self):
return self.__x
Ciao,
Kay

Just throwing in another slight variation to Kay's example here.
How about using ***name in the same way as *name, and **name are used? 
It extends the current argument options in a consistent manner and 'I 
believe' is easy to explain and visually says something different is 
happening here.

This builds on the already present arg, *arg, **arg,  and so why not a 
***arg to represent the 4th alternative, a suite?

You would also need to use it in the def statement as well, and probably 
would want to anyway if your argument suite is that long.

def property(***a, ***b):
a:
doc = "I'm the default 'x' property."
b:
def foo(arg):
return arg
return arg
x = property(***a, ***b)
a:
 doc = "I'm the 'x' property."
b:
 def fget(self):
 return self.__x
With the ***name syntax, making it's obvious it's different (a good 
thing), and you might be able to drop the 'with' or 'where'.

The (***name) == (name: suite) relationship may be useful in other 
places as well.

I'm not sure on the returns for the def above, just trying to make it 
more complete.  I presuming foo would be the default if 'b' isn't given 
in the function call. I suppose the ***b, and b: suite, in the function 
call can be optional.  Same for the ***a and a: suite.  By having them 
named, either one could be absent and the order could be swapped in the 
call if it makes it more readable.

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


Re: pre-PEP: Simple Thunks

2005-04-20 Thread Ron
Mike Meyer wrote:
Ron_Adam <[EMAIL PROTECTED]> writes:
Here's yet another way to do it, but it has some limitations as well.
import pickle
def pickle_it(filename, obj, commands):
   try:
   f = open(filename, 'r')
   obj = pickle.load(f)
   f.close()
   except IOError:
   pass 	
   for i in commands:
   i[0](i[1])
   f = open(filename, 'w')
   pickle.dump(obj, f)
   f.close()

file = 'filename'
L = []
opps = [ (L.append,'more data'),
(L.append,'even more data') ]
pickle_it(file, L, opps)

Um - it doesn't look like this will work. You pass L in as the "obj"
paremeter, and then it gets changed to the results of a
pickle.load. However, you call L.append in the for loop, so the data
will be appended to L, not obj. You'll lose an list elements that were
in the pickle.
   Hmmm, you are correct. :-/
I was trying to not use eval().  This could be made to work, but it will 
get messy, which is another reason not to do it.

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


Re: pre-PEP: Suite-Based Keywords - syntax proposal

2005-04-20 Thread Ron
Steven Bethard wrote:
Ron wrote:
How about using ***name in the same way as *name, and **name are used? 
It extends the current argument options in a consistent manner and 'I 
believe' is easy to explain and visually says something different is 
happening here.

This builds on the already present arg, *arg, **arg,  and so why not a 
***arg to represent the 4th alternative, a suite?

I dont' see how this is consistent.  *arg and **arg correspond to the 
two different container protocols: sequence/iterable and mapping.  Which 
container protocol do you se ***arg as corresponding to?  Note that 
namespaces are just mappings, so if you want to treat a block like a 
namespace, **arg makes more sense...

STeVe
Another possibility is to use an additional symbol to indicate "not 
here", "over there" or "outside this": %**args.  That has the advantage 
of allowing further expansion in the future if it's needed without 
getting into long strings of '**'s.  Although I don't think that 
would happen.

Too many various thoughts on this are are jumping in my mind right now. 
Which is partly why I've been staying out of this discussion. So here 
are some of them in no particular order.

(Q1.) Is it possible that a new container might be added to python 3000 
(or earlier) to correspond to a names suite?  Or a named lazy suite? 
ie.. one that might be evaluated at the function call versus at the 
define?  Or evaluated upon request?

[1] If so, the ***arg could be consistent in being a container protocol.
(Q2.)  Are the use of '*'s and '**'s allowed anywhere else beside within 
function call def's and call's?  I presume not because it would conflict 
with multiply and exponent operators. So this suggests to me it is 
specific function 'use' case's of function arguments and not general 
container protocol representation that can be used else where.

[1] If there are conflicts outside of function call use, then again 
**args should be preferred as not to create any additional conflicts.

[3] If the use of '*', and '**',  are used specifically to tell function 
calls and defs how to evaluate and use an argument vs a general 
container indicator.  Then ***arg has the advantage of indicating to use 
a named suite or an dict to be defined within the function body.  Named 
suites outside the function could use **arg as they would have already 
been evaluated.

# arg suite defined in the function.
x = function(***arg)
arg:
a = 1
b = 22
#continued ...
#body
# arg suite defined prior to function call.
arg:
a = 1
#continued ...
x = function(**arg)
Q3.  Which is more important, compiler/byte code representation of 
objects and operators or the user/syntax representation of objects and 
operators?  Are we more concerned with the low level representation to 
the compiler or the higher level representation to the user?

[1.] From a 'higher level'/'differing syntax' stand point,  the ***arg 
alternative more clearly communicates that there is a difference in it's 
use to the programmer. (although the low level representation may be the 
same as **arg)

[2.] If it's more important that an accurate representation of the lower 
level inner workings be maintained, then **args should again be preferred.

As far as my reference to consistency, forget I said that.  I think 
practicality might be more important than consistency here.  Consistency 
between small groups of one to three items is not a very strong 
association in any case.

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


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Ron
[EMAIL PROTECTED] wrote:
Many people I know ask why Python does slicing the way it does.
Can anyone /please/ give me a good defense/justification???
I'm referring to why mystring[:4] gives me
elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element).
Many people don't like idea that 5th element is not invited.
(BTW, yes I'm aware of the explanation where slicing
is shown to involve slices _between_ elements.  This
doesn't explain why this is *best* way to do it.)
Chris
Hi Chris,
What I've found is foreword slicing with positive stepping is very 
convenient for a lot of things. :-)

But when you start trying to use reverse steps, it can get tricky.
There are actually 4 different ways to slice and dice. So we have a 
pretty good choice. So the trick is to match the slice method to what 
you need, and also use the correct index's for that method.

Where s = 'abcd'
With s[i,j]
Foreword slices index, forward steps
a,  b,  c,  d
i=  0,  1,  2,  3
j=  1,  2,  3,  4
s[0,4] = 'abcd'
s[1,3] = 'bc'
Foreword slice index (-steps)
a,  b,  c,  d
i=  0,  1,  2,  3
j= -5, -4, -3, -2
s[3,-5] = 'dcba'
s[2,-4] = 'cb'
Reverse slice index (+steps)
a,  b,  c,  d
i= -4, -3, -2, -1
j=  1,  2,  3,  4
s[-4,4] = 'abcd'
s[-3,3] = 'bc'
Reverse slice index (-steps)
a,  b,  c,  d
i= -4, -3, -2, -1
j= -5, -4, -3, -2
s[-1,-5] = 'dcba'
s[-2,-4] = 'cb'
(Maybe this could be made a little more symetrical for Python 3000?)
Cheers,
Ron_Adam
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-21 Thread Ron
Grant Edwards wrote:
On 2005-04-21, Sergei Organov <[EMAIL PROTECTED]> wrote:

Well, I'm writing for embedded realtime systems in C/C++ and
have never encountered a single need to use goto.
I have encountered situations in C programs where the best
thing to use was a goto.  Those situations have always been
handled beutifully by a "raise" in Python.
setjmp/longjump?
I've always found setjmp/longjmp much more confusing and hard
to maintain than a simple goto.  It also requires library
support that goto doesn't.
Agreed. The 'goto error' idiom is in fact the only goto usage
I do agree with provided there is no support for exceptions,
but that's not applicable to Python anyway.

Exactly.  I've been writing C code for 20+ years, and the only
problems where I found goto to be a good solution are the ones
where exceptions are even better solutions in Python.  I've
never found myself wishing for a goto when writing Python code.
I can remember in the early apple2+ days of trying to untangle code 
written by others with liberal use of gotos and no clear program 
structure.  A non trivial task that often meant it was easier to start 
over than to modify someone elses program. Determining the context of a 
statement often required snaking through several dozen gotos with 'line 
number's to find out what a particular section of code actually did. 
Making changes to such code could be difficult and often had unintended 
consequences.

The if, elif, else, functions, and while statements are the replacements 
for goto's.  And they make the code much more readable and 
understandable than something like ...

100 PRINT "HELLO"
105 INPUT ">> ";S$  
110 IF S$ = "GOODBYE" THEN GOTO 140
115 IF S$ = "HOW ARE YOU" THEN GOTO 150
130 GOTO 100
140 PRINT "GOODBYE"
145 GOTO 200
150 PRINT "I'M FINE"
160 GOTO 105
200 REM CONTINUE
LOL, I HAD TO... Oops caps...  look up apple soft basic to remember what 
I couldn't do.  Part of the reason for the spaghetti code was that with 
line numbers it's easier to tack on something to the end than it is to 
change all the line numbers if you didn't allow for room.  I for one, 
don't miss goto's or line numbers!  ;-)

Apple Soft Quick Refrence -
http://www.cosmicwolf.com/AppleII/applesoft_basic.htm
Cheers,
Ron
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python does *SLICING* the way it does??

2005-04-21 Thread Ron
Ron wrote:
[EMAIL PROTECTED] wrote:
Many people I know ask why Python does slicing the way it does.
Can anyone /please/ give me a good defense/justification???
I'm referring to why mystring[:4] gives me
elements 0, 1, 2 and 3 but *NOT* mystring[4] (5th element).
> There are actually 4 different ways to slice 
Where s = 'abcd'
With s[i,j]
Foreword slices index, forward steps
a,  b,  c,  d
i=  0,  1,  2,  3
j=  1,  2,  3,  4
s[0,4] = 'abcd'
s[1,3] = 'bc'
...

Minor correction to this.  It's what I get for not realizing how late it 
was.

Where s = 'abcd'
With s[i:j:step]
Positive slice index, (+1 step)
 a,  b,  c,  d
 i=  0,  1,  2,  3
 j=  1,  2,  3,  4
 s[0:4] = 'abcd'
 s[1:3] = 'bc'
Positive slice index, (-1 step)
 a,  b,  c,  d
 i=  0,  1,  2,  3
 j= -5, -4, -3, -2
 s[3:-5:-1] = 'dcba'
 s[2:-4:-1] = 'cb'
Negative slice index, (+1 step)
 a,  b,  c,  d
 i= -4, -3, -2, -1
 j=  1,  2,  3,  4
 s[-4:4] = 'abcd'
 s[-3:3] = 'bc'
Reverse slice index, (-1 step)
 a,  b,  c,  d
 i= -4, -3, -2, -1
 j= -5, -4, -3, -2
 s[-1:-5:-1] = 'dcba'
 s[-2:-4:-1] = 'cb'

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


Re: Variables

2005-04-23 Thread Ron
Richard Blackwood wrote:
He would argue strongly against your notion of variable. In the 
statement "foo = 5", foo is constant. He would thus argue that foo is a 
constant and not a variable (regardless of whether you change foo's 
value in subsequent statements).
Sounds like his mind is made up and you will probably not be able to 
persuade him otherwise.

But maybe this will help... or not. ;-)
Given a math equation...
x = 2y+3
x and y are clearly (most would agree) variables.  The value of each 
changes depending on the value of the other.

To solve the equation you set one variable to a value to find the other.
x = 2*y+3
y = 5
x = 2*5+3
x = 13
Do this again for other values... etc...
Would he agree that x, and y are variables even after a value is 
determined?  Or would he say that they become constants once you decide 
a value for one?

I think context is the deciding factor if this is a general discussion 
concerning math equations.  The above equation may be an equation of a 
line, or it may be the equation of a specific condition with two unknowns.

They may variables which may either have the value which is constant, a 
known value, an unknown value, or a range of values.

So given only "foo = 5" ...
In Python foo is a Name which is bound to the integer 5.  There are 
other way to describe it, but it all comes down to being symbols 
representing a concept.

(It could have been a randomly generated sequence with no meaning at all 
too!)

Without knowing the context of the discussion, that is all that we can 
say.  However if we were to agree that foo represents a concept that has 
an unchanging value in the context that it is used, then it is a 
constant, because we agreed that it is.  So it is determined by the 
meaning we agree (or decide for ourself) to give to the name "foo".

So what is the meaning of foo?  In general computer discussions foo is 
ever changing and represents an abstract object to be used and reused to 
describe a multitude of possibilities.  I would call that a variable.

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


Re: Injecting code into a function

2005-04-25 Thread Ron
George Sakkis wrote:
Is there a general way of injecting code into a function, typically
before and/or after the existing code ? I know that for most purposes,
an OO solution, such as the template pattern, is a cleaner way to get
the same effect, but it's not always applicable (e.g. if you have no
control over the design and you are given a function to start with). In
particular, I want to get access to the function's locals() just before
it exits, i.e. something like:
def analyzeLocals(func):
func_locals = {}
def probeFunc():
# insert func's code here
sys._getframe(1).f_locals["func_locals"].update(locals())
probeFunc()
# func_locals now contains func's locals
So, how can I add func's code in probeFunc so that the injected code
(the update line here) is always called before the function exits ?
That is, don't just inject it lexically in the end of the function if
there are more than one exit points. I guess a solution will involve a
good deal bytecode hacking, on which i know very little; if there's a
link to a (relatively) simple HOWTO, it would be very useful.
Thanks,
George
I'd like to know this as well.  :)
I think you will have to modify the function func in some way to get 
locals when it exits.

def func():
x = 20
y = 40
func.locals = locals()   # inserted line
func()
print func.locals
On a related note, I'd like to know how to import locals into a function.
Cheers,
Ron





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


Re: How to run Python in Windows w/o popping a DOS box?

2005-04-25 Thread Ron
Bengt Richter wrote:
I don't know what pythonw.exe does with std i/o that hasn't been intercepted,
but I would think it could be handy to have it force a console window, and maybe
have a pythonw.exe command line option to dump either or both stdout and stderr
silently. That way by default you'd see errors etc. unless you opt now to.
(I should check, maybe they've thought of this already. It's really easy to do)
... Nope, I don't see it in python -h (and pythonw -h doesn't show anything ;-)
Using Editpad Pro to capture std out to an edit panel, I get
usage: Pythonw [option] ... [-c cmd | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
-i : inspect interactively after running script, (also PYTHONINSPECT=x)
 and force prompts, even if stdin does not appear to be a terminal
-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
-OO: remove doc-strings in addition to the -O optimizations
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-S : don't imply 'import site' on initialization
-t : issue warnings about inconsistent tab usage (-tt: issue errors)
-u : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
 see man page for details on internal buffering relating to '-u'
-v : verbose (trace import statements) (also PYTHONVERBOSE=x)
-V : print the Python version number and exit
-W arg : warning control (arg is action:message:category:module:lineno)
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
file   : program read from script file
-  : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
   default module search path.  The result is sys.path.
PYTHONHOME   : alternate  directory (or ;).
   The default module search path uses \lib.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fast plotting?

2005-04-26 Thread Ron
Russell E. Owen wrote:
Can anyone recommend a fast cross-platform plotting package for 2-D 
plots?

Our situation:
We are driving an instrument that outputs data at 20Hz. Control is via 
an existing Tkinter application (which is being extended for this new 
instrument) that runs on unix, mac and windows. We wish to update 5-10 
summary plots at approximately 2 Hz and will be offering controls to 
control the instrument and the plots, preferably (but not necessarily) 
mixed in with the plots.

Ideally the package would create plots in the Tkinter application. But 
we realize we're unlikely to get the speed we need that way. So we are 
willing to have the Tkinter app send data to the plotting package  (e.g. 
via a socket) and have it display the plots in a separate process.

We started out with matplotlib, which is a wonderful package (and well 
integrated with most or all GUI toolkits). Unfortunately it is just too 
slow -- at least when driving plots integrated with the Tkinter app. (It  
is getting faster and so are computers, so at some point this will be a 
great way to go. But for now...)

Any suggestions?
-- Russell
Have you looked at BLT?
http://sourceforge.net/projects/blt/
http://heim.ifi.uio.no/~hpl/Pmw.Blt/doc/


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


Re: How do I automate the removal of all non-ascii characters from my code?

2011-09-13 Thread ron
On Sep 12, 4:49 am, Steven D'Aprano  wrote:
> On Mon, 12 Sep 2011 06:43 pm Stefan Behnel wrote:
>
> > I'm not sure what you are trying to say with the above code, but if it's
> > the code that fails for you with the exception you posted, I would guess
> > that the problem is in the "[more stuff here]" part, which likely contains
> > a non-ASCII character. Note that you didn't declare the source file
> > encoding above. Do as Gary told you.
>
> Even with a source code encoding, you will probably have problems with
> source files including \xe2 and other "bad" chars. Unless they happen to
> fall inside a quoted string literal, I would expect to get a SyntaxError.
>
> I have come across this myself. While I haven't really investigated in great
> detail, it appears to happen when copying and pasting code from a document
> (usually HTML) which uses non-breaking spaces instead of \x20 space
> characters. All it takes is just one to screw things up.
>
> --
> Steven

Depending on the load, you can do something like:

"".join([x for x in string if ord(x) < 128])

It's worked great for me in cleaning input on webapps where there's a
lot of copy/paste from varied sources.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python without a tty

2011-09-29 Thread ron
On Sep 29, 5:21 am, Steven D'Aprano  wrote:
> I have a Python script which I would like to test without a tty attached
> to the process. I could run it as a cron job, but is there an easier way?
>
> I am running Linux.
>
> --
> Steven

Have you tried GNU Screen?  It let's you run processes under virtual
terminals, which can then be backgrounded, reconnected to, etc.  I
think it comes with most linux distros.
-- 
http://mail.python.org/mailman/listinfo/python-list


Django ported to Python3!

2011-12-02 Thread Ron
It looks like Vinay Sajip has succeeded in porting Django to Python3
(in a shared code base for Python 3.2 and Python 2.7). This is an
astoundingly good job, done very fast and is big news.
See https://groups.google.com/forum/#!topic/django-developers/XjrX3FIPT-U
and the actual code is at Bitbucket https://bitbucket.org/vinay.sajip/django

With NumPy and SciPy already ported, and with Matplotlib almost there,
maybe PIL and others will follow shortly. This could be a turning
point, or a milestone, or whatever you want to call it. Vinay is  a
hero who should be thanked and congratulated!

In an infinitely less important note, Python411 podcasts are finally
back online after  a three month occultation due to a prolonged and
ugly  billing dispute with Libsyn. Maybe I can interview Vinay and
have him tell us about the porting effort!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Django ported to Python3!

2011-12-03 Thread Ron
Thanks Stefan for clarifying that. I guess Martin deserves most of the
credit.

But I still admire how Sajip jumped in, and I especially admire how
the core team accepted his work without taking a "Not Invented Here"
attitude.

I sure hope the port is accepted into the main trunk soon. There is
just such a huge difference bewtween "90% done" and actually released.
Often code is 90% done but is never finished. And Django has such
enormous psychological significance for Python 3. Many important
projects will never begin serious porting until after Django
officially supports Python 3. And many Python folks will finally start
to take Python 3 seriously only when Django does announce official
support.

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


Re: LinuxJournal Readers' Choice Awards 2011 Best {Programming, Scripting} Language

2011-12-05 Thread Ron
Hello Wesley,

Thanks for the interesting news from Linux Journal.

Now, enquring minds want to know, when will there be a Core Python 3?

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


Sikuli: the coolest Python project I have yet seen...

2010-01-24 Thread Ron
Sikuli is the coolest Python project I have ever seen in my ten year
hobbyist career. An MIT oepn source project, Sikuli uses Python to
automate GUI tasks (in any GUI or GUI baed app that runs the JVM) by
simply drag and dropping GUI elements into Python scripts as function
arguments. Download at http://sikuli.csail.mit.edu/ I also did this
podcast about Sikuli 
http://media.libsyn.com/media/awaretek/Python411_20100124_Sikuli.mp3
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sikuli: the coolest Python project I have yet seen...

2010-01-25 Thread Ron
Thew link at MIT does appear to be down right now, but I presume it
will come back up.

Well, those of you who find it underwhelming are in good company. See
the blog post at Lambda the Ultimate
http://lambda-the-ultimate.org/node/3783

I was impressed though by the application to notify you when your bus
gets close to the pickup point, using Google maps, and by the app to
automatically chart a course to Houston from LA on I-10, again using
Google maps. And perhaps most of all, the app to notify you when your
sleeping baby wakes up, from a picture on a digital camera.

Hey, most of life is non-deterministic. I am in the analog engineering
world and simple, deterministic black and white situations are all
fine and useful, but I can see this very easy to use and simple
technology being useful also ;-))

All of the above apps are but a few lines of code.

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


Re: Sikuli: the coolest Python project I have yet seen...

2010-01-25 Thread Ron
OK, here's an idea. I used to do screen scraping scripts and run them
as CGI scripts with an HTMl user interface. Why not run Sikuli on
Jython on a JVM running on my server, so that I can do my screen
scraping with Sikuli? I can take user inputs by using CGI forms from a
web client, process the requests using a Sikuli script on the server,
and send the results back to the web client.

This sounds like fun to me, and easier to highlight and capture the
appropriate screen information on targeted web sites using Sikuli than
to hand code location information or even using Beautiful Soup.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sikuli: the coolest Python project I have yet seen...

2010-01-26 Thread Ron
On Jan 26, 10:59 am, CM  wrote:
> On Jan 24, 10:18 pm, Ron  wrote:
>
> > Sikuli is the coolest Python project I have ever seen in my ten year
> > hobbyist career. An MIT open source project, Sikuli uses Python to
> > automate GUI tasks (in any GUI or GUI based app that runs the JVM) by
> > simply drag and dropping GUI elements into Python scripts as function
> > Arguments. Download athttp://sikuli.csail.mit.edu/Ialso did this
> > podcast about 
> > Sikulihttp://media.libsyn.com/media/awaretek/Python411_20100124_Sikuli.mp3
>
> How is this preferable to a macro recorder?

Well, the pattern recognition engine allows you to recognize partial
matches to any image, to any desired degree of accuracy. In other
words, you can specify to take action only when an exact match is
found, or else when a 50% match is found. This allows applications
like the baby monitor (to tell you when your  sleeping baby wakes up,
and the imminent bus arrival monitor (to tell you when your bus is
within one mile or any distance you want), and the route mapper from
one city to another on a digital map.

Another thing, Sikuli works with web pages. In other words, you can
automate interaction with web sites as well as with desktop
applications.

You can also automate the entry of text.

And it works (theoretically) on any graphical platform (Mac, Linux,
Window, smartphones, etc).

Probably other advantages. Those are just the ones I see off the top
of my head.

Good question.

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


pyOpenGL Error unable to detect undefined names

2010-12-02 Thread Ron
Hello,

I am trying to use pyOpenGL and I keep getting the following errors:

Traceback (most recent call last):
  File "C:\Temp\Python\OpenGL_Test.py", line 10, in 
from OpenGL.GLU import *
  File "C:\Python26\lib\site-packages\OpenGL\GLU\__init__.py", line 4,
in 
from OpenGL.raw.GLU import *
  File "C:\Python26\lib\site-packages\OpenGL\raw\GLU\__init__.py",
line 6, in 
from OpenGL.raw.GLU.constants import *
  File "C:\Python26\lib\site-packages\OpenGL\raw\GLU\constants.py",
line 7, in 
from OpenGL import platform, arrays
  File "C:\Python26\lib\site-packages\OpenGL\arrays\__init__.py", line
22, in 
formathandler.FormatHandler.loadAll()
  File "C:\Python26\lib\site-packages\OpenGL\arrays\formathandler.py",
line 37, in loadAll
cls.loadPlugin( entrypoint )
  File "C:\Python26\lib\site-packages\OpenGL\arrays\formathandler.py",
line 44, in loadPlugin
plugin_class = entrypoint.load()
  File "C:\Python26\lib\site-packages\OpenGL\plugins.py", line 14, in
load
return importByName( self.import_path )
  File "C:\Python26\lib\site-packages\OpenGL\plugins.py", line 28, in
importByName
module = __import__( ".".join(moduleName), {}, {}, moduleName)
  File "C:\Python26\lib\site-packages\OpenGL\arrays\numpymodule.py",
line 25, in 
from OpenGL_accelerate.numpy_formathandler import NumpyHandler
  File "numpy.pxd", line 30, in OpenGL_accelerate.numpy_formathandler
(src\numpy_formathandler.c:3543)
ValueError: numpy.dtype does not appear to be the correct type object

The code is very simple all I have is two import statements:
from OpenGL.GLU import *
from OpenGL.GL import *

The code analysis says that it is "unable to detect undefined names".
What does that mean and how do I fix it? Is it an installation error?

Thanks for the help,
Ron
-- 
http://mail.python.org/mailman/listinfo/python-list


Python for MultiTouch!

2010-08-17 Thread Ron
Along with the news of Unbuntu supporting multitouch, I saw this and
just had to share, I think its really nice: PyMT

http://the-space-station.com/2010/8/16/python-multitouch:-pymt-0-5-released
-- 
http://mail.python.org/mailman/listinfo/python-list


scrapelib for web scraping

2010-08-17 Thread Ron
Shameless plug for a web scraping tool my son is involved in creating,
called scrapelib. He is on leave from university and is a consultant
for the Sunlight Foundation creating something called the Fifty States
Project to monitor lobbyist money to state governments in the USA.

http://github.com/mikejs/scrapelib
-- 
http://mail.python.org/mailman/listinfo/python-list


Podcast about Python's versions and implementations

2010-08-17 Thread Ron
New podcast up is a look at the various versions and implementations
of Python, including Python 3, Python 2, PyPy, IronPython, Jython,
Stackless, Psycho, Shedskin, Cython, Unladen Swallow, Berp, etc.

http://www.awaretek.com/python/

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


Re: logger doesn't roll over

2012-11-21 Thread Ron Eggler

Hooops sh*t! I outsmarted myself I guess... :o

However, Thanks for the kick GC!

Ron Eggler
1804 - 1122 Gilford St.
Vancouver, BC
V6G 2P5
(778) 230-9442

On 12-11-21 11:41 AM, Gary Chambers wrote:

Ron,


LOGFILE, maxBytes=(1048576*10), backupCount=5
What am I doing wrong here, I don't get it.


10 * 1048576 = 10MB

--
GC


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


serial module

2012-05-18 Thread Ron Eggler
Hoi,

I'm trying to connect to a serial port and always get the error
"serial.serialutil.SerialException: Port is already open." whcih is untrue. 
I have no serial port open yet, my code looks like this:
#!/usr/bin/python
import time
import serial

# configure the serial connections (the parameters differs on the device
# you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=19200,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)

ser.open()

Why do I get this error?

Thank you,
Ron

--- Posted via news://freenews.netfront.net/ - Complaints to [email protected] 
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: serial module

2012-05-22 Thread Ron Eggler
Grant Edwards wrote:

> On 2012-05-19, Paul Simon  wrote:
>> "Ron Eggler"  wrote:
> 
>>> [...] my code looks like this:
> 
>>> #!/usr/bin/python
> [...]
>>>port='/dev/ttyUSB0',
> 
>> Sounds like you may be using this on a Windows machine.
> 
> I don't think so.  :)

Nope it's Linmux but nevermind. I'm writing a C app instead. That's more in 
my line of fire too... :)

Thanks,
Ron


--- Posted via news://freenews.netfront.net/ - Complaints to [email protected] 
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Modify Python code as newbie

2020-01-17 Thread ron . eggler
Hi,

I'm semi new to Python but need to modify a program that calls the 
mqtt_client.publish()  function from aws iot.
Now, if the publish function fails, it raises an exception.  I need to change 
the code so that when an exception is raised, instead of giving up, it should 
retry.
Here's some semi pseudo code of what I came up with and what I'm particularly 
interested in is, if the exception in pub_msg() is raised, will my thread t 
keep running? 
What else could/should be improved about the below snippet? I'm looking forward 
to get some inputs.

Thanks!


import retrying
import Queue as queue
import threading as th
NUM_THREADS=1
numth=[]
def worker():
while not_terminated():
item = q.get()
if item is None:
continue
do_stuff(item)

def enQ(self, msg, topic):
if len(numthhttps://mail.python.org/mailman/listinfo/python-list


modify python code as newbie

2020-01-17 Thread ron . eggler
Hi,

I'm semi new to Python but need to modify a program that calls the 
mqtt_client.publish()  function from aws iot.
Now, when the publish function fails, it raises an exception.  I need to change 
the code so that when an exception is raised, instead of giving up, it should 
retry (indefinitely).
Here's some semi pseudo code of what I came up with: 
What I'm particularly interested in is, if when the exception in pub_msg() is 
raised, will my thread t keep running? 
What else could/should be improved in the below snippet? I'm looking forward to 
get some inputs.

Thanks!


import retrying
import Queue as queue
import threading as th
NUM_THREADS=1
nth=[]
def worker():
while not_terminated():
item = q.get()
if item is None:
continue
do_stuff(item)

def enQ(self, msg, topic):
if len(nthhttps://mail.python.org/mailman/listinfo/python-list


Re: Question About Logic In Python

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

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

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

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


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

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



> Cheers,
> Terry


Cheers,
Ron













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


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

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

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

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

 This domain is parked,  underconstruction.

Not sure if it means anything?


Doing a whois on liage.net points to:


Registrant:
Ticluse Teknologi

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

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

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


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

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


Maybe an email to them would clear it up?

Cheers,
Ron



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


Re: What is "self"?

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


I'll give it a try..

When you have a class definition:

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

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

 leader = Person()

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

 leader.set_name("John")

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

 leader.set_name(leader, "John")

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

 self.name = name

is the same as ...

 leader.name = name

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


I hope this helped.

Cheers,
Ron









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


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

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

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

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

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


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


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

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

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


Cheers,
Ron


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


Re: What is "self"?

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

I thought that I might have missed something there.

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

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

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

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

Cheers,
Ron





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


Re: Finding where to store application data portably

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

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

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

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

A few thoughts ...

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

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

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

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

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

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

Cheers,
Ron Adam


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


Re: Dynamically adding and removing methods

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


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

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


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


Cheers,
Ron



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


Re: What is "self"?

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

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

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

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

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

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


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

Thanks,
Ron











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


Re: What is "self"?

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

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

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

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

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

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

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

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

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


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


Re: Dynamically adding and removing methods

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

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


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

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

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

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

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

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


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

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


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

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

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

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


Cheers,
Ron




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


Re: PEP 350: Codetags

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

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

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


Possible multi-line comment with optional label.

 ##[label]: comment text :##


Examples:

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

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

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

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


 ## TODO:
 A comment with a label.

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


 ## FIX ME:
 Nested comments with labels.

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


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


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

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


Re: Dynamically adding and removing methods

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

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

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


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

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

Cheers,
Ron






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


Re: Dynamically adding and removing methods

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

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

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

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

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


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

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

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

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

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

 >>> boundmeth
>
 >>> C.m

 >>> C.__dict__['m']


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

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

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

Cheers,
Ron

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


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

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

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

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

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

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

So ...

   A if B else C + X * Y

Would evaluate as... ?

   A if B else (C + X * Y)


and...

value = X * Y + A if B else C

would be ?

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

or ?

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



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

Cheers,
Ron


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


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

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

> Ron Adam

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


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

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

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

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

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


Cheers,
Ron








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


Re: Class Help

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

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

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

xyz = Xyz()
xyz.y()


Also,

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

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

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



Cheers,
Ron











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


Re: Class Help

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

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

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

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


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

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

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

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

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

Also checking types is not the same as checking values.

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

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


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

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

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

* Errors that interrupt program execution.

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

* Human 'user' input errors.

Value testing is what is needed for these.

* Programming errors...

Nothing will replace testing here.


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

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

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

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

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

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

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

 ... many pages of code ...

 print Const['pi']  # dependable result?


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

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

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

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

Cheers,
Ron
















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


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

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

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

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

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

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

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

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

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

so...

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


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

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

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

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

and..

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

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

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

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


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

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

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

Works for me.

__lock_names__ = True

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


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

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

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

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

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

D = dis.dis(f)

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

Something like...

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



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


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

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

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


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

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

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

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

Ah... thanks.

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

def nulldecorator(f):
return f

if not __debug__:
   debugdecorator = nulldecorator


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

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


>  




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


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

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

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

import _cx_Oracle as cx_Oracle

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

Cheers,
Ron





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


dis.dis question

2005-10-08 Thread Ron Adam

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

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


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

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

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

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

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

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

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

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

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

Cheers,
Ron

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


Re: Weighted "random" selection from list of lists

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


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

Just add up the total of all lists.

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

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

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


Re: dis.dis question

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

  [cliped]

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

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

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

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

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

Cheers,
Ron




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


Re: Function decorator that caches function results

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

If I understand this correctly...

 if args in cache:

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

 result = fn(*args, **kwargs)

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

Is this correct?

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


Re: Function decorator that caches function results

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

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

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

Cheers,
Ron

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


Re: non descriptive error

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

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

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

Cheers,
Ron



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


Re: Python's Performance

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

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

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

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

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

;-)

Cheers,
Ron


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


Re: non descriptive error

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

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

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



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

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

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


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


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

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


Hope this helps,
Ron

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


Setdefault bypasses __setitem__

2005-10-12 Thread Ron Garret
Is this a bug or a feature?

class mydict(dict):
   def __setitem__(self, key, val):
 print 'foo'
 dict.__setitem__(self, key, val)

>>> d=mydict()
>>> d[1]=2
foo
>>> d.setdefault(2,3)
3

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


NYLUG meeting: The Python Object Model with Alex Martelli & Google (open bar and food!)

2005-10-14 Thread Ron Guerin
The New York Linux User's Group invites you to a special presentation
by Alex Martelli of Google, on the Python Object Model.  This 
presentation will be held at P.J. Clarke's Sidecar, rather than our
usual location, and Google is picking up the tab for an hour and a half
of open bar and food.  Additionally, if you're looking for a job as a
Python developer, bring your resume.

Please RSVP at http://rsvp.nylug.org to attend, as seating is limited.

- Ron

(announcement follows)

   The New York Linux User's Group Presents
Alex Martelli
   - on -
   The Python Object Model

Held at P.J. Clarke's Sidecar
 915 Third Avenue @ 55th Street - NY

Python is a multi-paradigm programming language, but, out of the
paradigms it supports, there is no doubt that OOP (Object Oriented
Programming) is the paradigm that forms Python's core. If you have done
any substantial programming with Python, you have, most likely, used
some of its OOP features. But -- have you ever stopped to really think
about those OOP features, the mechanisms that Python uses (and exposes!)
to implement them, and how best to make use of the possibilities this
state of things offers?

This subject is generally known as the "Object Model" of a language.
This talk stops a bit short of examining every level of Python's Object
Model -- in particular, it does not get into metatypes (metaclasses) and
similar levels of "Black Magic". Rather, the talk sticks to the most
practically interesting aspects of Python's Object Model as seen from
the point of view of a programmer using Python -- understanding exactly
what's going on in all kind of everyday OOP-usage situation, what
alternatives and trade-offs these mechanisms imply (for example, when
should you use closures, and when should you use functors instead? when
to inherit, and when to delegate instead?), and how Design Patterns play
into the mix (Python subsumes and build-ins some classic DPs, and makes a
few others irrelevant due to its highly dynamic typing, but other classic
DPs yet remain extremely relevant and important for optimal day to day
use of OOP in Python).

About Alex Martelli
---
Alex Martelli is Uber Technical Lead at Google, in Production Software.
He wrote Python in a Nutshell and co-edited the Python Cookbook, and is
a member of the Python Software Foundation. Before joining Google,
Martelli spent 8 years with IBM, 12 with think3 inc, and 3 as a Python
freelance consultant, mostly for AB Strakt (Sweden).

P. J. Clarke's Sidecar
--
915 Third Avenue @ 55th Street - NY

Sidecar is PJ Clarkes handsome semiprivate upstairs dining room.  You
enter Sidecar through a distinct yet discreet door on East 55th Street.

Subway:
Take the E, V or 6 Subways to 51st Street, cut over to Third Avenue and
walk north 4 blocks.

Take the 4, 5 or 6 Trains to 59th Street, cut over to Third and walk 4
blocks south.

Bus:
Take the 101, 102 or 103 Buses to 55th. If you're coming downtown on
Lexington, cut across to Third. If you're coming up on Third, it's right
across the street.

http://pjclarkes.com/htm/sidecar.htm

About NYLUG
---
NYLUG is the New York Linux Users Group, which has met every month
without fail for the last six years.  Meetings are free and open to the
public, but require advance RSVP due to fire code and security
requirements at our usual meeting space at the IBM Building.

Our announcements mailing list at
http://nylug.org/mailman/listinfo/nylug-announce provides a low-volume
but steady stream of Linux, Free and Open Source, and related community
and other user group announcements for the tri-state area.

Our technical discussion list is a moderate-volume list featuring a
diverse group that from home users to enterprise security experts.
http://nylug.org/mailman/listinfo/nylug-talk

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


Re: NYLUG meeting: The Python Object Model with Alex Martelli & Google(open bar and food!)

2005-10-14 Thread Ron Guerin
George Sakkis wrote:
> 
> 
> What date is it ? It isn't mentioned at the web site either.
> 

Sorry about that, actually it is on the web site, right at the top in
the blue band.

October 26, 2005  6:00pm - 10:00pm

Hope to see you there.

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


  1   2   3   4   5   6   7   8   >