Re: Generating sin/square waves sound

2011-12-30 Thread 88888 Dihedral
Please check PYGAME and Simple Directmedia library. 

Python is used as the director like role and functions in SDL 
do most of the jobs in Pygame. 

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


Re: pickling instances of metaclass generated classes

2011-12-30 Thread lars van gemerden
On Dec 29, 8:55 pm, Ian Kelly  wrote:
> On Thu, Dec 29, 2011 at 2:55 AM, lars van gemerden  
> wrote:
>
> > Hello,
>
> > Can someone help me with the following:
>
> > I am using metaclasses to make classes and these classes to make
> > instances. Now I want to use multiprocessing, which needs to pickle
> > these instances.
>
> > Pickle cannot find the class definitions of the instances. I am trying
> > to add a line to the __new__ of the metaclass to add the new class
> > under the right name in the right module/place, so pickle can find
> > it.
>
> > Is this the right approach? Can anyone explain to me where/how to add
> > these classes for pickle to find and maybe why?
>
> It sounds like you're trying to do something like this?
>
> >>> class MetaClass(type):
>
> ...     pass
> ...>>> instance = MetaClass('', (object,), {})()
> >>> instance
>
> <__main__. object at 0x00CC00F0 import pickle
> >>> pickle.dumps(instance)
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "c:\python27\lib\pickle.py", line 1374, in dumps
>     Pickler(file, protocol).dump(obj)
>   File "c:\python27\lib\pickle.py", line 224, in dump
>     self.save(obj)
>   File "c:\python27\lib\pickle.py", line 331, in save
>     self.save_reduce(obj=obj, *rv)
>   File "c:\python27\lib\pickle.py", line 401, in save_reduce
>     save(args)
>   File "c:\python27\lib\pickle.py", line 286, in save
>     f(self, obj) # Call unbound method with explicit self
>   File "c:\python27\lib\pickle.py", line 562, in save_tuple
>     save(element)
>   File "c:\python27\lib\pickle.py", line 295, in save
>     self.save_global(obj)
>   File "c:\python27\lib\pickle.py", line 748, in save_global
>     (obj, module, name))
> pickle.PicklingError: Can't pickle '>:
> it's not found as __main__.
>
> Yeah, pickle's not going to work with anonymous classes.  As you
> suggest, you could dynamically add the classes to the module namespace
> so that pickle.dumps will find them, but bear in mind that they will
> also have to exist when calling pickle.loads, so you will need to be
> able to reconstruct the same anonymous classes before unpickling later
> on.
>
> Cheers,
> Ian

Thank you Ian for the minimal example. This is almost the case i was
trying to discribe, however the classes will be named at runtime and
the class definitions will be persisted in a database.

Can you help me with how to add the classes to the correct namespace?
The application spans multiple modules (or compared to the example,
the metaclass definition will be in another module then one where the
class and instance will be generated).

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


Re: Generating sin/square waves sound

2011-12-30 Thread Dave Angel

On 12/30/2011 02:17 AM, Paulo da Silva wrote:

Hi,
Sorry if this is a FAQ, but I have googled and didn't find any
satisfatory answer.

Is there a simple way, preferably multiplataform (or linux), of
generating sinusoidal/square waves sound in python?

Thanks for any answers/suggestions.
If you're willing to be Linux-only, then I believe you can do it without 
any extra libraries.


You build up a string (8 bit char, on Python 2.x)  of samples, and write 
it to  "/dev/audio".  When i experimented, I was only interested in a 
few seconds, so a single write was all I needed.


Note that the samples are 8 bits, and they are offset by 128.  So a zero 
signal would be a string of 128 values.  A very quiet square wave might 
be a bunch of 126, followed by a bunch of 130.  and so on.  And the 
loudest might be a bunch of 2's followed by a bunch of 253's.


You'll have to experiment with data rate;   The data is sent out at a 
constant rate from your string, but I don't know what that rate is.



--

DaveA

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


Re: importing MySQLdb

2011-12-30 Thread Ned Deily
In article <4efb9d6d.3080...@gmail.com>,
 Dilara Ally  wrote:
> I'm trying to import the MySQLdb for python.  I downloaded the proper 
> setuptools egg (ver2.7) for a Mac with OSX10.6
> 
> I then downloaded the MySQL-python-1.2.3 and ran the following commands
> 
> python setup.py build
> sudo python setup.py install
> 
> Then to test that the module was properly loaded I used the interactive 
> python prompt ad ran the following command:
> 
> import MySQLdb
> 
> The error message read:
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "MySQLdb/__init__.py", line 19, in 
>  import _mysql
>File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 7, in 
>File "build/bdist.macosx-10.6-intel/egg/_mysql.py", line 6, in 
> __bootstrap__
> ImportError: 
> dlopen(/Users/dally/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.eg
> g-tmp/_mysql.so, 
> 2): Library not loaded: libmysqlclient.18.dylib
>Referenced from: 
> /Users/dally/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.6-intel.egg-tmp/_
> mysql.so
>Reason: image not found
> 
> Does anyone have any ideas on how to fix this problem?  Any help will be 
> greatly appreciated!

If you installed the MySQL client libraries from a MySQL binary 
installer, chances are that the library name in the client library does 
not contain the full path.  The MySQL project has a pretty dismal record 
for releasing faulty OS X binaries.  There are a few workarounds, the 
best being either to use install_name_tool to fix the path or to set the 
DYLD_LIBRARY_PATH environment variable.  See, for example, this blog 
post:

http://www.blog.bridgeutopiaweb.com/post/how-to-fix-mysql-load-issues-on-
mac-os-x/

-- 
 Ned Deily,
 n...@acm.org

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


Re: pickling instances of metaclass generated classes

2011-12-30 Thread lars van gemerden
On Dec 29, 8:55 pm, Ian Kelly  wrote:
> On Thu, Dec 29, 2011 at 2:55 AM, lars van gemerden  
> wrote:
>
> > Hello,
>
> > Can someone help me with the following:
>
> > I am using metaclasses to make classes and these classes to make
> > instances. Now I want to use multiprocessing, which needs to pickle
> > these instances.
>
> > Pickle cannot find the class definitions of the instances. I am trying
> > to add a line to the __new__ of the metaclass to add the new class
> > under the right name in the right module/place, so pickle can find
> > it.
>
> > Is this the right approach? Can anyone explain to me where/how to add
> > these classes for pickle to find and maybe why?
>
> It sounds like you're trying to do something like this?
>
> >>> class MetaClass(type):
>
> ...     pass
> ...>>> instance = MetaClass('', (object,), {})()
> >>> instance
>
> <__main__. object at 0x00CC00F0 import pickle
> >>> pickle.dumps(instance)
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "c:\python27\lib\pickle.py", line 1374, in dumps
>     Pickler(file, protocol).dump(obj)
>   File "c:\python27\lib\pickle.py", line 224, in dump
>     self.save(obj)
>   File "c:\python27\lib\pickle.py", line 331, in save
>     self.save_reduce(obj=obj, *rv)
>   File "c:\python27\lib\pickle.py", line 401, in save_reduce
>     save(args)
>   File "c:\python27\lib\pickle.py", line 286, in save
>     f(self, obj) # Call unbound method with explicit self
>   File "c:\python27\lib\pickle.py", line 562, in save_tuple
>     save(element)
>   File "c:\python27\lib\pickle.py", line 295, in save
>     self.save_global(obj)
>   File "c:\python27\lib\pickle.py", line 748, in save_global
>     (obj, module, name))
> pickle.PicklingError: Can't pickle '>:
> it's not found as __main__.
>
> Yeah, pickle's not going to work with anonymous classes.  As you
> suggest, you could dynamically add the classes to the module namespace
> so that pickle.dumps will find them, but bear in mind that they will
> also have to exist when calling pickle.loads, so you will need to be
> able to reconstruct the same anonymous classes before unpickling later
> on.
>
> Cheers,
> Ian

Ian also wrote:

