Re: matrix algebra
On Sep 22, 11:32 am, "Tim Leslie" <[EMAIL PROTECTED]> wrote: > There is no need for a wrapper. Both numarray and Numeric have been > deprecated in favour of numpy, so numpy is the only one you need to > use. Numpy should have all the tools you need. If you find something > missing, there's a good chance it's included in scipy (which is built > on top of numpy). For full details seewww.scipy.org. I don't agree. I am myself a casual user of numpy without sophisticated needs. Numpy seems to be the only player in town and unfortunateely, though powerful, its syntax is not intuitive or easy to remember. I therefore welcome any attempt to simplify the api for a specific group of non-power users. Alain -- http://mail.python.org/mailman/listinfo/python-list
PyRun_SimpleFile() crashes
my code: main.cpp #include int main(int argc, char **argv) { Py_Initialize(); FILE *file_1 = fopen("a2l_reader.py","r+"); PyRun_SimpleFile(file_1,"a2l_reader.py"); Py_Finalize(); } compile under windows using MinGW: g++ main.cpp libpython25.a -o a no error was found. But when I run a.exe the program just crashes. What should I do? -- http://mail.python.org/mailman/listinfo/python-list
Re: python freeze help
Mike Driscoll wrote: On Sep 23, 5:01 am, Gabriel Rossetti <[EMAIL PROTECTED]> wrote: Hello everyone, I'm trying to use python's freeze utility but I'm running into problems. I called it like this : python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py ~/Documents/Code/Python/src/jester/service.py -m jester then I did : make then I tried to run it : ./service and I get this : [EMAIL PROTECTED]:~/tmp/freeze$ ./service Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in from apport.report import Report File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in from problem_report import ProblemReport File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in from email.MIMEMultipart import MIMEMultipart File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ __import__(self.__name__) ImportError: No module named multipart I've gotten this error from py2exe before. I'm not sure how freeze works, but in py2exe I had to make sure the email package wasn't being accidentally excluded and explicitly included. I tried that (-m email), didn't work, I added -E and I get this : There are some missing modules: ['Carbon.File', 'Carbon.Folder', 'Carbon.Folders', 'EasyDialogs', 'FCNTL', 'MacOS', 'SOCKS', '_dummy_threading', '_emx_link', '_md5', '_sha', '_sha256', '_sha512', '_subprocess', '_winreg', '_xmlplus', 'ce', 'email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'gestalt', 'ic', 'java.lang', 'mac', 'msvcrt', 'nt', 'org.python.core', 'os.path', 'os2', 'pywintypes', 'riscos', 'riscosenviron', 'riscospath', 'rourl2path', 'sgi', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] so I tried to see if it existed : >>> import email >>> email.MIMEMultipart >>> maybe this is the problem, an email.MIMEMultipart object isn't what is returned but instead an email.LazyImporter object is, so freeze isn't happy... any ideas on how to solve this? Original exception was: Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Does anyone have any ideas as of why I get this? Thank you, Gabriel I don't know what this second error is... Mike -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On Sep 24, 8:10 am, Christian Heimes <[EMAIL PROTECTED]> wrote: > Side note: > > sys.exit() is just another way to write raise SystemExit. The function > is defined as: > As can be seen if you were ever silly enough to call sys.exit() in IDLE. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On Tue, 23 Sep 2008 13:25:26 -0700, Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose Python > functions, some of which do I/O. Therefore it is possible for many of > the library functions to raise IOError Exceptions. The question is: > should the library function be able to just dump to sys.exit() with a > message about the error (like "couldn't open this file"), or should the > exception propagate to the calling program which handles the issue? > > Thanks in advance for anyone who can either answer my question or point > me to where this question has already been answered. Presumably somebody has suggested that calling sys.exit() was a good option. I'm curious to what possible reason they could give for such a poor choice. Hint: if a library function can't open a file, the application should be given the opportunity to open a different file. Or do something completely different instead. Whatever. That's not up to the library to decide, not even if the library is in such a broken state that it can't continue. Why not? Because the application might deal with that by unloading the library and continuing regardless. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualize class inheritance hierarchy
On Sep 23, 4:58 pm, Christian Heimes <[EMAIL PROTECTED]> wrote: > Rob Kirkpatrick wrote: > > I'm assuming this has been discussed before, but I'm lacking any > > Google keywords that bring up the appropriate discussion. > > You are looking for "mro" aka method resolution order. The inspect > module contains several helper functions to inspect a class hierarchy. > > The following interactive session should give you an impression how to > use the functions: > > >>> import inspect > >>> import pprint > >>> from sqlalchemy.types import DateTime > > >>> inspect.getmro(DateTime) > (, 'sqlalchemy.types.TypeEngine'>, , > > >>> DateTime.__bases__ > (,) > > >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) > [(, ()), > [(, (,)), >[(, > (,)), > [(, > (,)) > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] > [, 'sqlalchemy.types.TypeEngine'>, , > ] > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] > [, ] Oh, yeah. That's the stuff! -- http://mail.python.org/mailman/listinfo/python-list
python 3.x third party modules
Hi all, I would like to look at third party modules which are python 3.0 ready. could some one point me to such a resource ? If its not available, it would be useful to host a page regarding this on python.org ? any comments ? KM -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names for > integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, so > that help(Constants.FOO) will print some arbitrary string. Sort of a > very limited implementation of PEP 224. The only solution that I can see > is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Others have suggested solutions, which may be better, but for completeness consider using properties: def make_const(value, doc=''): def getter(self): return value return property(getter, None, None, doc) class Foo(object): x = make_const(1.234, 'a special number') The only gotcha is that while help(Foo.x) works, help(Foo().x) does not. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use python object in C++
On 9月24日, 午後1:15, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Sep 23, 11:06 pm, "Aaron \"Castironpi\" Brady" > > > > <[EMAIL PROTECTED]> wrote: > > On Sep 23, 9:30 pm, [EMAIL PROTECTED] wrote: > > > > If the PyObject is a PyList, and all list items are strings, > > > say a=['aaa','bbb','ccc'] > > > > How can I have a > > > myArray[0] = "aaa" > > > myArray[1] = "bbb" > > > myArray[2] = "ccc" > > > in C++? > > > > Do I have to > > > use PyModule_GetDict() to get the dict first? > > > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? If it's > > > > impossible with Py_Main, can you use one of the other entry points? > > > > > If you've never manipulated PyObject* objects in C, they can be > > > > hairy. Even if you know 'a' is a sequence, its contents are still all > > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > > functions. > > > This one writes '[aaa, bbb, ccc]' to the console in two different > > ways. > > > #include > > > int main() { > > PyObject *list, *listrepr; > > Py_Initialize(); > > > /* first */ > > list= PyList_New( 3 ); > > PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > > PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > > PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > /* second */ > > list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > Py_Finalize(); > > return 0; > > > } > > > Did you want to execute some Python code, and examine variables it > > creates? > > Here's a third way: > > PyObject *list, *listrepr, *dict, *result, *name; > /* third */ > dict= PyDict_New( ); > result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", > Py_file_input, dict, NULL ); > name= PyString_FromString( "myarray" ); > list= PyDict_GetItem( dict, name ); > listrepr= PyObject_Repr( list ); > printf( "%s\n", PyString_AsString( listrepr ) ); > > Py_DECREF( dict ); > Py_DECREF( result ); > Py_DECREF( name ); > Py_DECREF( listrepr ); > Py_DECREF( list ); > > PyRun_String runs a namespace, 'dict', which holds the variables. Thanks! it helps. I know how to read from python now. main_module = PyImport_AddModule("__main__"); global_dict = PyModule_GetDict(main_module); pyObject = PyDict_GetItem(global_dict,key); it will require lots of type checking, but it's fine to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: >> > This seems to break the rule that if A is equal to B and B is equal >> > to C then A is equal to C. >> >> I don't see why transitivity should apply to Python objects in general. > > Well, for numbers it surely would be a nice touch, wouldn't it. May be > the reason for Decimal to accept float arguments is that irrational > numbers or very long rational numbers cannot be converted to a Decimal > without rounding error, and Decimal doesn't want any part of it. Seems > pointless to me, though. Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to be `True` or `False` given that 0.1 actually is In [98]: '%.50f' % 0.1 Out[98]: '0.1555111512312578270211815834045410' ? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use python object in C++
On Sep 23, 11:06 pm, "Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > On Sep 23, 9:30 pm, [EMAIL PROTECTED] wrote: > > > > > If the PyObject is a PyList, and all list items are strings, > > say a=['aaa','bbb','ccc'] > > > How can I have a > > myArray[0] = "aaa" > > myArray[1] = "bbb" > > myArray[2] = "ccc" > > in C++? > > > Do I have to > > use PyModule_GetDict() to get the dict first? > > what about the next? > > > > What do you know about the contents of 'argc' and 'argv'? If it's > > > impossible with Py_Main, can you use one of the other entry points? > > > > If you've never manipulated PyObject* objects in C, they can be > > > hairy. Even if you know 'a' is a sequence, its contents are still all > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different > ways. > > #include > > int main() { > PyObject *list, *listrepr; > Py_Initialize(); > > /* first */ > list= PyList_New( 3 ); > PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > listrepr= PyObject_Repr( list ); > printf( "%s\n", PyString_AsString( listrepr ) ); > > Py_DECREF( listrepr ); > Py_DECREF( list ); > > /* second */ > list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > listrepr= PyObject_Repr( list ); > printf( "%s\n", PyString_AsString( listrepr ) ); > > Py_DECREF( listrepr ); > Py_DECREF( list ); > > Py_Finalize(); > return 0; > > } > > Did you want to execute some Python code, and examine variables it > creates? Here's a third way: PyObject *list, *listrepr, *dict, *result, *name; /* third */ dict= PyDict_New( ); result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", Py_file_input, dict, NULL ); name= PyString_FromString( "myarray" ); list= PyDict_GetItem( dict, name ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( dict ); Py_DECREF( result ); Py_DECREF( name ); Py_DECREF( listrepr ); Py_DECREF( list ); PyRun_String runs a namespace, 'dict', which holds the variables. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use python object in C++
On Sep 23, 9:30 pm, [EMAIL PROTECTED] wrote: > If the PyObject is a PyList, and all list items are strings, > say a=['aaa','bbb','ccc'] > > How can I have a > myArray[0] = "aaa" > myArray[1] = "bbb" > myArray[2] = "ccc" > in C++? > > Do I have to > use PyModule_GetDict() to get the dict first? > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? If it's > > impossible with Py_Main, can you use one of the other entry points? > > > If you've never manipulated PyObject* objects in C, they can be > > hairy. Even if you know 'a' is a sequence, its contents are still all > > PyObject*s, which you can access via PyList_... and PySequence_ > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different ways. #include int main() { PyObject *list, *listrepr; Py_Initialize(); /* first */ list= PyList_New( 3 ); PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); /* second */ list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); Py_Finalize(); return 0; } Did you want to execute some Python code, and examine variables it creates? -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
Terry Reedy wrote: [EMAIL PROTECTED] wrote: ...If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? ... How about file.tell == 0? or have I misunderstood the requirement? OI thought roughly the same thing when I saw this, how about if not file.tell(): --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
"Aaron \"Castironpi\" Brady" <[EMAIL PROTECTED]> wrote: > You're out of options. You have to express it somehow. How about: Assignith z the value of x if the value of b is such that it is true, else assignith it the value of y. Assignith z not the value of w, nor the value of v, lest you raise NameError upon thy stack trace. -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
On 23 set, 22:50, Neal Becker <[EMAIL PROTECTED]> wrote: > I find I'm often tripped up by: > > x = Y (lots of constructor arguments) if something ... > > on first glance, I don't notice the if. Nobody does. This peculiar syntax has much better usage in short expressions. dothis if this else dothat -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use python object in C++
If the PyObject is a PyList, and all list items are strings, say a=['aaa','bbb','ccc'] How can I have a myArray[0] = "aaa" myArray[1] = "bbb" myArray[2] = "ccc" in C++? Do I have to use PyModule_GetDict() to get the dict first? what about the next? > > What do you know about the contents of 'argc' and 'argv'? If it's > impossible with Py_Main, can you use one of the other entry points? > > If you've never manipulated PyObject* objects in C, they can be > hairy. Even if you know 'a' is a sequence, its contents are still all > PyObject*s, which you can access via PyList_... and PySequence_ > functions. -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
On Sep 23, 8:50 pm, Neal Becker <[EMAIL PROTECTED]> wrote: > Aaron "Castironpi" Brady wrote: > > On Sep 23, 6:52 pm, Neal Becker <[EMAIL PROTECTED]> wrote: > >> In hindsight, I am disappointed with the choice of conditional syntax. I > >> know it's too late to change. The problem is > > >> y = some thing or other if x else something_else > > >> When scanning this my eye tends to see the first phrase and only later > >> notice that it's conditioned on x (or maybe not notice at all!). > >> Particularly if 'some thing or other' is long or complicated. > > > You're talking strictly about readability, which among other things is > > in the eye of the beholder, of course. Temporary variables can clean > > up some code, even if choosing names can be a hassle and it's more > > things to keep track of. Long lines and extra variables form a trade- > > off. You are writing a line with a conditional expression the value > > of which depends on something. What does it depend on, what is its > > value if that's true, and what is it if it's false? '...if...else...' > > only takes 6 characters... maybe you want more! > > > If you're looking for a strictly syntactic construct, you can always > > "fire blanks", or tracers, if the analogy's more accurate. > > > z= conditionally( x ) if b else y > > > This could serve as a gentle reminder, even where 'conditionally' > > returns its argument, i.e. is the identity function. You can always > > roll your own ternary with extra parameters too: > > > z= condition( b, x, y ) > > > Just don't confuse it with threading.Condition. > > > Otherwise, you're stuck with old syntax markers, and unless you > > wanted: > > > z= if b then x else y > > > You're out of options. You have to express it somehow. Did you want > > the condition first? Was there an alternative proposal you > > preferred? IINM if I'm not mistaken, > > > z= b and x or y > > > works just the same so long as x evaluates to True, as it will be > > tested. > > > Feel free to write your own from scratch, and we'll see how close > > Python can come to resembling it. > > > I suppose you can compare it to someone who stops listening before the > > word 'if', and completely misunderstands your statement. "Feed the > > dog if he's standing near the food dish" != "Feed the dog", which can > > of course lead to errors of both omission and commission (doing too > > little -or- too much). There's no way to fix that in a guaranteed > > way, except to say, "listen to the whole statement". > > > And strictly sarcastically, what did you want to do with reading the > > program? Why were you reading it? > > I find I'm often tripped up by: > > x = Y (lots of constructor arguments) if something ... > > on first glance, I don't notice the if. > > Why am I reading this? Umm, because I wrote it. Put it somewhere you'll notice! -- http://mail.python.org/mailman/listinfo/python-list
Twisted vs. CherryPy vs. ??? for light-weight web servers
Is there any consensus on what the best lightweight web-server is? Or rather would Twisted be a better choice to choose as a framework that allows me to serve html or xml data for light webservices. Or is CherryPy just as good? -- | _ | * | _ | | _ | _ | * | | * | * | * | -- http://mail.python.org/mailman/listinfo/python-list
Re: how to keep a window above all other OS windows?
On Sep 23, 3:34 pm, dmitrey <[EMAIL PROTECTED]> wrote: > On Sep 23, 11:21 pm, dmitrey <[EMAIL PROTECTED]> wrote: > > > Hi all, > > how to keep a Tkinter window above all other OS windows (i.e. > > including those ones from other programs)? > > > Thank you in advance, > > Dmitrey > > I have put [Tkinter] into topic of my message but somehow it has been > removed. > D. If you can get the handle of the window from the Tk framework, use the os call in 'ctypes'. Windows' call is ShowWindow( handle, HWND_TOPMOST ) I think. -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
Aaron "Castironpi" Brady wrote: > On Sep 23, 6:52 pm, Neal Becker <[EMAIL PROTECTED]> wrote: >> In hindsight, I am disappointed with the choice of conditional syntax. I >> know it's too late to change. The problem is >> >> y = some thing or other if x else something_else >> >> When scanning this my eye tends to see the first phrase and only later >> notice that it's conditioned on x (or maybe not notice at all!). >> Particularly if 'some thing or other' is long or complicated. > > You're talking strictly about readability, which among other things is > in the eye of the beholder, of course. Temporary variables can clean > up some code, even if choosing names can be a hassle and it's more > things to keep track of. Long lines and extra variables form a trade- > off. You are writing a line with a conditional expression the value > of which depends on something. What does it depend on, what is its > value if that's true, and what is it if it's false? '...if...else...' > only takes 6 characters... maybe you want more! > > If you're looking for a strictly syntactic construct, you can always > "fire blanks", or tracers, if the analogy's more accurate. > > z= conditionally( x ) if b else y > > This could serve as a gentle reminder, even where 'conditionally' > returns its argument, i.e. is the identity function. You can always > roll your own ternary with extra parameters too: > > z= condition( b, x, y ) > > Just don't confuse it with threading.Condition. > > Otherwise, you're stuck with old syntax markers, and unless you > wanted: > > z= if b then x else y > > You're out of options. You have to express it somehow. Did you want > the condition first? Was there an alternative proposal you > preferred? IINM if I'm not mistaken, > > z= b and x or y > > works just the same so long as x evaluates to True, as it will be > tested. > > Feel free to write your own from scratch, and we'll see how close > Python can come to resembling it. > > I suppose you can compare it to someone who stops listening before the > word 'if', and completely misunderstands your statement. "Feed the > dog if he's standing near the food dish" != "Feed the dog", which can > of course lead to errors of both omission and commission (doing too > little -or- too much). There's no way to fix that in a guaranteed > way, except to say, "listen to the whole statement". > > And strictly sarcastically, what did you want to do with reading the > program? Why were you reading it? I find I'm often tripped up by: x = Y (lots of constructor arguments) if something ... on first glance, I don't notice the if. Why am I reading this? Umm, because I wrote it. -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
On 23 set, 20:52, Neal Becker <[EMAIL PROTECTED]> wrote: > In hindsight, I am disappointed with the choice of conditional syntax. I > know it's too late to change. The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice > that it's conditioned on x (or maybe not notice at all!). Particularly if > 'some thing or other' is long or complicated. Yes, infix syntax sucks. No ambiguities in prefixed Lisp: (if x (or something other) something_else) Anyway, pretty amusing seeing Guido nodding to Larry... ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use python object in C++
On Sep 23, 7:50 pm, [EMAIL PROTECTED] wrote: > for example I have the following code: > > #include > > void exec_pythoncode( int arg, char**argv ) > { > Py_Initialize(); > Py_Main(argc,argv); > Py_Finalize(); > > } > > What I would like to know is how can I get the variables I want > after Py_Main(argc,argv) > > say I have a=[1,2,'Hello World',0.1234] in the python space, > I would like to have it as a struct in C++. > > Any sample code? > Thanks in advance! What do you know about the contents of 'argc' and 'argv'? If it's impossible with Py_Main, can you use one of the other entry points? If you've never manipulated PyObject* objects in C, they can be hairy. Even if you know 'a' is a sequence, its contents are still all PyObject*s, which you can access via PyList_... and PySequence_ functions. -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
On Sep 23, 6:52 pm, Neal Becker <[EMAIL PROTECTED]> wrote: > In hindsight, I am disappointed with the choice of conditional syntax. I > know it's too late to change. The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice > that it's conditioned on x (or maybe not notice at all!). Particularly if > 'some thing or other' is long or complicated. You're talking strictly about readability, which among other things is in the eye of the beholder, of course. Temporary variables can clean up some code, even if choosing names can be a hassle and it's more things to keep track of. Long lines and extra variables form a trade- off. You are writing a line with a conditional expression the value of which depends on something. What does it depend on, what is its value if that's true, and what is it if it's false? '...if...else...' only takes 6 characters... maybe you want more! If you're looking for a strictly syntactic construct, you can always "fire blanks", or tracers, if the analogy's more accurate. z= conditionally( x ) if b else y This could serve as a gentle reminder, even where 'conditionally' returns its argument, i.e. is the identity function. You can always roll your own ternary with extra parameters too: z= condition( b, x, y ) Just don't confuse it with threading.Condition. Otherwise, you're stuck with old syntax markers, and unless you wanted: z= if b then x else y You're out of options. You have to express it somehow. Did you want the condition first? Was there an alternative proposal you preferred? IINM if I'm not mistaken, z= b and x or y works just the same so long as x evaluates to True, as it will be tested. Feel free to write your own from scratch, and we'll see how close Python can come to resembling it. I suppose you can compare it to someone who stops listening before the word 'if', and completely misunderstands your statement. "Feed the dog if he's standing near the food dish" != "Feed the dog", which can of course lead to errors of both omission and commission (doing too little -or- too much). There's no way to fix that in a guaranteed way, except to say, "listen to the whole statement". And strictly sarcastically, what did you want to do with reading the program? Why were you reading it? -- http://mail.python.org/mailman/listinfo/python-list
Property Function
Hi, In python code, class A: get(self): do something set(self): do something g=property(get,set) what is the good use of "property" function?, I do not understand clearly.. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
Cameron Simpson <[EMAIL PROTECTED]> writes: > A good coder will present things clearly. For trivial stuff the one > line form may be fine, and for longer stuff then this: > > y = some thing or other \ > if x \ > else something_else Parentheses are usually more robust for multi-line, where possible: foo = (bar if some_condition() else baz) The lines can more easily be edited and rearranged without fiddling with backslashes at the end of every line. (For even more robustness at the cost of space, separate the parentheses so they're on separate lines from what they enclose.) It also addresses the original poster's complaint that there's no early signal of the compound nature of the expression: the opening parenthesis signals this. -- \ “It is far better to grasp the universe as it really is than to | `\persist in delusion, however satisfying and reassuring.” —Carl | _o__)Sagan | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
How do I use python object in C++
for example I have the following code: #include void exec_pythoncode( int arg, char**argv ) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is how can I get the variables I want after Py_Main(argc,argv) say I have a=[1,2,'Hello World',0.1234] in the python space, I would like to have it as a struct in C++. Any sample code? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
How can I use a PyObject in C++?
for example: #include void exec_python_code(int arg, char** argv) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is: after Py_Main(argc,argv); How do I get every variable in python space, say a=[1,2,3,'Hello World',[2,3]] b=['xx','xxx','',0.1234] , and use them in C++? any sample code? Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: python syntax for conditional is unfortunate
On 23Sep2008 19:52, Neal Becker <[EMAIL PROTECTED]> wrote: | In hindsight, I am disappointed with the choice of conditional syntax. | I know it's too late to change. The problem is | | y = some thing or other if x else something_else | | When scanning this my eye tends to see the first phrase and only | later notice that it's conditioned on x (or maybe not notice at all!). | Particularly if 'some thing or other' is long or complicated. Personally, I think this is deliberate (the wordiness and ordering, not the reading difficulty). Plenty of people dislike C's ternary b?x:y operator, presumably for the same reasons. A good coder will present things clearly. For trivial stuff the one line form may be fine, and for longer stuff then this: y = some thing or other \ if x \ else something_else or: if x: y = something or other else: y = something_else should appear. If it's your code, this is up to you. If it's another's, well anyone can write unreadable code... Cheers, -- Cameron Simpson <[EMAIL PROTECTED]> DoD#743 http://www.cskk.ezoshosting.com/cs/ Principles have no real force except when one is well fed. - Mark Twain -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualize class inheritance hierarchy
On Sep 23, 5:53 pm, Rob Kirkpatrick <[EMAIL PROTECTED]> wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? "Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob If you're using new-style classes, check out the __mro__ member, which no doesn't show up in its dir(). Otherwise, we can try a settrace (frame.f_code.co_name has the name of the class being defined in a class statement) or accumulate some class statements with a custom 'parser' run in the module 'parser'. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden: > It seems we have been implementing different algorithms. kd-trees are > not BK-trees. > http://www.scipy.org/Cookbook/KDTree Sorry for my silly mistake :-) Note: in your code I don't know if the collections.deque data structure may help (it's faster than list for appending), but I presume that's not a bottleneck. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
En Tue, 23 Sep 2008 09:37:44 -0300, Bobby Roberts <[EMAIL PROTECTED]> escribió: hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/x/ where x represents the domain name. How can I find the domain name of the current url being viewed. That info comes from the "Host" request field, and whether it's available or not depends on the web framework in use; for a plain old CGI script, it depends on the server configuration. Look at the HTTP_HOST environment variable (accessing os.environ, or with the cgi.print_environ() function) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
Robert Kern wrote: J Peyret wrote: On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are for searching through point sets in a k-dimensional space. My apologies. I did not actually follow bearophile's link, and thought he was talking about kd-trees like Sturla was. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualize class inheritance hierarchy
On Sep 23, 5:53 pm, Rob Kirkpatrick <[EMAIL PROTECTED]> wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? "Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob Compare their __mro__ members if they are new-style. The depth-first search for the member you're looking for is straightforward in Python, even if maybe not immediately obvious. If not, we can try a settrace and a search for when they are defined, and build an __mro__ manually. -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualize class inheritance hierarchy
Rob Kirkpatrick wrote: I'm assuming this has been discussed before, but I'm lacking any Google keywords that bring up the appropriate discussion. You are looking for "mro" aka method resolution order. The inspect module contains several helper functions to inspect a class hierarchy. The following interactive session should give you an impression how to use the functions: >>> import inspect >>> import pprint >>> from sqlalchemy.types import DateTime >>> inspect.getmro(DateTime) (, 'sqlalchemy.types.TypeEngine'>, , >>> DateTime.__bases__ (,) >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) [(, ()), [(, (,)), [(, (,)), [(, (,)) >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] [, 'sqlalchemy.types.TypeEngine'>, , ] >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] [, ] -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex Help
In message <[EMAIL PROTECTED]>, Support Desk wrote: > Anybody know of a good regex to parse html links from html code? The one I > am currently using seems to be cutting off the last letter of some links, > and returning links like > > http://somesite.co > > or http://somesite.ph > > the code I am using is > > > regex = r'' Can you post some example HTML sequences that this regexp is not handling correctly? -- http://mail.python.org/mailman/listinfo/python-list
python syntax for conditional is unfortunate
In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is y = some thing or other if x else something_else When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated. -- http://mail.python.org/mailman/listinfo/python-list
Re: appending * to glob returns files with '*' !!
No bug indeed, Erik was correct, in fact I had files with the * in the name... Thanks all for your replies! Erik Max Francis wrote: > > John [H2O] wrote: > >> I have a glob.glob search: >> >> searchstring = os.path.join('path'+'EN*') >> files = glob.glob(searchstring) >> for f in files: >> print f >> >> >> ___ >> This returns some files: >> EN082333 >> EN092334 >> EN* >> >> My routine cannot handle the '*' and it should'nt be returned anyway? :-/ >> >> A bug? > > No, it means you actually have a file named 'EN*' in the directory. > > -- > Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis >Many would be cowards if they had courage enough. > -- Thomas Fuller > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/appending-*-to-glob-returns-files-with-%27*%27-%21%21-tp19579121p19638699.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
detektei info detektei hessen in Gunzenhausen
http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
On Sep 23, 3:55 pm, Gerard flanagan <[EMAIL PROTECTED]> wrote: > George Sakkis wrote: > > On Sep 23, 1:23 am, "Tom Harris" <[EMAIL PROTECTED]> wrote: > > >> Greetings, > > >> I want to have a class as a container for a bunch of symbolic names > >> for integers, eg: > > >> class Constants: > >> FOO = 1 > >> BAR = 2 > > >> Except that I would like to attach a docstring text to the constants, > >> so that help(Constants.FOO) will print some arbitrary string. Sort of > >> a very limited implementation of PEP 224. The only solution that I can > >> see is to subclass int.__new__(), since once I have an int all it's > >> attributes are immutable. > > > Here's one approach, using metaclasses and descriptors; it sort of > > works, but it's less than ideal, both in usage and implementation. > > > George > > > #== usage > > > class MyConstants: > > __metaclass__ = ConstantsMeta > > FOO = const(1, 'some docs about foo') > > BAR = const(2) > > > print MyConstants.FOO.__doc__ > > help(MyConstants.FOO) > > print MyConstants.FOO - MyConstants.BAR > > print MyConstants.FOO - 2 > > print 1 - MyConstants.BAR > > > #=== implementation === > > > def ConstantsMeta(name, bases, namespace): > > for name,attr in namespace.iteritems(): > > if isinstance(attr, const): > > namespace[name] = _ConstDescriptor(name, attr.value, > > attr.doc) > > return type(name, bases, namespace) > > > class const(object): > > def __init__(self, value, doc=None): > > self.value = value > > self.doc = doc > > > class _ConstDescriptor(object): > > def __init__(self, name, value, doc): > > cls = type(name, (), dict( > > __doc__ = doc, > > __add__ = lambda self,other: value+other, > > __sub__ = lambda self,other: value-other, > > # ... > > __radd__ = lambda self,other: other+value, > > __rsub__ = lambda self,other: other-value, > > # XXX lots of boilerplate code for all special methods > > follow... > > # XXX Is there a better way ? > > )) > > self._wrapper = cls() > > > def __get__(self, obj, type): > > return self._wrapper > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think you get an equivalent result if you forget the descriptor > and adapt the metaclass: > > def ConstantsMeta(name, bases, namespace): > for name,attr in namespace.iteritems(): > if isinstance(attr, const): > cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) > namespace[name] = cls(attr.value) > return type(name, bases, namespace) Sweet! The big improvement of course is that you thought of subclassing the type of attr.value instead of delegating manually all special methods. It seems so obvious in retrospect, but I totally missed it for some reason; thanks! George -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 8:52 pm, [EMAIL PROTECTED] wrote: > Is this a good or bad thing? ;-) It seems we have been implementing different algorithms. kd-trees are not BK-trees. http://www.scipy.org/Cookbook/KDTree -- http://mail.python.org/mailman/listinfo/python-list
Visualize class inheritance hierarchy
Hi All, I just finished debugging some code where I needed to determine why one subclass had a bound method and another did not. They had different pedigree's but I didn't know immediately what the differences were. I ended up walking the hierarchy, going back one class at a time through the code, for the two subclasses (hierarchy ~7 classes deep each) to see whom they inherited from. Short of writing this down on paper, is there any way to graphically display the pedigree of an object/class? "Graphically" can be text output to the terminal, don't need anything special... I'm assuming this has been discussed before, but I'm lacking any Google keywords that bring up the appropriate discussion. Cheers, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 23 Sep 2008 13:34:10 -0700 (PDT), sturlamolden <[EMAIL PROTECTED]> wrote: >1. gfortran is not Absoft. I find this comment absurd. What did you mean by it ? Yes, gfortran is not Absoft, just as red is not blue (?!). I also don't understand whether you're looking for a free or a commercial compiler. I got the impression from your previous post that money was an object. >2. If I program the same in C99 and Fortran 95, and compile with gcc >and gfortran, the C99 code runs a lot faster (I've only tested with >wavelet transforms). Hmm. Unfortunatelly, i have none whatsoever experience in that field. Completely different area of study here, so without seeing at least some code, I cannot comment anything on that part. And 'a lot faster' is a very relative term. > >3. gfortran is not Absoft. > True. Best regards Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
Terry Reedy wrote: > MRAB wrote: >> >> How about something like this: >> >> def clear_workspace(): >> keep_set = set(['__builtins__', '__doc__', '__name__', >> 'clear_workspace']) > > For 2.6/3.0, add __package__ to the list to be kept. > >> for x in globals().keys(): >> if x not in keep_set: >> del globals()[x] Or... you might have a script clearWorkspace.py : - initGlobals = globals().keys() def clearWorkspace() : for gVar in globals().keys() : if gVar not in initGlobals : del globals()[gVar] - Which you run before doing anything else. Then you don't mind if additions were made to the list to keep, or if you are using something like pyCrust which has its own initial globals, or if you want to keep some global vars of your own (in which case you run clearWorkspace AFTER you instantiate your global vars). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
Drake wrote: I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Side note: sys.exit() is just another way to write raise SystemExit. The function is defined as: static PyObject * sys_exit(PyObject *self, PyObject *args) { PyObject *exit_code = 0; if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) return NULL; /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, exit_code); return NULL; } Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
Drake wrote: I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), No > or should the exception propagate to the calling program which handles the issue? Yes -- with an informative error message. If the caller ignores the exception, the program will exit with a full stack trace anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
[EMAIL PROTECTED] wrote: I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. How about file.tell == 0? or have I misunderstood the requirement? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden wrote: On Sep 23, 10:16 pm, Robert Kern <[EMAIL PROTECTED]> wrote: What's confusing? You do have to create a profile: How do I add a new page to the wiki? I'm only able to edit the front page of the cookbook. But it doesn't help to add link there if I have no page to link. (I may be incredibly stupid though.) You just navigate to the URL you want: http://www.scipy.org/Cookbook/KDTree This will show you a page saying: """ This page does not exist yet. You can create a new empty page, or use one of the page templates. Before creating the page, please check if a similar page already exists. Create new empty page """ The latter is a link that you can click. Looking at the other Cookbook page sources, I notice that you should add the following to the bottom of your page to categorize it appropriately. """ . CategoryCookbook """ Then put the link on the main Cookbook page (or do that first, then navigate through the link to create the page). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
> The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? > my view is that the exceptions are there precisely to tell the calling program about the error and give the programmer a chance to do something smart about it. A library, properly, doesn't even know the context in which it is running, and sys.exit() is pretty heavy handed for a library to call and shows assumptions beyond what a library should assume about its running environment. imho -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are "broken iterators" broken?
I'm interested what others think of this because at first I couldn't get it... I have an object which can iterate over its parts... and at first I thought, what? I'm supposed to create a new object every time the user needs to iterate the contents? In the end I interpreted that statement as if "unless __iter__()" is called again, in which case it makes sense that an iterator should stay "finished" until it's told to start to iterate again. Then even the stream analogy holds, you don't expect a stream to say EOF then start giving you bytes (from beyond the end, I guess)... instead, such a stream would more likely block if it got to the end of available data. I'm probably being stupid in this... perhaps I'm the only one that at first interpreted the phrase as being regardless of a fresh call to __iter__()... and that the OP was worried about some other implication. But if I was wrong to think it's ok for one and the same iterator to reset when __iter__() is called again, then I seriously don't understand. what does "forever" mean in that dictum? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
On 2008-09-23, Drake <[EMAIL PROTECTED]> wrote: > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), No. A library module should never call sys.exit(). > or should the exception propagate to the calling program which > handles the issue? Yes. Let the application handle the error if it wants to. If it's not handled, it'll end up causing the program to exit. -- Grant Edwards grante Yow! It's a hole all the at way to downtown Burbank! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
> > > Usegrammers? > usegrammers are just those that use grammars, but misspell it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python style: exceptions vs. sys.exit()
Drake wrote: I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Thanks in advance for anyone who can either answer my question or point me to where this question has already been answered. IMHO libraries should always just let the exception propagate up to the caller. That allows the caller the option of taking the appropriate action. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Not fully OO ?
> if they want to, but it is *fully* OO in that it includes everything > required to do OO. But maybe the original blogger meant by "fully OO" > what I mean by "Pure OO"? it seems to me this is what was meant... pure OO, AND forced to use it. My personal feeling is that python is multiparadigmed and I'm more than fine with that. BUT, I am going to hold onto what I've noticed which is that Python seems to use OO deeply, well into the interpreter, and that the procedural styles available at the Python source level pretty much are built on top of this OO model, given you accept a module as an object, which it seems to be within the source code... but in the end, it's just words and the most important thing is that python is a tool you can use to make a computer do what you want, and whatever you call it may just be a distraction. cheers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
On Sep 22, 7:13 pm, process <[EMAIL PROTECTED]> wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. Eliminating tail calls affects the semantics of your program (by changing memory complexity). As an optimization, it's a side-effect of the implementation, which is a particularly nasty kind of side- effect. Even if guaranteed it's fairly subtle. "return x()" would be optimized while "return x() + 1" would not. Or maybe you're calling a function that uses a wrapper and the wrapper isn't tweaked right to be optimized. Recursion in general can be very useful, but not tail-recursion. The only time it's not trivial to convert tail-recursion into a loop is when it involves multiple functions, but even that can be done if you know how. -- http://mail.python.org/mailman/listinfo/python-list
Re: curses.setsyx()?
On Sep 23, 4:16 pm, [EMAIL PROTECTED] wrote: > On Sep 22, 11:24 pm, Tim Roberts <[EMAIL PROTECTED]> wrote: > > > > > [EMAIL PROTECTED] wrote: > > >On Sep 19, 6:42 pm, [EMAIL PROTECTED] wrote: > > >> On Sep 19, 1:24 am, Tim Roberts <[EMAIL PROTECTED]> wrote: > > > >> > [EMAIL PROTECTED] wrote: > > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > > >> > >cursor. Any alternatives/solutions? > > > >> > Did you call doupdate after? setsyx just manipulates the data > > >> > structures. > > >> > It takes a call to doupdate to force those changes to take effect > > >> > visually. > > >> > -- > > >> > Tim Roberts, [EMAIL PROTECTED] > > >> > Providenza & Boekelheide, Inc. > > > >> I added it and it still doesn't work. This is what I'm doing when I > > >> want to display the cursor and prepare it for input at 2,3: > > > >> curses.echo() > > >> curses.curs_set(1) > > >> curses.setsyx(2,3) > > >> curses.doupdate() > > > >Any idea what's wrong? > > > No. Are you able to post an entire sample that demonstrates the problem? > > -- > > Tim Roberts, [EMAIL PROTECTED] > > Providenza & Boekelheide, Inc. > > http://pastebin.com/m6413db1 > > Run that and press 'n' key. It is supposed to move the cursor to 2,3 > and it doesn't. Sorry that was me, forgot to switch emails. But yes that is it. Remove the line about ppm/settings.conf if you don't want to create it because it will throw an exception. -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
On Sep 23, 1:23 pm, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: > Bobby Roberts a écrit : > > > hi group. I'm new to python and need some help and hope you can > > answer this question. I have a situation in my code where i need to > > create a file on the server and write to it. That's not a problem if > > i hard code the path. However, the domain name needs to be dynamic so > > it is picked up automatically. The path to our websites is > > > home/sites/x/ > > > where x represents the domain name. > > > How can I find the domain name of the current url being viewed. > > What are you using exactly ? cgi ? wsgi ? Else ? mod python over an in-house framework written years ago without documentation so it's not the easiest thing to navigate. We will be moving to django this fall. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 10:16 pm, Robert Kern <[EMAIL PROTECTED]> wrote: > What's confusing? You do have to create a profile: How do I add a new page to the wiki? I'm only able to edit the front page of the cookbook. But it doesn't help to add link there if I have no page to link. (I may be incredibly stupid though.) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to keep a window above all other OS windows?
On Sep 23, 11:21 pm, dmitrey <[EMAIL PROTECTED]> wrote: > Hi all, > how to keep a Tkinter window above all other OS windows (i.e. > including those ones from other programs)? > > Thank you in advance, > Dmitrey I have put [Tkinter] into topic of my message but somehow it has been removed. D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 10:05 pm, Robert Singer <[EMAIL PROTECTED]> wrote: > May I ask what are your main objections to it ? 1. gfortran is not Absoft. 2. If I program the same in C99 and Fortran 95, and compile with gcc and gfortran, the C99 code runs a lot faster (I've only tested with wavelet transforms). 3. gfortran is not Absoft. -- http://mail.python.org/mailman/listinfo/python-list
Python style: exceptions vs. sys.exit()
I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Thanks in advance for anyone who can either answer my question or point me to where this question has already been answered. -- http://mail.python.org/mailman/listinfo/python-list
[Tkinter] how to keep a window above all other OS windows?
Hi all, how to keep a Tkinter window above all other OS windows (i.e. including those ones from other programs)? Thank you in advance, Dmitrey -- http://mail.python.org/mailman/listinfo/python-list
Re: curses.setsyx()?
On Sep 22, 11:24 pm, Tim Roberts <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > >On Sep 19, 6:42 pm, [EMAIL PROTECTED] wrote: > >> On Sep 19, 1:24 am, Tim Roberts <[EMAIL PROTECTED]> wrote: > > >> > [EMAIL PROTECTED] wrote: > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >> > >cursor. Any alternatives/solutions? > > >> > Did you call doupdate after? setsyx just manipulates the data > >> > structures. > >> > It takes a call to doupdate to force those changes to take effect > >> > visually. > >> > -- > >> > Tim Roberts, [EMAIL PROTECTED] > >> > Providenza & Boekelheide, Inc. > > >> I added it and it still doesn't work. This is what I'm doing when I > >> want to display the cursor and prepare it for input at 2,3: > > >> curses.echo() > >> curses.curs_set(1) > >> curses.setsyx(2,3) > >> curses.doupdate() > > >Any idea what's wrong? > > No. Are you able to post an entire sample that demonstrates the problem? > -- > Tim Roberts, [EMAIL PROTECTED] > Providenza & Boekelheide, Inc. http://pastebin.com/m6413db1 Run that and press 'n' key. It is supposed to move the cursor to 2,3 and it doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On 23 Sep., 21:23, J Peyret <[EMAIL PROTECTED]> wrote: > On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: > > Guys, this looks like a great data structure/algo for something I am > working on. > > But... where do I find some definitions of the original BK-tree idea? *geometric data structures*. Just google for it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden wrote: On Sep 23, 9:17 pm, Robert Kern <[EMAIL PROTECTED]> wrote: You could also drop it on the scipy.org wiki in the Cookbook category. Yes, if I could figure out how to use it... What's confusing? You do have to create a profile: http://www.scipy.org/UserPreferences -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 23 Sep 2008 11:07:22 -0700 (PDT), sturlamolden <[EMAIL PROTECTED]> wrote: >On Sep 23, 3:44 pm, Robert Singer <[EMAIL PROTECTED]> wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > >Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > No. And just to avoid eventual useless discussions which might arise, I ment to say that *in general* compiled languages are faster. We can always have discussions whether or not some newer scripting languages like some from the above list, come close, but that usually is just wasted time. Specifically, I cannot say about R, IDL or S-PLUS, since I never used those (not even heard of IDL till now). Octave and Mathematica have been with me for such a short time (we had a few licences for Wolfram's child for one year, but not my part of the company, so ...) that I would rather not give my opinion about those. I've used Matlab and Scilab for a longer time (still do actually - Matlab for measurement data acquisition, and Scilab ... well, it just sits on the disk somewhere actually), and although Matlab is quite fast when disk I/O is involved, it still comes far. >> Also, (I'm not that familiar with python yet, so I don't know how to >> do it in python), try finding the bottlenecks of your calculation. > >I did use a profiler, there is no particular single bottle-neck. You're talking about your c or your python version of the program? There is always a bottleneck - that's just the part which works most slowly. Try to find the part which takes the longest to execute, try to put it differently. If it cannot be done, go to the next slowest part. >Good compilers are too expensive, and gfortran is not good enough yet. > ? Gfortran is one of the better compilers on the market. There was, just the other day, a nice discussion on comp.lang.fortran how it is marvellous what a group of enthousiasts managed do in their time, what commercial giants still didn't. May I ask what are your main objections to it ? Best regards Bob -- http://mail.python.org/mailman/listinfo/python-list
Does anybody use this web framework ?
Hi, I just found this new? python web framework (http://pypi.python.org/pypi/nagare/0.1.0). Does anybody know or use it ? Regards, Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
George Sakkis wrote: On Sep 23, 1:23 am, "Tom Harris" <[EMAIL PROTECTED]> wrote: Greetings, I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. Sort of a very limited implementation of PEP 224. The only solution that I can see is to subclass int.__new__(), since once I have an int all it's attributes are immutable. Here's one approach, using metaclasses and descriptors; it sort of works, but it's less than ideal, both in usage and implementation. George #== usage class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #=== implementation === def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): namespace[name] = _ConstDescriptor(name, attr.value, attr.doc) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc class _ConstDescriptor(object): def __init__(self, name, value, doc): cls = type(name, (), dict( __doc__ = doc, __add__ = lambda self,other: value+other, __sub__ = lambda self,other: value-other, # ... __radd__ = lambda self,other: other+value, __rsub__ = lambda self,other: other-value, # XXX lots of boilerplate code for all special methods follow... # XXX Is there a better way ? )) self._wrapper = cls() def __get__(self, obj, type): return self._wrapper -- http://mail.python.org/mailman/listinfo/python-list I think you get an equivalent result if you forget the descriptor and adapt the metaclass: def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) namespace[name] = cls(attr.value) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc #== usage class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #== Alternatively, forget the metaclass and have: def const(name, val, doc=None): return type(name, (type(val),), {'__doc__': doc})(val) #== usage class MyConstants: FOO = const('FOO', 1, 'some docs about foo') BAR = const('BAR', 2) MOO = const('MOO', 8.0, 'all about MOO') #== G. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
J Peyret wrote: On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are for searching through point sets in a k-dimensional space. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 9:17 pm, Robert Kern <[EMAIL PROTECTED]> wrote: > You could also drop it on the scipy.org wiki in the Cookbook category. Yes, if I could figure out how to use it... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? I looked through Amazon and only a few books mention something like BK-Tree and these are mostly conference minutes books, at ungodly prices. I also did a quick Google on it and there isn't that much about the subject. http://blog.notdot.net/archives/30-Damn-Cool-Algorithms,-Part-1-BK-Trees.html is the one I mostly saw referred. So... 2 questions: 1. More bk-tree references? I can follow the code, but some understanding of the background would be nice. 2. What, if any, is a good book to understand the basic of fuzzy/ string matching? Proximity/affinity problems? Or, more generally, a good book on advanced algorithms? No, I don't wanna read Knuth's just yet, something more modern/easy to follow maybe? Something like 'Programming Collective Intelligence', ISBN 0596529325, would be very nice, though it is perhaps a bit too specific in its applications. Books using Java or C are fine. Lisp, hmmm, well... I have trouble reading its notation, sorry. Cheers JLuc -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Bobby Roberts a écrit : hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/x/ where x represents the domain name. How can I find the domain name of the current url being viewed. What are you using exactly ? cgi ? wsgi ? Else ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
Sean Davis a écrit : On Sep 23, 2:02 pm, [EMAIL PROTECTED] wrote: I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. s/file handle/file object/ This being said, I can only second Sean's advice. And anyway, computing something and writing the result(s) of this computation to the file are orthogonal and mostly unrelated responsabilities, so they shouldn't be handled by the same function. Here's a possible reorganisation of your code: def simulate(parameter): # lots of code followed by return sigma def main(): # presumably some other code here with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) for param in range(10): writer.writerow(simulate(param)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
[EMAIL PROTECTED] wrote: sturlamolden: Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ You could also drop it on the scipy.org wiki in the Cookbook category. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Twisted: Get Protected HTTPS Page via Proxy with Authentication
This works: # Proxy credentials proxyAuth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authHeader = "Basic " + proxyAuth.strip() # Web site credentials basicAuth = base64.encodestring('%s:%s' % (username, password)) authHeader = "Basic " + basicAuth.strip() return client.getPage(url, headers={"Authorization": authHeader, 'Proxy-Authenticate': proxy_authHeader}) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 8:52 pm, [EMAIL PROTECTED] wrote: > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste):http://codepad.org/ http://codepad.org/rh8GzzJT Available 24 hours from now. > Is this a good or bad thing? ;-) It's just facinating how different people working on similar problems come up with different looking code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden: >F# and OCaml look promising though.< I bet on the future of D and Haskell (and maybe Fortress) instead :-) We'll see. >Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ >It looks very different form yours though.< Is this a good or bad thing? ;-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
> Will LINQ be ported to Python ? I have three suggestions: 1. When starting a new thread, start a *new* thread. Don't tack a new, unrelated subject onto an existing thread. Your post will not be seen by people with readers that collapse thread and who do not happen to read the 'Python is slow?' thread. 2. Also, give enough informaton that people can understand your question without searching the web and guessing. In particular, that do *you* mean by LINQ? The game? The .NET component? Or something else? 3. Before posting, search the Python manuals or the web a bit for an answer. If you mean the .NET component, googling 'Python LINQ' should partly answer your question. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 4:48 pm, hrishy <[EMAIL PROTECTED]> wrote: > Will LINQ be ported to Python ? No, because Python already has list comprehensions and we don't need the XML buzzword. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 10:57 am, Grant Edwards <[EMAIL PROTECTED]> wrote: > AFAICT, _everybody_ is bad at programming C++. Thankfully, at least Numpy developers are not bad at C programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
> But surely the idea behind it will eventually spread. It's really > just comprehensions generalized over XML and relational datasets, a > noble goal. Besides, it's main purpose for .NET was to bring > functional programming to it. Python already has that, somewhat... it's really any object out of the box, i think the sql linq stuff is more of a query compiler, IMO sqlalchemy does that. query = select(user_cols, and_(table_relationship.c.accept_user_id==user.id, table_relationship.c.start_date==None ), from_obj=join( table_relationship,table_user, onclause=table_user.c.id==table_relationship.c.init_user_id ).outerjoin(table_profile) ) session.execute(query).fetchall() XML? meh hopefully I would never need it. :) C# is my day job, and when I got my hands on LINQ back in January my initial thought was "Finally I have list comprehensions day job is fun again" For the most part, I think C# is catching up. -- http://mail.python.org/mailman/listinfo/python-list
FREE INTERNATIONAL TRADE LEADS
http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# -- http://mail.python.org/mailman/listinfo/python-list
Re: python timers and COM/directshow
You're right. Let me be more specific. Firstly, the reason I included c++ code is because I'm using Microsoft COM, which is natively in c++, and in fact, to access them through Python I use the comtypes module [import comtypes] and then GetModule('quartz.dll') to access the dll's. I am using the gtk GUI widgets. I have a gtk.Hscale scrollbar which I would like to be a trackbar for the video playback. To coordinate this in Python, much like in c++, I would like to have a timer thread synchronizing the scrollbar update. ie: def scrollbar_callback(args): media_control.CurrentPosition= scrollbar.get_value() def timer_callback(args): #code to update the scrollbar based on video position, something like scrollbar.set_value(media_control.CurrentPosition) >>>*And, I would like to be able to kill, run the timer based on whether the >>>video is playing or paused, ie def player(args): media_control.Run() #plays video timer.run() def pauser(args): media_control.Pause() timer.kill Any tips? -sayanan -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
Peter Pearson wrote: On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris <[EMAIL PROTECTED]> wrote: I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. [snip] Commiserating, not helping: I have a similar problem with a module that holds values of physical constants, http://webpages.charter.net/curryfans/peter/nature.py: boltzmanns_constant = 1.380622e-16 * erg / k stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k gravitational_constant = 6.6732e-8 * erg*cm/g/g I would like to reveal more details with, e.g., help( gravitational_constant ) . . . and maybe then I could use shorter names. gravitational_constant = g = 6.6732e-8 * erg*cm/g/g ... -- http://mail.python.org/mailman/listinfo/python-list
Re: python timers and COM/directshow
On Sep 23, 4:24 am, Tim Golden <[EMAIL PROTECTED]> wrote: > Sayanan Sivaraman wrote: > > So I've written a simple video player using directshow/COM in VC++, > > and I'm in the process of translating it to python. For example, when > > the avi starts playing, I have a call media_control.Run() , etc. > > > I'm wondering how I should go about updating my gtk.Hscale widget as a > > trackbar for the avi player. > > > In C++, I have the following callbacks that update the scrollbar and > > video position with a timer. > > [... snip callbacks ...] > > > > > I'm wondering how I would implement similar callbacks in Python for a > > gtk.Hscale, and some sort of time [I'm not familiar with Pythons > > timers/threading at all]. > > You'd help your cause a lot here if you posted *Python* > code to indicate what's calling what back where. Also if > you stated whether you were using, eg, the GTK toolkit which > your description suggests, or some other GUI toolkit. Because > they tend to vary as to how they arrange their callbacks. > > In geeneral, Python callbacks are trivial: you create the > function to do whatever and then pass the function as an > object into the calling-back function call. Something > like this (invented GUI toolkit): > > > def handle_lbutton_click (event): > # > # do stuff with lbutton click > # > > def handle_widget_slide (event): > # > # do stuff with widget slide > # > > handle_event ("lbutton_click", handle_lbutton_click) > widget.attach_event ("slide", handle_widget_slide) > > > > But the details will obviously depend on the toolkit you > use. > > TJG > TJG Sorry, you make a very good point. I am using gtk. I don't have a problem with callbacks for the gtk widgets. My question is about timers and their callbacks. The reason I used c++ code is that Microsoft's COM interface is natively in C++, and Python uses "import comtypes" to access this functionality and the dll's.[ie GetModule('quartz.dll')] Essentially what I would like to have [as evidenced by the c++ code] is something like the following: def timer_callback(args): while timer is active update scrollbar position based on video progress #here I am using microsoft's COM interface, so the function would be something like scrollbar.set_value(media_control.CurrentPosition) def scrollbar_callback : when the scrollbar is moved, update this video position #this I understand. It would be something like media_control.CurrentPosition= scrollbar.get_value() def pauser : media_control.Pause() *somehow kill timer* def player: media_control.Run() timer.run() #timer.run() would call timer_callback So I would like to know how to construct and implement a timer that would do the above, a la the first callback. In addition, the timer has to be able to be paused/killed if I pause the video, and implemented again if I play the video ie: Thanks, sayanan -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Gerhard Häring wrote: D'Arcy J.M. Cain wrote: I'm not sure I follow this logic. Can someone explain why float and integer can be compared with each other and decimal can be compared to integer but decimal can't be compared to float? from decimal import Decimal i = 10 f = 10.0 d = Decimal("10.00") i == f True i == d True f == d False I can give you the technical answer after reading the sources of the decimal module: you can only compare to Decimal what can be converted to Decimal. And that is int, long and another Decimal. The new fractions module acts differently, which is to say, as most would want. >>> from fractions import Fraction as F >>> F(1) == 1.0 True >>> F(1.0) Traceback (most recent call last): File "", line 1, in F(1.0) File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__ numerator = operator.index(numerator) TypeError: 'float' object cannot be interpreted as an integer >>> F(1,2) == .5 True >>> .5 == F(1,2) True so Fraction obviously does comparisons differently. Decimal is something of an anomaly in Python because it was written to exactly follow an external standard, with no concessions to what would be sensible for Python. It is possible that that standard mandates that Decimals not compare to floats. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
On Sep 23, 7:02 pm, [EMAIL PROTECTED] wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) > writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. > > Thanks in advance for your assistance > > Thomas Philips You can use he os.path module: appending = os.path.exists(summaryFn) with open(summaryFn, 'ab') as f: writer = ... if not appending: writer.writerow(header) writer.writerow(Sigma) But if you only write to the file in one code location, you can set a flag. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
On Sep 23, 2:02 pm, [EMAIL PROTECTED] wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) > writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 5:31 pm, [EMAIL PROTECTED] wrote: > Well written C++ code is generally faster or much faster than similar > Python code, but programming in Python is often simpler, and it > generally requires less time. So it may happen that to solve a problem > a Python program that runs in 1 hour that requires 1 hour to be > written allows you to find the solution in less time than a C++ > program that runs in 5-10 minutes that requires you 3-4 hours to be > written :-) I could easily sit down and wait half an hour. I could even wait a week for the calculation to complete. But this is a program that will be used many times, and not just by me. > Note that C++ is just one option, but there are other languages > around, like CLisp or D (or even a modern JavaVM), that are often an > acceptable compromise between Python and C/C++. Yes, if I knew Lisp, I would have used SBCL. Java I can program. But it is a pain in the ass for any scientific programming. F# and OCaml look promising though. > Note that I have written a kd-tree in both Python (with Psyco > compulsively) and D, this is the Psyco > version:http://code.activestate.com/recipes/572156/ Sure I could show you the code, Python and C++, if I had a place to post it. It looks very different form yours though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 3:44 pm, Robert Singer <[EMAIL PROTECTED]> wrote: > Well, python is not a number crunching language. However much we would > like it to be (we would ? :-). > No scripting language is. Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > Before resorting to rewriting the problem try psyco. It speeds up > things sometimes. I did, Psyco did not help. > Also, (I'm not that familiar with python yet, so I don't know how to > do it in python), try finding the bottlenecks of your calculation. I did use a profiler, there is no particular single bottle-neck. > Well, personally, I try to combine fortran (being a fortran programmer > by trade) with python Good compilers are too expensive, and gfortran is not good enough yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: adding in-place operator to Python
Arash Arfaee wrote: Hi All, Is there anyway to add new in-place operator to Python? Or is there any way to redefine internal in-place operators? Python does not have 'in-place operators'. It has 'augmented assignment statements' that combines a binary operation with an assignment. *If* the target being rebound is mutable, *then* (and only then) the operation can be and is recommended to be done 'in-place'. User-defined mutable classes (as most are) can implement in-place behavior with __ixxx__ methods. But for the reason given below, __ixxx__ methods should supplement and not replace direct mutation methods. Correct terminology is important for understanding what augmented assigments do and what they are basically about. First, most augmented assignments target immutables, in particular, numbers and strings, which do not have __ixxx__ methods. So the operation is *not* done in-place. The only difference from separately indicating the assignment and operation is that the programmer writes the target expression just once and the interpreter evaluates the target expression just once instead of each repeating themselves. (And consequently, any side-effects of that evaluation happen just once instead of twice.) The same __xxx__ or __rxxx__ method is used in either case. This non-repetition is the reason for augmented assigments. The optional in-place optimization for mutables is secondary. It was debated and could have been left out. Second, all augmented assignments perform an assignment, even if the operation is done in place. However, if a mutable such as a list is accessed as a member of an immutable collection such as a tuple, mutation is possible, but rebinding is not. So the mutation is done and then an exception is raised. To avoid the exception, directly call a mutation method such as list.extend. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 2:07 pm, Jason Scheirer <[EMAIL PROTECTED]> wrote: > On Sep 23, 7:48 am, hrishy <[EMAIL PROTECTED]> wrote: > > > Hi > > > Will LINQ be ported to Python ? > > > regards > > Hrishy > > I think this question is more appropriate to ask on an IronPython > development list -- LINQ is pretty solidly intertwined with .Net, and > so you'll likely want to look at the .Net implementation of Python. But surely the idea behind it will eventually spread. It's really just comprehensions generalized over XML and relational datasets, a noble goal. Besides, it's main purpose for .NET was to bring functional programming to it. Python already has that, somewhat... -- http://mail.python.org/mailman/listinfo/python-list
Detecting the first time I open/append to a file
I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. Thanks in advance for your assistance Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix programming
A. Joseph wrote: I need an ebook or tutorial that teach matrix programming. Perhaps you should start here: http://www.catb.org/~esr/faqs/smart-questions.html#intro Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
On Sep 23, 1:23 am, "Tom Harris" <[EMAIL PROTECTED]> wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Here's one approach, using metaclasses and descriptors; it sort of works, but it's less than ideal, both in usage and implementation. George #== usage class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #=== implementation === def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): namespace[name] = _ConstDescriptor(name, attr.value, attr.doc) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc class _ConstDescriptor(object): def __init__(self, name, value, doc): cls = type(name, (), dict( __doc__ = doc, __add__ = lambda self,other: value+other, __sub__ = lambda self,other: value-other, # ... __radd__ = lambda self,other: other+value, __rsub__ = lambda self,other: other-value, # XXX lots of boilerplate code for all special methods follow... # XXX Is there a better way ? )) self._wrapper = cls() def __get__(self, obj, type): return self._wrapper -- http://mail.python.org/mailman/listinfo/python-list
Matrix programming
I need an ebook or tutorial that teach matrix programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 7:48 am, hrishy <[EMAIL PROTECTED]> wrote: > Hi > > Will LINQ be ported to Python ? > > regards > Hrishy I think this question is more appropriate to ask on an IronPython development list -- LINQ is pretty solidly intertwined with .Net, and so you'll likely want to look at the .Net implementation of Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Not fully OO ?
2008/9/23 Craig Allen <[EMAIL PROTECTED]>: > So python may turn out to be pure OO I think that's the sort of thing the pedants would hang that hats on, too. Python isn't *pure* OO, in that it lets the programmers do non-OO if they want to, but it is *fully* OO in that it includes everything required to do OO. But maybe the original blogger meant by "fully OO" what I mean by "Pure OO"? The question I usually ask is "Does this language help me get the job done?" Python often does. That's all that really matters, isn't it? -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Hi, Bobby Roberts wrote: On Sep 23, 9:10 am, Tino Wildenhain <[EMAIL PROTECTED]> wrote: Bobby Roberts wrote: Depends on the technology/web framework. If you use WSGI, you should use something like: host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] -- Gerhard Yeah i already tried environ("SERVER_NAME") but get a key error when i do. You could output the whole environ to see what you get and how it is called. ... evidently the environ dictionary is off limits on our server. It can't be that tough in python to get the current complete url being viewed. It's a snap in asp(which is my background). Its a snap in all python based web apps I ever saw. You didn't tell us what you actually using so we can't say. Also there is no notation of "url beeing viewed" in HTTP if you are looking from server's point of view. There is a request for an URI and a host where the request is directed at then then the server decides to publish a resource based on whatever rules. If that publishing results in a call to your python script (or the script itself is the server) then you would deal with whatever interface API you decided to use gives you. Ah and last not least you can even use python in ASP (look for scripting host) but's not a route to take these days :-) (You really want no inline code but a decent templating engine like PageTemplates (TAL)) Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I use a callable object as a method
Hrvoje Niksic wrote: >> However, the second version does not work. I think I understand >> why. That's because "a" inside f1 is not a function (but an object). > > An object that defines __call__ is perfectly usable as a function. > Your problem is that it doesn't know how to convert itself to a > method, so that f1.a() knows how to pass f1 as another_self to > add.__call__. To do that, add needs to be a bit smarter: A! Now it works, thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
SPE restore defaults
Hi, I am sorry if this is a bit off topic... I downloaded SPE, but i changed the config option by mistake to a Skin only for Mac... so everytime i start SPE it crashes. I tried uninstalling, but it didnt work, it seems the value is in the registry, but i couldnt find it. Can anyone help? (Spe forum is not useful.. thanks) -- http://mail.python.org/mailman/listinfo/python-list