Re: help with calling a static method in a private class
On Sep 14, 4:38 pm, de...@web.de (Diez B. Roggisch) wrote: lallouslall...@lgwm.org writes: How can I keep the class private and have the following work: [code] class __internal_class(object): @staticmethod def meth1(s): print meth1:, s @staticmethod def meth2(s): print meth2:, __internal_class.meth1(s) x = __internal_class() x.meth2('sdf') [/code] By not using a double underscore. It is effectless on classes anyway (they are not hidden because of that). And additionally, but simply not using staticmethods at all. It's a rather obscure feature ofpython- usually, classmethods are what is considered a static method in other languages. And with that, even your double underscores work: class __internal_class(object): @classmethod def meth1(cls, s): print meth1:, s @classmethod def meth2(cls, s): print meth2:, cls.meth1(s) x = __internal_class() x.meth2('sdf') Diez Thanks, that does the trick. -- http://mail.python.org/mailman/listinfo/python-list
help with calling a static method in a private class
How can I keep the class private and have the following work: [code] class __internal_class(object): @staticmethod def meth1(s): print meth1:, s @staticmethod def meth2(s): print meth2:, __internal_class.meth1(s) x = __internal_class() x.meth2('sdf') [/code] Thanks -- http://mail.python.org/mailman/listinfo/python-list
Book review / advise
Hello, I wonder if anyone read this: http://www.amazon.com/PYTHON-2-6-Extending-Embedding-documentation/dp/1441419608/ref=sr_1_7?ie=UTF8s=booksqid=1277214352sr=1-7 or this: http://www.amazon.com/Python-Extending-Embedding-Documentation-Manual/dp/1441412743/ref=pd_sim_b_3 Are these books just a print out of the manual that comes w/ Python distribution or they are written in a different way and more organized way? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Hi again, Well, it seems the printed version of the manual. Can anyone suggest a nice book to learn more about the Python C Api? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
Hi James, For me it is not a matter of competency to seek a book: organized, structured and uniform way of presenting information. Nonetheless, I always refer to the sources to get my questions answered...but a book (with the qualities I mentioned above) would make everyone's life easier. :) On Jun 22, 4:24 pm, James Mills prolo...@shortcircuit.net.au wrote: On Wed, Jun 23, 2010 at 12:14 AM, lallous lall...@lgwm.org wrote: Well, it seems the printed version of the manual. Can anyone suggest a nice book to learn more about the Python C Api? It's not really a book, but how about the source ? If you're a competent C programmer you're not really going to even need a pretty book now are you ? :) (No phun intended! --james -- -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: Book review / advise
On Jun 22, 4:49 pm, James Mills prolo...@shortcircuit.net.au wrote: On Wed, Jun 23, 2010 at 12:27 AM, lallous lall...@lgwm.org wrote: For me it is not a matter of competency to seek a book: organized, structured and uniform way of presenting information. Nonetheless, I always refer to the sources to get my questions answered...but a book (with the qualities I mentioned above) would make everyone's life easier. Like I said, no phun intended :) I don't know any off hand and reading printed material is not something I enjoy! Yes James, I understand. I did not mean to attack you or defend a point rather than make a point. I appreciate your feedback. Thank you Tim too. Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
to pass self or not to pass self
Hello, Learning Python from the help file and online resources can leave one with many gaps. Can someone comment on the following: # - class X: T = 1 def f1(self, arg): print f1, arg=%d % arg def f2(self, arg): print f2, arg=%d % arg def f3(self, arg): print f3, arg=%d % arg # this: F = f2 # versus this: func_tbl = { 1: f1, 2: f2, 3: f3 } def test1(self, n, arg): # why passing 'self' is needed? return self.func_tbl[n](self, arg) def test2(self): f = self.f1 f(6) f = self.F # why passing self is not needed? f(87) # - x = X() x.test1(1, 5) print '--' x.test2() Why in test1() when it uses the class variable func_tbl we still need to pass self, but in test2() we don't ? What is the difference between the reference in 'F' and 'func_tbl' ? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure virtual functions in Python?
On Feb 21, 11:21 am, Lie Ryan lie.1...@gmail.com wrote: On 02/21/10 19:27,lallouswrote: snip If the base defines the method and it was empty, then my C++ code would still call the function. This is not optimal because I don't want to go from C++ to Python if the _derived_ class does not implement the cb. That sounds like a microoptimization; have you profiled your code and determined that calling empty function causes a bottleneck? I doubt it. Now the base class should define it so that doc parsers properly describe the base class. The recipe suggested is not worth the trouble. Unfortunately I cannot use abc module since I use Python 2.5 Because nobody here could have guessed that your dispatcher was written in C++; your problem is near trivial if your dispatcher is a pure-python code. You are right. I haven't checked how much it costs to continuously call an empty function, but why do it if I know (during initialization from my C++ dispatcher code) that certain Python object should not have certain methods called. I still prefer not to call at all, even if it was an empty function. Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure virtual functions in Python?
On Feb 22, 12:42 am, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: lallouswrote: If the base defines the method and it was empty, then my C++ code would still call the function. This is not optimal because I don't want to go from C++ to Python if the _derived_ class does not implement the cb. I would simply not implement the method at all in the base class. Then the C++ code can do an attribute lookup for the method, and if it's not found, do nothing. -- Greg That is what I currently do. But if I comment out the implementations (empty ones) then the documentation generation tool will not document the callbacks. -- http://mail.python.org/mailman/listinfo/python-list
Walking lists
Hello I am still learning Python, and have a question, perhaps I can shorten the code: L = ( (1, 2, 3), (4,), (5,), (6, 7) ) for x in L: print x What I want, is to write the for loop, something like this: for (first_element, the_rest) in L: print first_element for x in the_rest: # now access the rest of the elements I know I can : for x in L: first = x[0] rest = x[1:] Probably that is not possible, but just asking. Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Walking lists
Thank you all for the replies. The solution using Python 3's syntax look very intuitive. Thanks Tim, Arnaud for the idea (I am using 2.x) -- Elias On Feb 25, 1:28 pm, lallous elias.bachaal...@gmail.com wrote: Hello I am still learning Python, and have a question, perhaps I can shorten the code: L = ( (1, 2, 3), (4,), (5,), (6, 7) ) for x in L: print x What I want, is to write the for loop, something like this: for (first_element, the_rest) in L: print first_element for x in the_rest: # now access the rest of the elements I know I can : for x in L: first = x[0] rest = x[1:] Probably that is not possible, but just asking. Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure virtual functions in Python?
On Feb 20, 6:08 pm, Martin v. Loewis mar...@v.loewis.de wrote: class C1: # Pure virtual def cb(self, param1, param2): This is a callback �...@param param1: ... �...@param param2: ... raise NotImplementedError, Implement me # Dispatcher function that calls 'cb' only if 'cb' is implemented in child classes def dispatcher(c): if hasattr(c, 'cb'): c.cb(Hello, World) dispatcher(C2()) dispatcher(C3()) What I want is the ability to have the dispatcher() not to call 'cb' if it was not implemented in one of the child classes. Please advise. There is nothing more beyond that what you already did. You can raise a NotImplementedError for classes that don't implement the method. That's it. That's not true. Currently, the hasattr() call would report that cb is available, when it is actually not implemented. It would be possible to do something like if hasattr(c, 'cb') and not is_pure(c.cb): c.cb(Hello, World) is_pure could, for example, look at a function attribute of the callback. You'd write something like @pure_virtual def cb(self, param1, param2): not_implemented Regards, Martin Hello Martine, Can you elaborate more on how to use the mechanism you described? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Pure virtual functions in Python?
Thanks everyone for the answers. The dispatcher() is actually sits in C++ code. So my code receives an object that is an instance of the base class, it PyObject_GetAttrString(py_obj, 'funcname'). If the attribute exists I will call PyObject_CallMethod on it. If the base defines the method and it was empty, then my C++ code would still call the function. This is not optimal because I don't want to go from C++ to Python if the _derived_ class does not implement the cb. Now the base class should define it so that doc parsers properly describe the base class. The recipe suggested is not worth the trouble. Unfortunately I cannot use abc module since I use Python 2.5 -- http://mail.python.org/mailman/listinfo/python-list
Pure virtual functions in Python?
Hello How can I do something similar to pure virtual functions in C++ ? Let us consider this: class C1: # Pure virtual def cb(self, param1, param2): This is a callback @param param1: ... @param param2: ... raise NotImplementedError, Implement me # Implementation w/o a 'cb', thus 'cb' should not be used class C2(C1): def __init__(self): pass # Implementation w/ 'cb', thus 'cb' can be used class C3(C1): def __init__(self): pass def cb(self, param1, param2): print i am c3 cb # Dispatcher function that calls 'cb' only if 'cb' is implemented in child classes def dispatcher(c): if hasattr(c, 'cb'): c.cb(Hello, World) dispatcher(C2()) dispatcher(C3()) What I want is the ability to have the dispatcher() not to call 'cb' if it was not implemented in one of the child classes. Please advise. -- http://mail.python.org/mailman/listinfo/python-list
Python library for working with simple equations
Hello Is there is any Python library that allow such things: Given a string expression as: x + 5 + x * (y + 2), any library that can develop the equation for example. Or if we say factor with x then it renders the expression with x * ( rest of expression ). There could be a functionality where when x,y are given then the expression can be evaluated. If there are two expressions, they can be added and the symbols preserved. Does such a thing exist? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Help with lambda
Hello, I am still fairly new to Python. Can someone explain to me why there is a difference in f and g: def make_power(n): return lambda x: x ** n # Create a set of exponential functions f = [lambda x: x ** n for n in xrange(2, 5)] g = [make_power(n) for n in xrange(2, 5)] print f[0](3), f[1](3) print g[0](3), g[1](3) I expect to have f act same like g. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with lambda
Yes it should be listed somewhere, now I get it. Thanks Arnaud. -- Elias On Feb 18, 1:47 pm, Arnaud Delobelle arno...@googlemail.com wrote: lallous elias.bachaal...@gmail.com writes: Hello, I am still fairly new to Python. Can someone explain to me why there is a difference in f and g: def make_power(n): return lambda x: x ** n # Create a set of exponential functions f = [lambda x: x ** n for n in xrange(2, 5)] g = [make_power(n) for n in xrange(2, 5)] print f[0](3), f[1](3) print g[0](3), g[1](3) I expect to have f act same like g. Thanks It's a FAQ! Except I don't think it's in the official Python FAQ, but it ought to be. The reason (very quickly) is that each time you call make_power() you create a new name 'n' which is bound to a different value each time, whereas in f: [lambda x: x ** n for n in xrange(2, 5)] The 'n' is the same name for each of the lambda functions and so is bound to the same value, which by the end of the loop is 4. So each of the lambdas in the list f is the same as: lambdsa x; x**4 after the end of the list comprehension. The usual fix for this is to change f to: f = [lambda x, n=n: x ** n for n in xrange(2, 5)] I'll let you think why this works. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with lambda
On Feb 18, 1:56 pm, D'Arcy J.M. Cain da...@druid.net wrote: On Thu, 18 Feb 2010 04:28:00 -0800 (PST) lallous elias.bachaal...@gmail.com wrote: def make_power(n): return lambda x: x ** n Hint: type(make_power(2)) Did you expect that to return int? No, I expect to see a specialized function. # Create a set of exponential functions f = [lambda x: x ** n for n in xrange(2, 5)] g = [make_power(n) for n in xrange(2, 5)] The result of make_power(n) is a function that raises it's argument to the power of n. I don't know what you are trying to do. Maybe this? g = [make_power(n)(2) for n in xrange(2, 5)] or g = [make_power(2)(n) for n in xrange(2, 5)] What I am trying to do is generate different functions. If you're curious, I was playing with ctypes and wanted to see how it handles C-Python callbacks: CB_T = WINFUNCTYPE(c_int, c_int) many_cb_t = CFUNCTYPE(c_int, c_int, CB_T) many_cb = many_cb_t(addressof(c_void_p.in_dll(dll, many_cb))) #ANY_SIMPLER def make_power(n): return lambda x: x ** n cbs = [CB_T(make_power(n)) for n in xrange(0, 1000)] cbs.append(None) many_cb(3, *cbs) And the C code in a shared lib: int many_cb(int value, ...) { va_list va; va = va_start(va, value); cb_t cb; int s = 0; while ( (cb = va_arg(va, cb_t)) != NULL) { printf(calling %p, cb); int r = cb(value); s += r; printf(, r=%d\n, r); } va_end(va); return s; } Speaking of that, anyone has an idea how to make simpler the line with #ANY_SIMPLER? I try: many_cb = CB_T.in_dll(dll, many_cb) - but that seems to work with data items only. -- http://mail.python.org/mailman/listinfo/python-list
Re: Building a multiline string
@Ulrich: On Feb 4, 1:09 pm, Ulrich Eckhardt eckha...@satorlaser.com wrote: Just for the record: Neither of the below methods actually produce a multiline string. They only spread a string containing one line over multiple lines of source code. I meant: Note - Note: I don't want to use new lines I did not want a multi line string Thanks guys, method 3 seems to be good enough. -- http://mail.python.org/mailman/listinfo/python-list
Building a multiline string
Hello Maybe that's already documented, but it seems the parser accepts to build a long string w/o really using the first method: # Method1 x = line1 + \ # cannot use comments! line2+ \ line3 and instead using a list with one element like this: # Method2 x = [ line1 # can use comments line2 line3 ][0] Or: # Method3 x = ( line1 # can use comments line2 line3 ) (Not that I don't want new lines in the strings) Now should I be using method 2 or 3 in production code? -- Elias -- http://mail.python.org/mailman/listinfo/python-list
How to import a file by its full path using C api?
Hello PyObject* PyImport_ImportModule( const char *name) How to specify a full file path instead and a module name? Like PyImport_SomeFunction(const char *path_to_script, const char *name) Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: How to import a file by its full path using C api?
Looks like one way to do that is to use something like: s.sprintf( import imp\n imp.load_source('%s', r'%s'), modname, script_path); PyRun_SimpleString(s.c_str()); Unless someone has a better suggestion. Regards, Elias lallous lall...@lgwm.org wrote in message news:heir4g$oh...@aioe.org... Hello PyObject* PyImport_ImportModule( const char *name) How to specify a full file path instead and a module name? Like PyImport_SomeFunction(const char *path_to_script, const char *name) Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
C api question and determining PyObject type
Hello I have an a class defined as: class __object(object): pass Now, I call a C function that takes a PyObject* and checks its type: if (PyString_Check(obj)) ... if (PySequence_Check(obj)) Before doing the check, I print the passed object with PyObject_Str() and get: passed object: __main__.__object object at 0x040E4050 However, the C code returns true on the: if (PySequence_Check(obj)) Why? That is not a sequence? Please advise. -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: C api question and determining PyObject type
Actually, the object class is defined as: class __object(object): def __getitem__(self, idx): return getattr(self, idx) Anyway, now I check like this: bool PyIsSequenceType(PyObject *obj) { if (!PySequence_Check(obj)) return false; Py_ssize_t sz = PySequence_Size(obj); if (sz == -1 || PyErr_Occurred() != NULL) { PyErr_Clear(); return false; } return true; } I don't like it, any other suggestions? -- Elias lallous lall...@lgwm.org wrote in message news:hdr80a$vs...@aioe.org... Hello I have an a class defined as: class __object(object): pass Now, I call a C function that takes a PyObject* and checks its type: if (PyString_Check(obj)) ... if (PySequence_Check(obj)) Before doing the check, I print the passed object with PyObject_Str() and get: passed object: __main__.__object object at 0x040E4050 However, the C code returns true on the: if (PySequence_Check(obj)) Why? That is not a sequence? -- http://mail.python.org/mailman/listinfo/python-list
Adding methods to an object instance
Hello class __object(object): def __getitem__(self, idx): return getattr(self, idx) class __dobject(object): pass x = __object() setattr(x, 0, hello) print x[0] y = __dobject(a=1,b=2) setattr(y, 0, world) #print y[0] How can I, given an object of instance __dobject, add to that instance a __getitem__ method so that I can type: print y[0] Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Python C API and references
Hello, Everytime I use PyObject_SetAttrString(obj, attr_name, py_val) and I don't need the reference to py_val I should decrement the reference after this call? So for example: PyObject *py_val = PyInt_FromLong(5) PyObject_SetAttrString(py_obj, val, py_val); Py_DECREF(py_val) Right? If so, take sysmodule.c: if (PyObject_SetAttrString(builtins, _, Py_None) != 0) return NULL; Shouldn't they also call Py_DECREF(Py_None) ? Same logic applies to PyDict_SetItemString() and the reference should be decrement after setting the item (ofcourse if the value is not needed). -- Elias -- http://mail.python.org/mailman/listinfo/python-list
C api and checking for integers
Hello, I am a little confused on how to check if a python variable is an integer or not. Sometimes PyInt_Check() fails and PyLong_Check() succeeds. How to properly check for integer values? OTOH, I tried PyNumber_Check() and: (1) The doc says: Returns 1 if the object o provides numeric protocols, and false otherwise. This function always succeeds. What do they mean: always succeeds ? (2) It seems PyNumber_check(py_val) returns true when passed an instance! Please advise. -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C API and references
Hello Daniel, Thanks for the reply. Everytime I use PyObject_SetAttrString(obj, attr_name, py_val) and I don't need the reference to py_val I should decrement the reference after this call? It really depends on /how/ the object is created. If the method used to create *py_val* increases the reference count on the object and another function any other function is used to increase the reference count, you should use Py_DECREF or Py_XDECREF. So for example: PyObject *py_val = PyInt_FromLong(5) PyObject_SetAttrString(py_obj, val, py_val); Py_DECREF(py_val) Right? In this case is right. *PyInt_FromLong()* returns a new reference: 'Return value: New reference.', which is increasing the reference count and PyObject_SetAttrString does it twice, then you have a reference count of two and you need to decrement the initial reference counting of the object, or you will have a memory leak. [quote] int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v. int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) Set the value of the attribute named attr_name, for object o, to the value v. Returns -1 on failure. This is the equivalent of the Python statement o.attr_name = v. [/quote] Looking at the documentation, should I have understood that the passed value reference will be incremented and that I should decrement it if I don't need it? Or I should have understood just because of the fact that whenever we have x = b (be it from the C api in a form of SetAttr()) then we should know that b's reference will be incremented. ? Because, before this discussion I did not know I should decrease the reference after SetAttr() If so, take sysmodule.c: if (PyObject_SetAttrString(builtins, _, Py_None) != 0) return NULL; Shouldn't they also call Py_DECREF(Py_None) ? No, I think that Py_None do not needs to decrease the reference count... None is an object like other objects. I think its reference must be taken into consideration too, for instance why there is the convenience macro: Py_RETURN_NONE ? -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Python C api: create a new object class
Hello I have 3 questions, hope someone can help: 1) How can I create an instance class in Python, currently I do: class empty: pass Then anytime I want that class (which I treat like a dictionary): o = empty() o.myattr = 1 etc Is there is a one line syntax to instantiate an instance? Any other ways than this: o = new.classobj('object', (), {}) 2) How can I, similarly, create an object o in C api: PyObject *o = what_to_call() PyObject_SetAttrString(o, attrname, py_val) ... One way I found was first calling PyClass_New() (to create an empty class) and then passing the return value to PyInstance_NewRaw to get a new instance of that empty class. Can I achieve the same otherwise? 3) Given a PyObject* is there is a way to tell if one can call PyObject_SetAttrString() on that object w/o getting an error? For example, before calling a PyObject* one can see if it is callable, but can I test if an object supports setattr? (from C api) Thank you, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: C api and exception handling
Thanks for your help Carl as usual. Will go with the getattr override method which is cleaner as you explained. Regards, Elias Carl Banks pavlovevide...@gmail.com wrote in message news:f02c069c-e536-4c6b-b114-2215aa611...@k17g2000yqh.googlegroups.com... On Nov 2, 7:16 am, lallous lall...@lgwm.org wrote: Hello, Is there is a way, using the Python C api, to install an exception handler that: - will be triggered when an exception occurs - analyze the reason of the exception - correct the situation and try again (something like exception handling on windows where the exception handler can retrieve the registers context-faulting instruction-fix situation if needed-restart execution from the same point) Python has no concept of retrying, at either the Python or C API level. You might be able to do something Evil in C to get this effect but I don't recommend it, it'll be fundamentally averse to how Python works and future versions are likely to break it. Since I will be asked: what are you trying to achieve?, this is what I want: func_call(hello) - no exceptions, good code: function is defined and called properly SomeUndefinedFunction(x, y) - undefined function call will trigger an exception. I want my python/C exception handler to inspect the reason of the exception, if it was a call to an undefined function call then redirect the execution to a certain method, say: ExecuteByName(SomeUndefinedFunction, x, y) I know if I create a small class with getattr hooked, what I want can be achieved. I'd do it that way. There is ordinarily no way to hook into a plain function call like SomeUndefinedFunction() in Python; if you go around hacking up the interpreter to do that users will be highly confused and surprised. OTOH, hooking into attributes is pretty well-known. When a person sees attribute notation they know there's an opportunity to do weird stuff. When a strange function is called, they will be like, oh, someone overrode __getattr__. But can it be done otherwise (without using a class and instead relying on exception handlers and correcting the exception)? Just forget about exception handling. If you REALLY insist on doing this, and I highly recommend against it, the best chance you have is to try to hook into the importing process and load a module that uses a custom dictionary object. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Unloading a module
Hello Group, If a reference to an imported module reaches zero will Python cleanup everything related to that module and unload the compiled code, etc, etc...? For example: import sys m = [__import__(str(x)) for x in xrange(1,4)] del sys.modules['1'] del m[0] print m Is module['1'] really unloaded or just it is not reachable but still loaded? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: .pyc from stdin?
Hello Shay, Shay Telfer shaypyt...@earthyself.com wrote in message news:mailman.1021.1254988413.2807.python-l...@python.org... Hi... It seems that python will accept a .py file piped from stdin, but not a .pyc file (and there don't seem to be any flags to allow this). Am I missing something? Eg cat blah.py | python works, but cat blah.pyc | python Try for example: python -c import blah doesn't. (If you're wondering why anyone would do this it's because I'm actually intending to use curl rather than cat :) The former works because the Python interpreter understands python syntax, and when you (in the latter case) provide the interpreter a pyc file it surely won't work because it does not understand those compiled bytes just like that -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: .pyc from stdin?
Hello Shay, Shay Telfer shaypyt...@earthyself.com wrote in message news:mailman.1021.1254988413.2807.python-l...@python.org... Hi... It seems that python will accept a .py file piped from stdin, but not a .pyc file (and there don't seem to be any flags to allow this). Am I missing something? Eg cat blah.py | python works, but cat blah.pyc | python Try for example: python -c import blah doesn't. (If you're wondering why anyone would do this it's because I'm actually intending to use curl rather than cat :) The former works because the Python interpreter understands python syntax, and when you (in the latter case) provide the interpreter a pyc file it surely won't work because it does not understand those compiled bytes just like that -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: .pyc from stdin?
Hello Shay, Shay Telfer shaypyt...@earthyself.com wrote in message news:mailman.1021.1254988413.2807.python-l...@python.org... Hi... It seems that python will accept a .py file piped from stdin, but not a .pyc file (and there don't seem to be any flags to allow this). Am I missing something? Eg cat blah.py | python works, but cat blah.pyc | python Try for example: python -c import blah doesn't. (If you're wondering why anyone would do this it's because I'm actually intending to use curl rather than cat :) The former works because the Python interpreter understands python syntax, and when you (in the latter case) provide the interpreter a pyc file it surely won't work because it does not understand those compiled bytes just like that -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: data matrix python
Hello Try re-asking your question in a more general way so that users w/o background information (about those classes and modules you're using) can help you with your problem. -- Elias bbarb...@inescporto.pt wrote in message news:mailman.968.1254922056.2807.python-l...@python.org... Good morning all! I am trying to build a data matrix, but I am not able either to write to file with a proper structure nor to get the data from the matrix. I want to sort some music by similarity content, and I just have the indexes of the playlist like this: dm = numpy.array(songs) [0 4 2 1 3] [1 2 0 4 3] [2 1 0 4 3] [3 2 1 0 4] [4 0 1 2 3] Now, I want to keep the same format but with the names of the songs, something like this: Sort_dm.append(songlist(dm)) ['100.mp3\n' '10008.mp3' '10005.mp3\n' '10001.mp3\n' '10006.mp3\n' '10001.mp3\n' '10005.mp3\n' '100.mp3\n' '10008.mp3' '10006.mp3\n' '10005.mp3\n' '10001.mp3\n' '100.mp3\n' '10008.mp3' '10006.mp3\n' '10006.mp3\n' '10005.mp3\n' '10001.mp3\n' '100.mp3\n' '10008.mp3' '10008.mp3' '100.mp3\n' '10001.mp3\n' '10005.mp3\n' '10006.mp3\n'] But there is no way either I can access to the data... because there are strings, or save them in matrix format! I could not find anything in the documentation about this! any hint would be very welcome! thank you for your time! Best regards, Bea Mora This message was sent using IMP, the Internet Messaging Program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing a C pointer in a Python class instance
Carl Banks pavlovevide...@gmail.com wrote in message news:d50bba1e-b272-4e39-8a58-377531278...@z4g2000prh.googlegroups.com... On Sep 30, 5:24 am, lallous lall...@lgwm.org wrote: Hello After using the PyCObject, I cannot pickle the class anymore. Any simple solution to this problem? (or resorting to __reduce__ is the only solution?) You can't pickle a CObject, you'd have to create a custom type (one that implements one of the pickling methods) for that. Or arrange for whatever object contains the CObject to pack and unpack it manually. Out of curiosity, what kind of data you storing in this CObject? Maybe we can help you choose a better way to handle it at the C level. I am wrapping a C++ pointer with the python object. That way I can tell with which C++ object a given python class instance is associated. The thing is when developing, I need to pickle but I don't need the C++ pointer, so I solved the problem with conditional compilation: - testing: pickle allowed and This is stored in the py object - production code: no need to pickle and this and pyobject are bound Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and lost files
Hello Timothy, Timothy W. Grove tim_gr...@sil.org wrote in message news:mailman.726.1254378947.2807.python-l...@python.org... Recently I purchased some software to recover some files which I had lost. (A python project, incidentally! Yes, I should have kept better backups!) They were nowhere to found in the file system, nor in the recycle bin, but this software was able to locate them and restore them. I was just wondering if there was a way using python to view and recover files from the hard drive which would otherwise remain lost forever? To recover lost or deleted files you need a specialized tools (such as data recovery programs). I don't see a way to recover files using python itself but perhaps using a data recovery program written in Python. -- Elias -- http://mail.python.org/mailman/listinfo/python-list
emptying a list
Hello What is faster when clearing a list? del L[:] or L = [] -- Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial directory search question
chad cdal...@gmail.com wrote in message news:4e260ef3-8b0e-4613-a4f8-1c267e875...@u16g2000pru.googlegroups.com... On Sep 29, 7:20 pm, Tim Chase python.l...@tim.thechases.com wrote: What's the sanest way to print out all the files in the directory that start with the underscore? Ie, I just want to list _1, _2, _3, _4. I'd use a string's join() method to combine the results of a list-comprehension or generator that filtered the output of os.listdir() based on the startswith() method of the strings. Left intentionally oblique and code-free because this sounds a bit like a home-work problem. If you're a python coder, that should make pretty decent sense and be a one-liner to implement. -tkc Okay, sorry for the delay to the response. I got side tracked trying to stalk, I mean talk to the 59 year old neighbor girl. Anyways, I couldn't get it to one in one line. Here is what I did... % more rec.py #!/usr/local/bin/python import os import time for filename in os.listdir(/usr/bbs/confs/september): #stat = os.stat(filename) if filename.startswith(_): print filename L = [filename for filename in os.listdir(/usr/bbs/confs/september) if filename.startswith(_)] Now you have a list with the desired filtered names. ./rec.py _1 _2 _3 _4 _5 _6 _7 _8 It correctly prints out all the files in the directory that start with an underscore. -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing a C pointer in a Python class instance
Thanks everyone. Finally, I used Falcolas suggestion and took into consideration sturlamolden's comments. Regards, Elias lallous lall...@lgwm.org wrote in message news:h9sgcn$iv...@aioe.org... Hello From my C extension module I want to store a C pointer in a given PyObject. The only way I figure how to do it is to use Py_BuildValues and store the poiner casted to Py_ssize_t, thus: Py_BuildValues(n, (Py_ssize_t)my_ptr) Can it be done differently? Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Python book
Hello Can anyone suggest a good book Python book for advancing from beginner level? (I started with Learning Python 3rd ed) Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: Storing a C pointer in a Python class instance
Hello After using the PyCObject, I cannot pickle the class anymore. Any simple solution to this problem? (or resorting to __reduce__ is the only solution?) Thanks, Elias Falcolas garri...@gmail.com wrote in message news:9d3790aa-f7d9-4bb5-a81f-5428b2d60...@v25g2000yqk.googlegroups.com... On Sep 29, 2:27 am, lallous lall...@lgwm.org wrote: Hello From my C extension module I want to store a C pointer in a given PyObject. The only way I figure how to do it is to use Py_BuildValues and store the poiner casted to Py_ssize_t, thus: Py_BuildValues(n, (Py_ssize_t)my_ptr) Can it be done differently? Regards, Elias You can use a PyCObject_FromVoidPtr http://docs.python.org/c-api/cobject.html PyArg_ParseTuple(args, O, pyVoidPointer); castPointer = (type *) PyCObject_AsVoidPtr(pyVoidPointer); return PyCObject_FromVoidPtr((void *) castPointer, NULL); -- http://mail.python.org/mailman/listinfo/python-list
Storing a C pointer in a Python class instance
Hello From my C extension module I want to store a C pointer in a given PyObject. The only way I figure how to do it is to use Py_BuildValues and store the poiner casted to Py_ssize_t, thus: Py_BuildValues(n, (Py_ssize_t)my_ptr) Can it be done differently? Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: create a class instance from C API?
Thanks Carl, that does it! -- Elias Carl Banks pavlovevide...@gmail.com wrote in message news:48ce343a-36ef-406f-bea3-851444785...@b18g2000vbl.googlegroups.com... On Sep 28, 8:19 am, lallous lall...@lgwm.org wrote: Hello How to programmatically create a class instance of a given Python class? For example to create a new list there is the PyObject *PyList_New() but suppose the user already defined a class: class X: pass How to create an instance of it from my C extension module? Same way you'd do it in Python: call it. Use PyObject_Call or any of it's convenient variants. Example (leaving off all the error-checking stuff): mod = PyImport_ImportModule(modname); cls = PyObject_GetAttrStr(mod,classname); inst = PyObject_CallFunctionObjArgs(cls,NULL); Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
print object attributes recursively
Hello Suppose I have this code: class X: def __init__(self, n): self.L = [x for x in xrange(0, n+1)] class Y: def __init__(self, n): self.M = [X(x) for x in xrange(0, n)] t = Y(5) How can I easily print t and all its nested attributes? (Something like PHP's print_r()) Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
create a class instance from C API?
Hello How to programmatically create a class instance of a given Python class? For example to create a new list there is the PyObject *PyList_New() but suppose the user already defined a class: class X: pass How to create an instance of it from my C extension module? Regards, Elias -- http://mail.python.org/mailman/listinfo/python-list
Re: match braces?
Hello, Thank you all for your replies. A simple suggestion as Chris' actually might help. I am used to two spaces indentation since years, and apparently two spaces won't make it clear if no visuals were present (braces, or begin/end, ...) Though it is not comfortable to change a style, I will play with 8 spaces indentation, it would naturally make it clearer ;) -- Elias On Sep 3, 11:43 am, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 3, 2009 at 2:38 AM, lallouslall...@lgwm.org wrote: Hello In C/C++ you use the braces where as in Python you use the indentation levels. Most editors offer a Ctrl+[ to match the braces so that you can easily identify the scopes (more correctly statements blocks). I am finding it difficult to see blocks Erm, how does the indentation itself not make it plainly and explicitly clear? Perhaps you need to set your tabstops wider? Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
match braces?
Hello In C/C++ you use the braces where as in Python you use the indentation levels. Most editors offer a Ctrl+[ to match the braces so that you can easily identify the scopes (more correctly statements blocks). I am finding it difficult to see blocks and/or jump from end to start with some IDE hotkeys, when coding in Python. Any advise? Thanks, Elias -- http://mail.python.org/mailman/listinfo/python-list
copy object?
Hello I am new to python and have some questions. How to copy objects using another method than this: class op: def __init__(self, op): for x in dir(op): if x[:2] == __: continue setattr(self, x, getattr(op, x)) o = op(src) I tried to copy with o = copy.copy(src) but as soon as src is gone, o's attributes are not correct, and I cannot use copy.deepcopy () because of this error: TypeError: object.__new__(SwigPyObject) is not safe, use SwigPyObject.__new__() Can the previous for loop be simplified and replaced with a map() and a lambda function? Thanks. -- http://mail.python.org/mailman/listinfo/python-list