'''
Actually, I was wrong, you probably don't need to do that.  I suggest
going with Robert Kern's suggestion to either register the class with
the copy_reg module, or (perhaps better since it won't leak
registrations) implement a __reduce__ method on the class.  For
example, this seems to work:

>>> def reconstructor(*metaclass_args):
... cls = MetaClass.build_class(*metaclass_args)
... self = cls.__new__(cls)
... return self
...
>>> class MetaClass(type):
... @classmethod
... def build_class(mcs, arg1, arg2, arg3):
... # Do something useful with the args...
... class _AnonymousClass(object):
... __metaclass__ = mcs
... def __reduce__(self):
... return (reconstructor, ('foo', 'bar', 'baz'),
self.__dict__)
... return _AnonymousClass
...
>>> instance = MetaClass.build_class('foo', 'bar', 'baz')()
>>> instance
<__main__._AnonymousClass object at 0x011DB410>
>>> instance.banana = 42
>>> import pickle
>>> s = pickle.dumps(instance)
>>> s
"c__main__\nreconstructor
\np0\n(S'foo'\np1\nS'bar'\np2\nS'baz'\np3\ntp4\nRp5\n(dp6\nS'banana'\np7\nI42\nsb."
>>> inst2 = pickle.loads(s)
>>> inst2
<__main__._AnonymousClass object at 0x011DBE90>
>>> inst2.banana
42
>>> inst2.__class__ is instance.__class__
False

Cheers,
Ian

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


Re: Generating sin/square waves sound

2011-12-30 Thread mblume
Am Fri, 30 Dec 2011 07:17:13 + schrieb Paulo da Silva:

> Hi,
> Sorry if this is a FAQ, but I have googled and didn't find any
> satisfatory answer.
> 
> Is there a simple way, preferably multiplataform (or linux), of
> generating sinusoidal/square waves sound in python?
> 
> Thanks for any answers/suggestions.

Have a look at the wave module, available under Windows and Linux,
which operates on .WAV files. The following snippet might get you going:

#!/usr/bin/python
import math, wave, struct

def signal(t, freq):
return math.sin(2.0*math.pi*freq*t)


wout  = wave.open("sample.wav", "wb")
nchan = 1
sampwidth = 2
framerate = 8000
nframes   = 7 * framerate
comptype  = "NONE"
compname  = "no compression"


wout.setparams((nchan, sampwidth, framerate, nframes, comptype, compname))

ts = 1.0 / framerate
t  = 0.0
n  = 0
data = []
vals = []
while n < nframes:
vals.append(signal(t, 517.0))
n = n + 1
t = t + ts

mx   = max((abs(x) for x in vals))
vals = [ x/mx for x in vals ]   
data = ""
for v in vals:
data = data + struct.pack("http://mail.python.org/mailman/listinfo/python-list


Re: pickling instances of metaclass generated classes

2011-12-30 Thread Peter Otten
lars van gemerden wrote:

> On Dec 29, 8:55 pm, Ian Kelly  wrote:
>> On Thu, Dec 29, 2011 at 2:55 AM, lars van gemerden 
>> wrote:
>>
>> > Hello,
>>
>> > Can someone help me with the following:
>>
>> > I am using metaclasses to make classes and these classes to make
>> > instances. Now I want to use multiprocessing, which needs to pickle
>> > these instances.
>>
>> > Pickle cannot find the class definitions of the instances. I am trying
>> > to add a line to the __new__ of the metaclass to add the new class
>> > under the right name in the right module/place, so pickle can find
>> > it.
>>
>> > Is this the right approach? Can anyone explain to me where/how to add
>> > these classes for pickle to find and maybe why?
>>
>> It sounds like you're trying to do something like this?
>>
>> >>> class MetaClass(type):
>>
>> ... pass
>> ...>>> instance = MetaClass('', (object,), {})()
>> >>> instance
>>
>> <__main__. object at 0x00CC00F0 import pickle
>> >>> pickle.dumps(instance)
>>
>> Traceback (most recent call last):
>> File "", line 1, in 
>> File "c:\python27\lib\pickle.py", line 1374, in dumps
>> Pickler(file, protocol).dump(obj)
>> File "c:\python27\lib\pickle.py", line 224, in dump
>> self.save(obj)
>> File "c:\python27\lib\pickle.py", line 331, in save
>> self.save_reduce(obj=obj, *rv)
>> File "c:\python27\lib\pickle.py", line 401, in save_reduce
>> save(args)
>> File "c:\python27\lib\pickle.py", line 286, in save
>> f(self, obj) # Call unbound method with explicit self
>> File "c:\python27\lib\pickle.py", line 562, in save_tuple
>> save(element)
>> File "c:\python27\lib\pickle.py", line 295, in save
>> self.save_global(obj)
>> File "c:\python27\lib\pickle.py", line 748, in save_global
>> (obj, module, name))
>> pickle.PicklingError: Can't pickle '>:
>> it's not found as __main__.
>>
>> Yeah, pickle's not going to work with anonymous classes.  As you
>> suggest, you could dynamically add the classes to the module namespace
>> so that pickle.dumps will find them, but bear in mind that they will
>> also have to exist when calling pickle.loads, so you will need to be
>> able to reconstruct the same anonymous classes before unpickling later
>> on.
>>
>> Cheers,
>> Ian
> 
> Thank you Ian for the minimal example. This is almost the case i was
> trying to discribe, however the classes will be named at runtime and
> the class definitions will be persisted in a database.
> 
> Can you help me with how to add the classes to the correct namespace?
> The application spans multiple modules (or compared to the example,
> the metaclass definition will be in another module then one where the
> class and instance will be generated).

If the metaclass is global in whatever module you don't need to bother about 
that. The problem is that you cannot access the classes (metaclass 
instances) under a dotted name. One workaround is a pseudo-module that does 
whatever is needed to recreate the class:

import pickle
import sys

class MetaClass(type):
pass

class M(object):
def __init__(self, module):
self.__module = module
def __getattr__(self, name):
print "creating class", name
class_ = MetaClass(name, (), {"__module__": self.__module})
setattr(self, name, class_)
return class_

sys.modules["m"] = M("m")
import m
c = m.x
s = pickle.dumps(c)
print repr(s)
d = pickle.loads(s)

assert c is d

sys.modules["m"] = M("m")
e = pickle.loads(s)

assert c is not e

The official way is probably what Robert mentioned, via the copy_reg module, 
but I didn't get it to work.

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


Is python.org down?

2011-12-30 Thread Mario Menezes
Hi,

 I´m trying to access pypi.python.org as well as www.python.org and none of 
them is up?

  Anybody else having problems with python.org today? Is there a scheduled 
downtime?

  Thanks

Mario Menezes
Brazil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is python.org down?

2011-12-30 Thread tistje
On 30 dec, 14:21, Mario Menezes  wrote:
> Hi,
>
>  I´m trying to access pypi.python.org as well as www.python.org and none of 
> them is up?
>
>   Anybody else having problems with python.org today? Is there a scheduled 
> downtime?
>
>   Thanks
>
> Mario Menezes
> Brazil

Seems like it is down ... I downloaded the 2.7.2 Windows installer a
couple of hours ago, but now even the download page isn't accessible.

Tist Verdonck
Belgium
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is python.org down?

2011-12-30 Thread Jérôme
Fri, 30 Dec 2011 05:39:37 -0800 (PST)
tistje a écrit:

> On 30 dec, 14:21, Mario Menezes  wrote:
> > Hi,
> >
> >  I´m trying to access pypi.python.org as well as www.python.org and none
> > of them is up?
> >
> >   Anybody else having problems with python.org today? Is there a
> > scheduled downtime?

> Seems like it is down ... I downloaded the 2.7.2 Windows installer a
> couple of hours ago, but now even the download page isn't accessible.

http://www.python.org seems to be working, now.

-- 
Jérôme
France
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is python.org down?

2011-12-30 Thread Chris Angelico
On Sat, Dec 31, 2011 at 12:21 AM, Mario Menezes  wrote:
> Hi,
>
>  I´m trying to access pypi.python.org as well as www.python.org and none of 
> them is up?
>
>  Anybody else having problems with python.org today? Is there a scheduled 
> downtime?
>
>  Thanks

Appears to be up now, for me at least. No reported troubles with DNS.
If you're still unable to get to it, try doing a DNS lookup, or try
pinging 82.94.164.162 (which is www.python.org according to my
lookup). Which one's out?

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


Re: Is python.org down?

2011-12-30 Thread Mario Menezes
Yeah! www.python.org is up now.

pypi.python.org still with problems (502 Bad Gateway).

will wait couple time. somebody seems to be working on this.

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


Re: Is python.org down?

2011-12-30 Thread python
A good tool for determining whether a site is down or just unavailable
to you:

http://downorisitjustme.com

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


Re: Is python.org down?

2011-12-30 Thread tistje
On 30 dec, 14:48, Chris Angelico  wrote:
> On Sat, Dec 31, 2011 at 12:21 AM, Mario Menezes  wrote:
> > Hi,
>
> >  I´m trying to access pypi.python.org as well aswww.python.organd none of 
> > them is up?
>
> >  Anybody else having problems with python.org today? Is there a scheduled 
> > downtime?
>
> >  Thanks
>
> Appears to be up now, for me at least. No reported troubles with DNS.
> If you're still unable to get to it, try doing a DNS lookup, or try
> pinging 82.94.164.162 (which iswww.python.orgaccording to my
> lookup). Which one's out?
>
> ChrisA

only pypi is still unaccessible (502 Bad Gateway).

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


Re: Is python.org down?

2011-12-30 Thread vikash agrawal
hi Everyone,

it seems http://in.pycon.org/2011/  is also down :(

Regards
Vikash Agrawal

-- 
sent via HTC Sensation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickling instances of metaclass generated classes

2011-12-30 Thread lars van gemerden
On Dec 30, 12:16 pm, lars van gemerden  wrote:
> On Dec 29, 8:55 pm, Ian Kelly  wrote:
>
>
>
>
>
>
>
>
>
> > On Thu, Dec 29, 2011 at 2:55 AM, lars van gemerden  
> > wrote:
>
> > > Hello,
>
> > > Can someone help me with the following:
>
> > > I am using metaclasses to make classes and these classes to make
> > > instances. Now I want to use multiprocessing, which needs to pickle
> > > these instances.
>
> > > Pickle cannot find the class definitions of the instances. I am trying
> > > to add a line to the __new__ of the metaclass to add the new class
> > > under the right name in the right module/place, so pickle can find
> > > it.
>
> > > Is this the right approach? Can anyone explain to me where/how to add
> > > these classes for pickle to find and maybe why?
>
> > It sounds like you're trying to do something like this?
>
> > >>> class MetaClass(type):
>
> > ...     pass
> > ...>>> instance = MetaClass('', (object,), {})()
> > >>> instance
>
> > <__main__. object at 0x00CC00F0 import pickle
> > >>> pickle.dumps(instance)
>
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "c:\python27\lib\pickle.py", line 1374, in dumps
> >     Pickler(file, protocol).dump(obj)
> >   File "c:\python27\lib\pickle.py", line 224, in dump
> >     self.save(obj)
> >   File "c:\python27\lib\pickle.py", line 331, in save
> >     self.save_reduce(obj=obj, *rv)
> >   File "c:\python27\lib\pickle.py", line 401, in save_reduce
> >     save(args)
> >   File "c:\python27\lib\pickle.py", line 286, in save
> >     f(self, obj) # Call unbound method with explicit self
> >   File "c:\python27\lib\pickle.py", line 562, in save_tuple
> >     save(element)
> >   File "c:\python27\lib\pickle.py", line 295, in save
> >     self.save_global(obj)
> >   File "c:\python27\lib\pickle.py", line 748, in save_global
> >     (obj, module, name))
> > pickle.PicklingError: Can't pickle '>:
> > it's not found as __main__.
>
> > Yeah, pickle's not going to work with anonymous classes.  As you
> > suggest, you could dynamically add the classes to the module namespace
> > so that pickle.dumps will find them, but bear in mind that they will
> > also have to exist when calling pickle.loads, so you will need to be
> > able to reconstruct the same anonymous classes before unpickling later
> > on.
>
> > Cheers,
> > Ian
> Ian also wrote:
>
> '''
> Actually, I was wrong, you probably don't need to do that.  I suggest
> going with Robert Kern's suggestion to either register the class with
> the copy_reg module, or (perhaps better since it won't leak
> registrations) implement a __reduce__ method on the class.  For
> example, this seems to work:
>
> >>> def reconstructor(*metaclass_args):
>
> ...     cls = MetaClass.build_class(*metaclass_args)
> ...     self = cls.__new__(cls)
> ...     return self
> ...>>> class MetaClass(type):
>
> ...     @classmethod
> ...     def build_class(mcs, arg1, arg2, arg3):
> ...         # Do something useful with the args...
> ...         class _AnonymousClass(object):
> ...             __metaclass__ = mcs
> ...             def __reduce__(self):
> ...                 return (reconstructor, ('foo', 'bar', 'baz'),
> self.__dict__)
> ...         return _AnonymousClass
> ...>>> instance = MetaClass.build_class('foo', 'bar', 'baz')()
> >>> instance
>
> <__main__._AnonymousClass object at 0x011DB410 instance.banana = 42
> >>> import pickle
> >>> s = pickle.dumps(instance)
> >>> s
>
> "c__main__\nreconstructor
> \np0\n(S'foo'\np1\nS'bar'\np2\nS'baz'\np3\ntp4\nRp5\n(dp6\nS'banana'\np7\nI 
> 42\nsb.">>> inst2 = pickle.loads(s)
> >>> inst2
>
> <__main__._AnonymousClass object at 0x011DBE90 inst2.banana
> 42
> >>> inst2.__class__ is instance.__class__
>
> False
>
> Cheers,
> Ian
>
> '''

Interesting, though I cannot say I completely understand this solution
(looked up __reduce__, but still). I am trying to adapt this example
to a situation where the metaclass generated classes are named at
runtime (not anonymous), but cannot figure it out.

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


Re: pickling instances of metaclass generated classes

2011-12-30 Thread lars van gemerden
On Dec 30, 4:56 pm, lars van gemerden  wrote:
> On Dec 30, 12:16 pm, lars van gemerden  wrote:
>
>
>
>
>
>
>
>
>
> > On Dec 29, 8:55 pm, Ian Kelly  wrote:
>
> > > On Thu, Dec 29, 2011 at 2:55 AM, lars van gemerden  
> > > wrote:
>
> > > > Hello,
>
> > > > Can someone help me with the following:
>
> > > > I am using metaclasses to make classes and these classes to make
> > > > instances. Now I want to use multiprocessing, which needs to pickle
> > > > these instances.
>
> > > > Pickle cannot find the class definitions of the instances. I am trying
> > > > to add a line to the __new__ of the metaclass to add the new class
> > > > under the right name in the right module/place, so pickle can find
> > > > it.
>
> > > > Is this the right approach? Can anyone explain to me where/how to add
> > > > these classes for pickle to find and maybe why?
>
> > > It sounds like you're trying to do something like this?
>
> > > >>> class MetaClass(type):
>
> > > ...     pass
> > > ...>>> instance = MetaClass('', (object,), {})()
> > > >>> instance
>
> > > <__main__. object at 0x00CC00F0 import pickle
> > > >>> pickle.dumps(instance)
>
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > >   File "c:\python27\lib\pickle.py", line 1374, in dumps
> > >     Pickler(file, protocol).dump(obj)
> > >   File "c:\python27\lib\pickle.py", line 224, in dump
> > >     self.save(obj)
> > >   File "c:\python27\lib\pickle.py", line 331, in save
> > >     self.save_reduce(obj=obj, *rv)
> > >   File "c:\python27\lib\pickle.py", line 401, in save_reduce
> > >     save(args)
> > >   File "c:\python27\lib\pickle.py", line 286, in save
> > >     f(self, obj) # Call unbound method with explicit self
> > >   File "c:\python27\lib\pickle.py", line 562, in save_tuple
> > >     save(element)
> > >   File "c:\python27\lib\pickle.py", line 295, in save
> > >     self.save_global(obj)
> > >   File "c:\python27\lib\pickle.py", line 748, in save_global
> > >     (obj, module, name))
> > > pickle.PicklingError: Can't pickle '>:
> > > it's not found as __main__.
>
> > > Yeah, pickle's not going to work with anonymous classes.  As you
> > > suggest, you could dynamically add the classes to the module namespace
> > > so that pickle.dumps will find them, but bear in mind that they will
> > > also have to exist when calling pickle.loads, so you will need to be
> > > able to reconstruct the same anonymous classes before unpickling later
> > > on.
>
> > > Cheers,
> > > Ian
> > Ian also wrote:
>
> > '''
> > Actually, I was wrong, you probably don't need to do that.  I suggest
> > going with Robert Kern's suggestion to either register the class with
> > the copy_reg module, or (perhaps better since it won't leak
> > registrations) implement a __reduce__ method on the class.  For
> > example, this seems to work:
>
> > >>> def reconstructor(*metaclass_args):
>
> > ...     cls = MetaClass.build_class(*metaclass_args)
> > ...     self = cls.__new__(cls)
> > ...     return self
> > ...>>> class MetaClass(type):
>
> > ...     @classmethod
> > ...     def build_class(mcs, arg1, arg2, arg3):
> > ...         # Do something useful with the args...
> > ...         class _AnonymousClass(object):
> > ...             __metaclass__ = mcs
> > ...             def __reduce__(self):
> > ...                 return (reconstructor, ('foo', 'bar', 'baz'),
> > self.__dict__)
> > ...         return _AnonymousClass
> > ...>>> instance = MetaClass.build_class('foo', 'bar', 'baz')()
> > >>> instance
>
> > <__main__._AnonymousClass object at 0x011DB410 instance.banana = 42
> > >>> import pickle
> > >>> s = pickle.dumps(instance)
> > >>> s
>
> > "c__main__\nreconstructor
> > \np0\n(S'foo'\np1\nS'bar'\np2\nS'baz'\np3\ntp4\nRp5\n(dp6\nS'banana'\np7\nI 
> > 42\nsb.">>> inst2 = pickle.loads(s)
> > >>> inst2
>
> > <__main__._AnonymousClass object at 0x011DBE90 inst2.banana
> > 42
> > >>> inst2.__class__ is instance.__class__
>
> > False
>
> > Cheers,
> > Ian
>
> > '''
>
> Interesting, though I cannot say I completely understand this solution
> (looked up __reduce__, but still). I am trying to adapt this example
> to a situation where the metaclass generated classes are named at
> runtime (not anonymous), but cannot figure it out.
>
> Cheers, Lars

Found a way to name the classes:

def reconstructor(*metaclass_args):
cls = MetaClass2.build_class(*metaclass_args)
self = cls.__new__(cls)
return self

class MetaClass(type):
@classmethod
def build_class(mcs, name, arg1, arg2, arg3):
return mcs(name, (object,), {"__reduce__": lambda e:
(reconstructor2, (name, arg1, arg2, arg3), e.__dict__)})

I still wonder whether it might be easier to add the class to the
namespace. Can anyone help me with that?

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


Doing a HTTP DELETE operation with urllib2?

2011-12-30 Thread Roy Smith
Is there some way to make urllib2.urlopen() perform a DELETE instead of a GET 
or POST?

 I'm hoping I don't have to dip way down into httplib.  I've got an application 
test framework built on top of urllib2.  It makes heavy use of 
HTTPCookieProcessor.  If I need to use the httplib calls directly, I'll have to 
re-implement a lot of that machinery.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pickling instances of metaclass generated classes

2011-12-30 Thread Ian Kelly
On Fri, Dec 30, 2011 at 9:51 AM, lars van gemerden  wrote:
> I still wonder whether it might be easier to add the class to the
> namespace. Can anyone help me with that?

from mypackage import mymodule

setattr(mymodule, myclass.__name__, myclass)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doing a HTTP DELETE operation with urllib2?

2011-12-30 Thread Douglas Landgraf

Hi,

On 12/30/2011 12:01 PM, Roy Smith wrote:

Is there some way to make urllib2.urlopen() perform a DELETE instead of a GET 
or POST?

  I'm hoping I don't have to dip way down into httplib.  I've got an 
application test framework built on top of urllib2.  It makes heavy use of 
HTTPCookieProcessor.  If I need to use the httplib calls directly, I'll have to 
re-implement a lot of that machinery.

You might want to look:
https://github.com/dougsland/rhev3-restapi-scripts/blob/master/sample-delete.py

--
Cheers
Douglas

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


Creating a binary only python distribution of a C extension module and including some additional python and c files in it

2011-12-30 Thread akhilesh singhania
Hi,

I have a extension module in C which I want to distribute in binary
format, ideally an rpm. Additionally, I want to include some python
files (examples on how to use the extension module) and source for a
library the module dynamically links to (c,h, and make files).

How do I specify the example python file in setup.py so that it will
be included in the rpm?

If I specify it as scripts, I get the following error:

$ python setup.py bdist --format=rpm

  running build_scripts
  creating build/scripts-2.6
  error: file 'foo.py' does not exist
  error: Bad exit status from /var/tmp/rpm-tmp.yjws9x (%build)
If I specify it as data_files, I get the following error:

$ python setup.py bdist --format=rpm

  error: Installed (but unpackaged) file(s) found:
 /usr/foo.pyc
 /usr/foo.pyo
If I specify it as py_modules, I do not get errors but it is not
included in the resulting rpm.

Specifying it as a script works if I use

$ python setup.py bdist --format=gztar
Additionally, can I control the hierarchy of how the files are laid
out in the rpm?

Currently, I am specifying the c,h,make files as data_files and they
get placed in /usr, which is not desirable.

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


Re: How to get function string name from i-th stack position?

2011-12-30 Thread Tim Chase

On 12/30/11 11:51, dmitrey wrote:

how to get string name of a function that is n levels above
the current Python interpreter position?


Use the results of traceback.extract_stack()

  from traceback import extract_stack
  def one(x):
print "one", x
stk = extract_stack()
for mod, lineno, fun_name, call_code_text in stk:
  print "[%s:%i] in %s" % (mod, lineno, fun_name)
  def two(x):
print "two", x
one(x)
  def three(x):
print "three", x
two(x)
  three("Hi")


-tkc



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


Re: How to get function string name from i-th stack position?

2011-12-30 Thread dmitrey
On Dec 30, 8:35 pm, Tim Chase  wrote:
> On 12/30/11 11:51, dmitrey wrote:
>
> > how to get string name of a function that is n levels above
> > the current Python interpreter position?
>
> Use the results of traceback.extract_stack()
>
>    from traceback import extract_stack
>    def one(x):
>      print "one", x
>      stk = extract_stack()
>      for mod, lineno, fun_name, call_code_text in stk:
>        print "[%s:%i] in %s" % (mod, lineno, fun_name)
>    def two(x):
>      print "two", x
>      one(x)
>    def three(x):
>      print "three", x
>      two(x)
>    three("Hi")
>
> -tkc

Thank you. And what should I do to get function by itself instead of
its string name, e.g. I want to know does this function is my_func or
any other? For example, I would like to check is this function Python
sum(), or maybe numpy.sum(), or anything else?
Regards, D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doing a HTTP DELETE operation with urllib2?

2011-12-30 Thread Roy Smith
Ah, cool.  I didn't know you could do that.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Doing a HTTP DELETE operation with urllib2?

2011-12-30 Thread Steven D'Aprano
On Fri, 30 Dec 2011 10:57:06 -0800, Roy Smith wrote:

> Ah, cool.  I didn't know you could do that.  Thanks.

Who are you talking to, and what is "that"?

Replies with no context are somewhat less than useful. It might have made 
sense in your head when you wrote the reply, but to those reading, it is 
rather cryptic.


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


Re: Doing a HTTP DELETE operation with urllib2?

2011-12-30 Thread Dave Angel

On 12/30/2011 03:37 PM, Steven D'Aprano wrote:

On Fri, 30 Dec 2011 10:57:06 -0800, Roy Smith wrote:


Ah, cool.  I didn't know you could do that.  Thanks.

Who are you talking to, and what is "that"?

Replies with no context are somewhat less than useful. It might have made
sense in your head when you wrote the reply, but to those reading, it is
rather cryptic.


Actually I think he was replying to Roy Smith's message, which has a 
timestamp of 77 minutes later.  Interesting the effects you get when 
some clocks are allowed to drift.




--

DaveA

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


mutually exclusive arguments to a constructor

2011-12-30 Thread Adam Funk
(Warning: this question obviously reflects the fact that I am more
accustomed to using Java than Python.)

Suppose I'm creating a class that represents a bearing or azimuth,
created either from a string of traditional bearing notation
("N24d30mE") or from a number indicating the angle in degrees as
usually measured in trigonometry (65.5, measured counter-clockwise
from the x-axis).  The class will have methods to return the same
bearing in various formats.

In Java, I would write two constructors, one taking a single String
argument and one taking a single Double argument.  But in Python, a
class can have only one __init__ method, although it can have a lot of
optional arguments with default values.  What's the correct way to
deal with a situation like the one I've outlined above?


-- 
Unix is a user-friendly operating system. It's just very choosy about
its friends.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Günther Dietrich
Adam Funk  wrote:

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

You can determine the type of the input data by using isinstance() and 
take the appropriate actions depending on this decision:

>>> class MyClass(object):
... def __init__(self, input_data):
... if isinstance(input_data, basestring):
... print "Do actions for string type input"
... elif isinstance(input_data, float):
... print "Do actions for float type input"
... def get_output_data(self):
... return "output data"
... 
>>> a = MyClass("String")
Do actions for string type input
>>> b = MyClass(15.9)
Do actions for float type input



Best regards,

Günther
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mutually exclusive arguments to a constructor

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

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

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

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

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

Mel.

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


Re: mutually exclusive arguments to a constructor

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

(Using Python 3 below)

Method 1
--
Your __init__ method could take the angle as an argument (which seems
the most natural to me).  Then you could have a class method that
takes the string

i.e.

class Bearing:
def __init__(self, angle):
self.angle = angle
# or whatever your internal reprsentation is
@classmethod
def fromstring(cls, string):
# Here, work out the angle from the string
return cls(angle)

So you can do:

b = Bearing(65.5)

or

b = Bearing.fromstring("N24d30mE")

Method 2
--

You can test the type of the argument of the __init__ method

class Bearing:
def __init__(self, arg):
if isinstance(arg, str):
# here calculate the value of angle
else:
angle = float(angle)
self.angle = angle

Now you can do:

b = Bearing(65.5)

or

b = Bearing("N24d30mE")

Both methods are used for builtin types:

>>> int('12')
12
>>> int(12.5)
12
>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}
>>> dict.fromkeys([1, 2])
{1: None, 2: None}

HTH

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


Re: mutually exclusive arguments to a constructor

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

Similar to other answers already posted:


#!/usr/bin/env python
class azimuth:
def __init__(self, bearing, heading):
self.bearing = bearing
self.heading = heading
if not bearing:
self.bearing = 30.5 # or, realistically, a calculation
based on the heading
if not heading:
self.heading = "N..." # or, realistically, a calculation
based on the bearing
@staticmethod
def getBearingInstance(bearing):
return azimuth(bearing, None)
@staticmethod
def getHeadingInstance(heading):
return azimuth(None, heading)

azimuth1 = azimuth.getBearingInstance("N24d30mE")
print azimuth1.heading

azimuth2 = azimuth.getHeadingInstance(30)
print azimuth2.bearing
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get function string name from i-th stack position?

2011-12-30 Thread Ian Kelly
On Fri, Dec 30, 2011 at 11:43 AM, dmitrey  wrote:
> Thank you. And what should I do to get function by itself instead of
> its string name, e.g. I want to know does this function is my_func or
> any other? For example, I would like to check is this function Python
> sum(), or maybe numpy.sum(), or anything else?

The Python stack only includes Python code objects.  Built-ins like
sum won't appear in it because they're basically C functions and don't
have associated code objects.  If you really want to see them, you
could probably do something with ctypes to inspect the C stack, but I
don't recommend it.

You can get the Python code objects from the stack by calling
inspect.stack(), which includes each frame object currently on the
stack as the first member of each tuple.  E.g.:

frames = map(operator.itemgetter(0), inspect.stack())

Each frame has an f_code attribute that stores the code object
associated with that frame.  Getting the actual function from the code
object is tricky, for two reasons.  One, not all code objects
represent functions.  There are also code objects for modules, class
definitions, and probably other thing as well.  Two, code objects
don't have associated functions. The relationship is the reverse:
functions have associated code objects.  You would have to iterate
over each function that you're interested in, looking for one with a
func_code attribute that "is" the frame's f_code attribute.

In any case, testing function identity is a rather large rabbit hole
that is best avoided.  These are mathematically the same function:

def plus1(value):
return value + 1

plus_one = lambda x: x + 1

But they are two distinct function objects, and there is no way
programmatically to determine that they are the same function except
by comparing the bytecode (which won't work generally because of the
halting problem).

What is it that you're trying to do?  Perhaps the helpful folks on the
list will be able to suggest a better solution if you can provide more
details.

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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Steven D'Aprano
On Fri, 30 Dec 2011 20:40:16 +, Adam Funk wrote:

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

The most idiomatic way to do this would be with named constructor 
functions, or by testing the argument type in __init__. For example:

# Method 1
class Azimuth(object):
def __init__(self, angle):
# Initialise an azimuth object from an angle (float)
self._angle = float(angle)
@classmethod
def from_bearing(cls, bearing):
# Create an azimuth object from a bearing (string).
angle = cls.bearing_to_angle(bearing)
return cls(angle)
@staticmethod
def bearing_to_angle(bearing):
# Convert a bearing (string) into a float.
return 0.0  # whatever...


Note some features of this version:

* Normal methods receive the instance as first argument, "self".

* We use the classmethod and staticmethod decorators to create class 
  and static methods. Be warned that the meaning of these are NOT 
  the same as in Java!

* Class methods receive the class object as first argument, "cls". 
  Hence the name. Note that in Python, classes are objects too.

* We make from_bearing a class method, so we can call it from either
  the class itself:

  ang = Azimuth.from_bearing("25N14E")

  or from an existing instance:

  ang2 = ang.from_bearing("17N31W")

* Static methods don't receive either the class or the instance. They
  are equivalent to a top level function, except encapsulated inside
  a class.


# Method 2
class Azimuth(object):
def __init__(self, arg):
# Initialise an azimuth object from arg, either an angle (float)
# or a bearing (string).
if isinstance(arg, str):
angle = bearing_to_angle(arg)
else:
angle = float(arg)
self._angle = float(angle)

def bearing_to_angle(bearing):
# Convert a bearing (string) into a float.
return 0.0  # whatever...


Note that in this example, I've turned bearing_to_angle into a regular 
function outside of the class instead of a static method. Just because I 
can. This is probably slightly more idiomatic than the use of static 
methods.


Either method is acceptable, although the first is slightly more "pure" 
because it doesn't use isinstance. The second may fail if the user passes 
a string-like object which behaves identically to strings, but doesn't 
inherit from str. If you care about that, you should prefer the first way 
with an explicit from_bearing method.



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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Steven D'Aprano
On Fri, 30 Dec 2011 21:18:29 +, Jason Friedman wrote:

> class azimuth:
> def __init__(self, bearing, heading):

It is conventional, and recommended, to use an initial capital letter for 
classes. (Yes, Python built-ins violate that rule, and indeed so do some 
non-built-ins.) See PEP 8 for the recommended style guide.


[...]
> @staticmethod
> def getBearingInstance(bearing):
> return azimuth(bearing, None)
> @staticmethod
> def getHeadingInstance(heading):
> return azimuth(None, heading)

In this case, you should use classmethod rather than staticmethod and 
avoid hard-coding the class:

@classmethod
def getBearingInstance(cls, bearing):
return cls(bearing, None)

That way subclassing will work correctly:


class MyAzimuth(azimuth):
pass

angle = MyAzimuth.getBearingInstance("N24d30mE")

will return a MyAzimuth instance instead of an azimuth instance.



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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Roy Smith
In article ,
 Adam Funk  wrote:

> (Warning: this question obviously reflects the fact that I am more
> accustomed to using Java than Python.)
> 
> Suppose I'm creating a class that represents a bearing or azimuth,
> created either from a string of traditional bearing notation
> ("N24d30mE") or from a number indicating the angle in degrees as
> usually measured in trigonometry (65.5, measured counter-clockwise
> from the x-axis).

There's two ways to do this.

One would be to have the __init__ method switch on the type of its 
argument:

def __init__(self, bearing_or_azimuth):
   if isinstance(bearing_or_azimuth, basestring):
  # do the bearing thing
   else:
  # do the azimuth thing

I suspect many people would consider that unpythonic.  The other way 
would be what, in the C++/Java world, would be called the "named 
constructor idiom".  Just write two factory functions:

class DirectionIndicatingThingie:
   @staticmethod
   def from_bearing(cls, bearing):
  dit = DirectionIndicatingThingie()
  dit.direction = whatever
  return dit

and likewise for from_azimuth()

"But!", some C++/Java type bondage addicts might cry, "there's nothing 
to prevent somebody from creating a DirectionIndicatingThingie directly, 
bypassing the factory functions.  There's no way to make the constructor 
private!".  To which the free-willed pythonistas would respond, "If it 
hurts when you do that, don't do that".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Chris Angelico
On Sat, Dec 31, 2011 at 10:24 AM, Roy Smith  wrote:
> "But!", some C++/Java type bondage addicts might cry, "there's nothing
> to prevent somebody from creating a DirectionIndicatingThingie directly,
> bypassing the factory functions.  There's no way to make the constructor
> private!".  To which the free-willed pythonistas would respond, "If it
> hurts when you do that, don't do that".

You know a Python programmer's been at your C++ code when it opens:
#define class struct

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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Roy Smith
In article ,
 Chris Angelico  wrote:

> On Sat, Dec 31, 2011 at 10:24 AM, Roy Smith  wrote:
> > "But!", some C++/Java type bondage addicts might cry, "there's nothing
> > to prevent somebody from creating a DirectionIndicatingThingie directly,
> > bypassing the factory functions.  There's no way to make the constructor
> > private!".  To which the free-willed pythonistas would respond, "If it
> > hurts when you do that, don't do that".
> 
> You know a Python programmer's been at your C++ code when it opens:
> #define class struct

Why stop there?

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


Re: mutually exclusive arguments to a constructor

2011-12-30 Thread Chris Angelico
On Sat, Dec 31, 2011 at 10:39 AM, Roy Smith  wrote:
> In article ,
>  Chris Angelico  wrote:
>
>> You know a Python programmer's been at your C++ code when it opens:
>> #define class struct
>
> Why stop there?
>
> #define private public

Probably yeah, do both. Anyway, life's so much easier when you don't
have to write trivial getter/setter methods (and then maintain them).
I've never had a situation where I've changed a private member while
keeping the getters and setters unchanged; the ONLY benefit accessor
methods have ever given to me personally has been logging (and
granted, that is hard to do without them - since you can't override
__getitem__ in C++ - but how often do you really need that facility?).

I used to believe in the separation of interface from implementation.
Then I realised that most of the separation was transparent anyway,
and gave up on it. And then realised why the separation is a good idea
after all. :)

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


Re: Which library for audio playback ?

2011-12-30 Thread K Richard Pixley

On 12/29/11 05:55 , Jérôme wrote:

I'm writing a small application that plays sound through the speakers. The
sounds are juste sine waves of arbitrary frequency I create in the code, not
sample .wav files.

I didn't expect the choice for an audio library to be that complicated. There
are several libraries, and none of them seems to be *the* reference.

Searching the web, I found these resources :

http://wiki.python.org/moin/Audio
http://wiki.python.org/moin/PythonInMusic

* I privileged ALSA to OSS as I read elsewhere that OSS is deprecated, or on
   its way to be. (And JACK is not widely installed, apart from specific
   applications (audio work).)

* Then, I picked the alsaaudio library (http://pyalsaaudio.sourceforge.net/).
   I don't remember exactly why. I think the project had the most recent
   updates. I don't think any project claims to be (let alone aims at being)
   complete.

I'm wondering if I made a sensible choice.

There are other libraries, including the following two that are platform
independent :

* PyAudiere (http://pyaudiere.org/), OSS , not packaged for debian
* PyAudio (http://people.csail.mit.edu/hubert/pyaudio/)

What solution would you recommend ?

Are there other criterions I should take into account ?

Thanks.



I made a similar survey of available libraries recently.  I'm interested 
in MIDI also, though, primarily on mac.


There doesn't seem to be any definitive audio library for linux, 
although several, (jack, oss, alsa), exist.  (My impression is similar 
to yours, OSS is obsolete. Jack may be the better library technically, 
but is not as widely ported or available as ALSA.)


There is a definitive library for both audio and MIDI on mac - core 
audio.  There really aren't any competitors.


There is also a definitive library for windows, although I don't use 
windows.  It's the open source one with low latency that everyone in the 
professional world uses to replace windows because, (surprise!), windows 
isn't capable of coping.


I have found python libraries for each of these, although some are very 
low level libraries, basically just wrapping something even lower.  If 
anyone has done an integrated "full solution" for linux or mac, I didn't 
find it.  The closest I found was PortMIDI and PortAudio which appear to 
have ports for all three platforms as well as one or two sets of python 
bindings and seem to be high enough level to be both useful and 
productive.  The hard part there is that PortMIDI and PortAudio come in 
source, which requires a bit of hunting to track down prerequisites, etc.


Please keep us posted as I'm chasing a similar problem.

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


Re: Generating sin/square waves sound

2011-12-30 Thread K Richard Pixley

On 12/29/11 23:17 , Paulo da Silva wrote:

Hi,
Sorry if this is a FAQ, but I have googled and didn't find any
satisfatory answer.

Is there a simple way, preferably multiplataform (or linux), of
generating sinusoidal/square waves sound in python?

Thanks for any answers/suggestions.


I just posted on this elsewhere.  Look for a thread titled: "Which 
library for audio playback ?"


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


InvalidResponseError: headers must be str

2011-12-30 Thread Niklas Rosencrantz
I'm upgrading from python 2.5 to python 2.7 and then I'm starting to get this 
error:

InvalidResponseError: headers must be str

I think it is because somewhere my HTTP headers are cast to unicode instead of 
string but I can't find where in the code? The example code I'm trying to 
upgrade to python 2.7 is 
https://github.com/supernifty/gae-paypal-online-market-example

class Pay( object ):
  def __init__( self, amount, return_url, cancel_url, remote_address, 
secondary_receiver=None, ipn_url=None, shipping=False ):
headers = {
  'X-PAYPAL-SECURITY-USERID': str(settings.PAYPAL_USERID), 
  'X-PAYPAL-SECURITY-PASSWORD': str(settings.PAYPAL_PASSWORD), 
  'X-PAYPAL-SECURITY-SIGNATURE': str(settings.PAYPAL_SIGNATURE), 
  'X-PAYPAL-REQUEST-DATA-FORMAT': str('JSON'),
  'X-PAYPAL-RESPONSE-DATA-FORMAT': str('JSON'),
  'X-PAYPAL-APPLICATION-ID': str(settings.PAYPAL_APPLICATION_ID),
  'X-PAYPAL-DEVICE-IPADDRESS': str(remote_address),
}

data = {
  'currencyCode': 'USD',
  'returnUrl': return_url,
  'cancelUrl': cancel_url,
  'requestEnvelope': { 'errorLanguage': 'en_US' },
} 

if shipping:
  data['actionType'] = 'CREATE'
else:
  data['actionType'] = 'PAY'

if secondary_receiver == None: # simple payment
  data['receiverList'] = { 'receiver': [ { 'email': settings.PAYPAL_EMAIL, 
'amount': '%f' % amount } ] }
else: # chained
  commission = amount * settings.PAYPAL_COMMISSION
  data['receiverList'] = { 'receiver': [ 
  { 'email': settings.PAYPAL_EMAIL, 'amount': '%0.2f' % amount, 
'primary': 'true' },
  { 'email': secondary_receiver, 'amount': '%0.2f' % ( amount - 
commission ), 'primary': 'false' },
] 
  }

if ipn_url != None:
  data['ipnNotificationUrl'] = str(ipn_url)

self.raw_request = json.dumps(data)
#request = urllib2.Request( "%s%s" % ( settings.PAYPAL_ENDPOINT, "Pay" ), 
data=self.raw_request, headers=headers )
#self.raw_response = urllib2.urlopen( request ).read() 
self.raw_response = url_request( "%s%s" % ( str(settings.PAYPAL_ENDPOINT), 
str("Pay") ), data=self.raw_request, headers=headers ).content() 
logging.info( "response was: %s" % self.raw_response )
self.response = json.loads( str(self.raw_response) )
-- 
http://mail.python.org/mailman/listinfo/python-list


dict_to_xml

2011-12-30 Thread Emeka
Hello All,


I have a dictionary object I would like to convert to xml.

Could some assist with the link to libs to use?  Or good examples.

Regards,
Janus

-- 
*Satajanus  Nig. Ltd


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


Re: InvalidResponseError: headers must be str

2011-12-30 Thread Steven D'Aprano
On Fri, 30 Dec 2011 20:58:10 -0800, Niklas Rosencrantz wrote:

> I'm upgrading from python 2.5 to python 2.7 and then I'm starting to get
> this error:
> 
> InvalidResponseError: headers must be str

Please show the ENTIRE traceback, not just the error message. The 
traceback is very informative: it shows the actual line of code that 
causes the problem, plus the entire sequence of calls that lead to it. 
The error message on its own is almost useless.

Please COPY AND PASTE the traceback, do not re-type it from memory, 
summarize it, simplify it, or otherwise change it in any way.


> I think it is because somewhere my HTTP headers are cast to unicode

Why do you think that?


> instead of string but I can't find where in the code? 

Have you tried searching for any of these?

- direct calls to unicode()
- unicode literals u"..."
- calls to the decode method some_string.decode( ... )



> The example code
> I'm trying to upgrade to python 2.7 is
> https://github.com/supernifty/gae-paypal-online-market-example
> 
> class Pay( object ):
>   def __init__( self, amount, return_url, cancel_url, remote_address,
>   secondary_receiver=None, ipn_url=None, shipping=False ):
> headers = {
>   'X-PAYPAL-SECURITY-USERID': str(settings.PAYPAL_USERID),
>   'X-PAYPAL-SECURITY-PASSWORD': str(settings.PAYPAL_PASSWORD),
>   'X-PAYPAL-SECURITY-SIGNATURE': str(settings.PAYPAL_SIGNATURE),
>   'X-PAYPAL-REQUEST-DATA-FORMAT': str('JSON'),
>   'X-PAYPAL-RESPONSE-DATA-FORMAT': str('JSON'),
>   'X-PAYPAL-APPLICATION-ID': str(settings.PAYPAL_APPLICATION_ID),
>   'X-PAYPAL-DEVICE-IPADDRESS': str(remote_address),
> }


'JSON' is already a string. Calling str() on it is a waste of time.

What values do the various settings.* have? If they are already strings, 
calling str() again is a waste of time. I see you do this all through 
your class, needlessly calling str() on strings.



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