[Tutor] python instances and type
Hello, Sorry for the long email, but thanks in advance. I am not quite sure what is happening, so I have not been able to adequately seek a solution via Google, so if this answer is fairly easy to find on Google, let me know. I am not sure how to produce an example of my problem without using the python code and classes that I have, so I will try to compose an effective theoretical example below. If there are any clarifications to be made please let me know. Basically the problem I am having is obtaining the proper type identification from a Python object. So going through the motions, lets say I have 2 types: class foo_1: data = "" class foo_2: foo_1s={} Time goes by and some assignments are performed and foo_2 is populated with some foo_1 objects. Now, I am using the the function below, get_class_resolution to get the type of foo_1 and foo_2, and it works well when I don't perform any black magic voodoo and simply use after the object is created. It would return the string "foo_1" for the example below: x = foo_1() x.data = "boring" print type(x), type(x).mro() [] print get_class_resolution(x) foo_1 But I need to do black magic voodoo, and when I perform an operation similar to below on a foo_2 object the get_class_resolution returns "instance". In fact I am expecting it to return foo_1. foo_2o = foo_2() foo_2o.foo_1s["boring"] = x bar = foo_2o.foo_1s.values()[0] print type(bar), type(bar).mro() [, ] print get_class_resolution(bar) instance I am not sure what the difference between the instance vs. a class, but I never thought the type of the object was allowed to change. Any help would be appreciated. Thanks, Adam def get_class_resolution(obj): ''' get the first class resolution string for a particular object @type obj: Mixed/ Any @param obj: this is the object to get the name of. Good for aiding in the comparison of two objects by name and heirarchy @rtype: string @return: class name resolution of the object ''' # typical output is "[ ]" print str(type(obj).mro()) print str(type(obj)) name = str(type(obj).mro()).split("'")[1] if len(name.split(".")) > 1: return ".".join(name.split(".")[:-1]) return name ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to program to python the right way?
Hello everyone, I have pretty much finished hacking on my Thesis and I have come to the conclusion, I really do not know how to use Python to it "full" extent. Some of the things I have really messed up in my implementation are serialization (specifically sub-classes), classes, and instantiating them the "correct" way, and there are some things I have not tried, but I would like to like contained execution and thread management. Are there any books (with examples) out there that show some of these techniques and explain the gotchas that come with the package. Thanks in advance. Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to program to python the right way?
I guess the problem I am trying to quell really revolves around style and the proper way to do application programming with Python. So one of the things I found out the hard way about is classes. I started of programming my Python Classes using the old style, because I did not understand how the process works when a class is instantiated. class Foo: string = "" int = 0 On 4/21/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > Adam Pridgen wrote: > > Hello everyone, > > > > I have pretty much finished hacking on my Thesis and I have come to > > the conclusion, > > I really do not know how to use Python to it "full" extent. Some of > > the things I have really messed up in my implementation are > > serialization (specifically sub-classes), classes, and instantiating > > them the "correct" way, and there are some things I have not tried, > > but I would like to like contained execution and thread management. > > Are there any books (with examples) out there that show some of these > > techniques and explain the gotchas that come with the package. Thanks > > in advance. > > I think the Python Cookbook is an excellent book for learning idiomatic > Python. > > Your question is pretty vague, can you ask a more specific question > about an area where you are having trouble? > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to program to python the right way?
Disregard this email, gmail mis-fired. On 4/21/07, Adam Pridgen <[EMAIL PROTECTED]> wrote: > I guess the problem I am trying to quell really revolves around style > and the proper way to do application programming with Python. So one > of the things I found out the hard way about is classes. > > I started of programming my Python Classes using the old style, > because I did not understand how the process works when a class is > instantiated. > > > class Foo: > string = "" > int = 0 > > > On 4/21/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > Adam Pridgen wrote: > > > Hello everyone, > > > > > > I have pretty much finished hacking on my Thesis and I have come to > > > the conclusion, > > > I really do not know how to use Python to it "full" extent. Some of > > > the things I have really messed up in my implementation are > > > serialization (specifically sub-classes), classes, and instantiating > > > them the "correct" way, and there are some things I have not tried, > > > but I would like to like contained execution and thread management. > > > Are there any books (with examples) out there that show some of these > > > techniques and explain the gotchas that come with the package. Thanks > > > in advance. > > > > I think the Python Cookbook is an excellent book for learning idiomatic > > Python. > > > > Your question is pretty vague, can you ask a more specific question > > about an area where you are having trouble? > > > > Kent > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Declaring a Python/C Package and Accessing Python Constants from C API
Hello everyone, I am trying to create a python package that includes both a native python module and then a python module created using the Python/C API. I have several questions pertaining to this area. First, how do I make the C API module aware of the python module. Specifically, I have declared all of my constant variables because it was much easier and cleaner, but I want to be able to access those constants from my C API module. I know I can declare the python module globally, but the python module and the C API module are part of the same package. I have read Python C/API guide, and I could not find anything like an example or explanation related to performing this task. I have also seen a couple of posts online, but they seem to miss over this point. Is there anyone out there that has done something like this before? I am on a Posix/Linux system. Thanks in advance, Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaring a Python/C Package and Accessing Python Constants from C API
I guess to follow this question up, I am trying to combine an Extension module and Python module under a single package, and I am not having any luck with it. I know I have an error in my configuration script, but I am not sure where or how.Here is my directory structure: I am trying to setup my modules so that I can do the following: import python_foo.foo_defines import python_foo.foo_interface setup.py build/ <-- results from set install python_foo/ __init__.py foo_defines.py foo_interface.c foo_interface.h import os from distutils.core import setup, Extension from distutils.sysconfig import get_python_inc incdir = os.path.join(get_python_inc(plat_specific=1)) module = Extension('foo_interface', include_dirs = [incdir], libraries = [], library_dirs = [], sources = ['python_foo/foo_interface.c']) setup(name = 'python_foo', packages = ['python_foo'], package_dir = {'python_foo' : 'python_foo'}, ext_modules = [module], py_modules = ['python_foo.foo_defines' ] ) I perform: python setup.py install and it compiles and installs without error, but when I try the following: import python_foo from python_foo import foo_interface It says it can not find the module. Thanks for any help in advance, Adam On 5/11/07, Adam Pridgen <[EMAIL PROTECTED]> wrote: > Hello everyone, > > I am trying to create a python package that includes both a native > python module and then a python module created using the Python/C API. > I have several questions pertaining to this area. First, how do I > make the C API module aware of the python module. Specifically, I > have declared all of my constant variables because it was much easier > and cleaner, but I want to be able to access those constants from my C > API module. I know I can declare the python module globally, but the > python module and the C API module are part of the same package. I > have read Python C/API guide, and I could not find anything like an > example or explanation related to performing this task. I have also > seen a couple of posts online, but they seem to miss over this point. > Is there anyone out there that has done something like this before? I > am on a Posix/Linux system. > > Thanks in advance, > > Adam > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] ctypes typedef
Hey everyone, I am messing around with the ctypes package, and I wasn wondering how I go about defining a new type, where I essentially call an int foo. For example in C, I would use the following statement: typedef int foo; Is there an equivalent statement using ctypes, or is there another way of performing this task? Thanks in advance, Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unpickling data after passing over the network
Hello, I am having problems with unpickling data after I pass the data through a socket. Right now, I am pickling a basic string base 64 encoding and sending the data over the network. After the recipient client/server receives the data, it is decoded and then unpickled. The unpickling fails with an EOFError, and I am not sure why. I have tested the my process works between functions. I have not been able to find anything on google relating to this problem. Right now I am using Python 2.4.3 on a 64bit Linux box. Below is a stack trace and below that is the script. To run the script start the server in one command line: python BegPython.py server and in another shell start the client with python BegClient.py client . Thanks in advance for your help. -ds Traceback (most recent call last): File "BegClient.py", line 77, in ? elif sys.argv[1].lower() == "client": BegClient() File "BegClient.py", line 41, in BegClient data = DeserialDecode(recv_basic(mySocket)) File "BegClient.py", line 23, in DeserialDecode return cPickle.loads(base64.decodestring(data)) EOFError BegClient.py: # To Run client server start the server then the client: # python BegClient.py Server # python BegClient.py Client def Test(): import cPickle, base64 str = "This is one thing that I just do not understand, \ but I will give it a shot" print str str = SerialEncode(str) print str str = DeserialDecode(str) print str def SerialEncode(data): import cPickle, base64 return base64.encodestring(cPickle.dumps(data,2)) def DeserialDecode(data): import cPickle, base64 return cPickle.loads(base64.decodestring(data)) def recv_basic(the_socket): total_data=[] while True: data = the_socket.recv(8192) print data if data != "": break total_data.append(data) print "Finished Recving data" return ''.join(total_data) def BegClient(): import socket, cPickle mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.connect ( ( "", 64268 ) ) data = DeserialDecode(recv_basic(mySocket)) print data mySocket.send( SerialEncode("Hello!")) data = DeserialDecode(recv_basic(mySocket)) print data mySocket.send( SerialEncode("Bye!")) print data mySocket.close() def BegServer(): import socket, sys, __builtin__ def myhook(code): return code; sys.displayhook = myhook mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 64268 ) ) mySocket.listen ( 1 ) i = 0 import cPickle while i < 10: i += 1 channel, details = mySocket.accept() print 'We have opened a connection with', details channel.send ( SerialEncode("What's up")) code = DeserialDecode(recv_basic(channel)) print code if __name__ == "__main__": import sys if sys.argv[1].lower() == "server": BegServer() elif sys.argv[1].lower() == "client": BegClient() else: Test() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about local scopes (namespaces)
Sorry for the long email, and thanks in advance. In the below example, is the list foo supposed to retain the value after the function, Bar(), returns? Is the list foo supposed to reinitialized on each call to Bar(), meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is called w/out parameters)? In the example, Bar() is called multiple times, and for the first three times, I expect foo to initialized as an empty list. When I call Bar() and make the assignment however, it turns out that foo is not reinitialized and it acts like a statically type variable in C or Java (e.g. retaining its value from each call and subsequent execution). I would have expected only one instance of the string in f after it is assigned the name of foo, however there are four. My understanding of the code below is as follows: --If Bar is called without any parameters, then foo is initialized as an empty list, always. --If Bar is called with a list parameter, then the name foo is aliased to that object. --In the last two cases, if Bar() returns a value to an assignment, the list will be aliased to that variable name as well --When Bar() returns, if there is nothing aliased to the list foo, then the list is destroyed Is the my understanding correct? Thank you again for taking the time to review my question. --Adam def Bar(foo=[]): foo.append("newb got a keyboard\n") return foo if __name__ == "__main__": Bar() Bar() Bar() f = Bar() print f Results: C:\workspace\ProvingGrounds\src\Bill>python Bug.py ['newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a keyboard\n'] def Bar(foo=[]): foo.append("newb got a keyboard\n") return foo if __name__ == "__main__": Bar() Bar() Bar() f = Bar() print f ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] what instance type is a function object?
Thanks in advance for your help. I am trying to pickle a class, but I want to exclude function objects for obvious reasons. How do I determine if a python object is a function, specifically when using isinstance()? I am not sure what a type or instance a Python 'function' originates from. The below code throws an exception, because function is not a type. Presently I am attempting to do the following: def __getstate__( ret_val = {} for key in self.__dict__: if not isinstance(self.__dict__[key], function): pass # do assignment here Thanks again, Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dictionaries of Tuples of Strings
Hello, When I have a tuple with a single string in a dictionary entry and try to iterate over the tuple and it breaks the string into individual characters. Is this supposed to be happening? This problem is a little tricky to explain so I have included the output and the corresponding example code. In the example I have a dictionary with tuples of strings as the values. If I have more than one tuple, I am ok and the value is not broken into individual characters (look at the "type="in the code below. If I have only one string in the tuple value, then the string is broken into individual characters. Thanks again, Adam. Output: name="years_of_newbness" type="xs:hexbinary" name="years_of_newbness" type="xs:integer" name="newb" type="x" name="newb" type="s" name="newb" type=":" name="newb" type="t" name="newb" type="r" name="newb" type="i" name="newb" type="n" name="newb" type="g" Example.py: import sets def Foo (elements=None): e_types = set() str = "" for k in elements: e_types.clear() for j in TYPES_PYTHON_TO_XML[k[1]]:# <-- Problem arises here # a tuple with a single string in dictionary is broken apart if j in e_types: continue str += CreateXMLElement(k[0], j)+"\n" e_types.add(j) print str def CreateXMLComplex(name, elements): return XML_COMPLEX_STMNT%(name, elements) def CreateXMLElement(name, type): return XML_ELEMENT_STMNT%(name, type) XML_ELEMENT_STMNT = "name=\"%s\" type=\"%s\" " TYPES_PYTHON_TO_XML = { 'int':('xs:hexbinary','xs:integer'), 'str':("xs:string") } Foo([("years_of_newbness", "int")]) # <-- Works, more than one element in the tuple Foo([('newb', 'str')])# <-- Fails, only one element in the tuple import sets def Foo (elements=None): e_types = set() str = "" for k in elements: e_types.clear() for j in TYPES_PYTHON_TO_XML[k[1]]:# <-- Problem arises here # a tuple with a single string in dictionary is broken apart if j in e_types: continue str += CreateXMLElement(k[0], j)+"\n" e_types.add(j) print str def CreateXMLComplex(name, elements): return XML_COMPLEX_STMNT%(name, elements) def CreateXMLElement(name, type): return XML_ELEMENT_STMNT%(name, type) XML_ELEMENT_STMNT = "name=\"%s\" type=\"%s\" " TYPES_PYTHON_TO_XML = { 'int':('xs:hexbinary','xs:integer'), 'str':("xs:string") } Foo([("years_of_newbness", "int")]) # <-- Works, more than one element in the tuple Foo([('newb', 'str')])# <-- Fails, only one element in the tuple___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wav audio playback
You are getting these errors because the API for Python varies by release (e.g. 2.4 to 2.5) due to additions, bug fixes, etc.. The warning you are receiving is letting you know that it was compiled and meant to be run on Python 2.4, and also subtly warning that problems may arise when you run or write your scripts in the 2.5 environment. To get rid of the error safely, if possible compile PyAudio for Python 2.5, or if you can regress back to Python 2.4 until PyAudio package is available for Python 2.5. There might also be a flag that can be set to ignore warnings when you run the Python, but I am not sure about this. Some of the more Pythonic vets on the list might be able to provide feed back on that. However, from my past experience, regressing back to Python 2.4 seems to be the easiest and safest option in most cases. Regards, Adam On 2/26/07, Isaac <[EMAIL PROTECTED]> wrote: > hello from a programming newbie. > > I am writing a metronome function. > Currently, I am using a hack with the system bell: > > [code] > def tick(rate): > while true: #do until C-c > > print '\a' #system bell inside terminal > > time.sleep(rate) #pause at desired rate > > [/code] > > I would like to use any audio clip for a 'beat' of the metronome. > I have looked into pyaudio for .wav clips. I installed the binary for > pyaudio but it put the files into site-packages folder in > my python-2.4 framework directory; I copied the files to the site-packages > folder under 2.5 but when I import pyaudio at the Python 2.5 interpreter I > get: > > """ > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/pyaudio.py:101: > RuntimeWarning: Python C API version mismatch for module _portaudio: This > Python has API version 1013, module _portaudio has version 1012. > import _portaudio as pa """ > > It does play sound but how can I get rid of this error? Do I have to wait > for the newer version of portaudio and/or pyaudio to be released to keep > this error from happening? Should I be concerned with this warning? > Is there another, better, sound playback module that anyone recommend I > could use? > > I have mac ppc os X 10.4.8 (would like to have cross platform > functionality, eventually) > Using Python 2.5 > > cheers > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] executing a string representing python code
here's the magic you are looking for: func_str = \ ''' def some_func(value): # youwould check value instance here and do something to it print "Hello World", value return "Done" ''' exec(func_str) f = locals()["some_func"] print f("wasn't that cool!") When you exec the str, it will create a function object, and then you can obtain the object by accessing the object by kwd in the locals() dictionary. Guess it's not really magic, but I think it is still pretty cool ;) There also several variations to this method, but this is the most readable IMHO. Cheers, Adam On 3/2/07, Cecilia Alm <[EMAIL PROTECTED]> wrote: > I know that there are several ways to execute a string which represents a > piece of python code. > Out of curiosity, is it only eval which returns a value? (as below, where > the string corresponds to a defined function). > > >>> def addone(val): > ... return val + 1 > ... > >>> res = eval('addone(10)') > > Thanks! > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] kwds
Hello, I am having a difficult time understanding the whole "def function(*args, **kwds):" business, and I have not really found a clear or concise explanation via Google. My question is pretty much this, is **kwds a dictionary and can I use it like a dictionary, and what is the deal with the * or **? Sometime ago I found something explaining the basics of these parameters, but I lost the link and I lost that warm and fuzzy feeling I had about them ;). Thanks in advance, Adam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor