Re: cosmetic Tkinter question
On 26.12.2004, at 16:38, Sean McIlroy wrote: I've got a bunch of Frames, all packed into the root window with side=TOP, and in each Frame I've got a Checkbutton packed with side=LEFT. I expected the Checkbuttons to be flush with the left edge of the window, but they're not, and it looks a little gross. How do I get them to align? if you pack the frames with option fill=X they should be well aligned -- This commands the frame to use all available space in the horizontal direction: your_frame.pack(side=TOP,fill=X) your_button.pack(side=LEFT) - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
syntax error in eval()
Hi all, I am trying to dynamically add class attributes at runtime using the function eval(), i.e. I want to do something like >>> class X : pass ... >>> X.attr = 5 but without knowing either the attributes name nor its value. However, I encounter a syntax error I cannot understand: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class X : pass ... >>> attrname = "attr" >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) Traceback (most recent call last): File "", line 1, in ? File "", line 1 X.attr = val ^ SyntaxError: invalid syntax Does anyone have a clue what might be wrong? Thanks in advance. - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman -- http://mail.python.org/mailman/listinfo/python-list
Re: syntax error in eval()
Thank you, Duncan and Steven. I completely forgot about setattr. Of course that's the way ... as its name might suggest *g* What you are doing wrong is attempting to use eval before exhausting all the simpler techniques. Why not just call 'setattr'? setattr(X, 'attr', 5) BTW, the syntax error is because eval evaluates an expression and an assignment statement is a statement not an expression. -- Abandon the search for Truth -- settle for a good fantasy. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: here document
On 11.01.2005, at 11:34, Nader Emami wrote: Would somebody help me how i can write the 'here document' in Python script please? I have a csh script in which a program is invoked with some argument in the form of here document: /bin/exe.x << End_Here CategorY = GRIB etc. End_Here I translate this script to Python and i don't know how can I do this! f = open("/bin/exe.x","w") print >>f , """CategoryY = GRIB etc. """ -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen -- http://mail.python.org/mailman/listinfo/python-list
how to set doc-string of new-style classes
Hello, does anyone know a way to set the __doc__ string of a new style class? Any attempt I tried results in the following error: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object) : ... pass ... >>> Foo.__doc__ = "bar" Traceback (most recent call last): File "", line 1, in ? TypeError: attribute '__doc__' of 'type' objects is not writable I can understand someone arguing that "changing a doc string is during programm execution and should therefore be forbidden!" But, I cannot even find out a way to set the doc string, when I CREATE a class using type(name,bases,dict) ... At least this should be possible, IMHO. - harold - -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. -- http://mail.python.org/mailman/listinfo/python-list
Re: exporting from Tkinter Canvas object in PNG
On 11.01.2005, at 19:14, Nicolas Pourcelot wrote: Hello, I'm new to this mailing list and quite to Pyhon too. I would like to know how to export the contain of the Canvas object (Tkinter) in a PNG file ? Thanks :) Nicolas Pourcelot -- http://mail.python.org/mailman/listinfo/python-list you can make a postscript dump using >>> canvas = Tkinter.Canvas(master) >>> canvas.postscript(file="your_file_name.ps") If you have ImageMagick, you can later use % convert your_file_name.ps your_file_name.png on the comand line, if you want to have png. - harold - -- Science is to see what everybody else has seen, and think what nobody else has thought. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: how to set doc-string of new-style classes
On 11.01.2005, at 19:35, Alex Martelli wrote: harold fellermann <[EMAIL PROTECTED]> wrote: ... But, I cannot even find out a way to set the doc string, when I CREATE a class using type(name,bases,dict) ... At least this should be possible, IMHO. x=type('x',(),dict(__doc__='hi there')) x.__doc__ 'hi there' yes, you're right ... a subsequent question, that puzzles me: where can I apply for the "most-stupid-question"-award, now *g* thanks anyway, - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
On 12.01.2005, at 18:35, It's me wrote: For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? because len() works only for sequence and mapping objects: >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. - harold - -- Ceci n'est pas une signature. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Why would I get a TypeEror?
On 12.01.2005, at 18:35, It's me wrote: For this code snip: a=3 b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? the problem is, that (1,len(a)) is evaluated, neither what type a actually has (python has no builtin lazy evaluation like ML). You have to do it this way instead: a=3 ... b = isinstance(a,(list,tuple,dict)) and len(a) or 1 - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Unclear On Class Variables
Hi Tim, If you have class Foo(object) : x = 0 y = 1 foo = Foo() foo.x # reads either instance or class attribute (class in this case) foo.x = val # sets an instance attribute (because foo is instance not class) Foo.x = val # sets a class attribute foo.__class.__x = val # does the same this might be sometimes confusing. IMHO, the following is especially nasty: >>> foo = Foo() >>> foo.x += 1 >>> >>> print foo.x 1 >>> print Foo.x 0 although the += operator looks like an inplace add it isn't. it is just syntactic sugar for foo.x = foo.x + 1. - harold - On 13.01.2005, at 07:18, Tim Daneliuk wrote: I am a bit confused. I was under the impression that: class foo(object): x = 0 y = 1 means that x and y are variables shared by all instances of a class. But when I run this against two instances of foo, and set the values of x and y, they are indeed unique to the *instance* rather than the class. It is late and I am probably missing the obvious. Enlightenment appreciated ... -- --- - Tim Daneliuk [EMAIL PROTECTED] PGP Key: http://www.tundraware.com/PGP/ -- http://mail.python.org/mailman/listinfo/python-list -- Everyone is a genius. It's just that some people are too stupid to realize it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickling a class instead of an instance
have a look at the thread "copying classes?" some days ago. what goes for copying goes for pickling also, because the modules use the same interface. - harold - On 13.01.2005, at 13:32, Sebastien Boisgerault wrote: Hi, It seems to me that it's not possible with the pickle module to serialize a class rather than an instance, as in from pickle import * class C(object): "... doc ..." a = 1 pickstr = dumps(C) I mean, it does *something*, there is no error indeed, but from the string pickstr, I am unable to rebuild the class C in a brand new context (got a "you're really stupid, all you deserve is an AttributeError because you know there is no attribute 'C' in the 'module' object" error). Am I wrong ? Why would the "(new-style) classes are regular objects too" mantra not apply in this case ? Could we imagine a patch to the pickle module to handle this kind of situation ? SB -- http://mail.python.org/mailman/listinfo/python-list -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Tix and Tkinter
On 31.12.2004, at 16:50, Harlin Seritt wrote: import Tix from Tkconstants import * from Tkinter import * root = Tix.Tk() Label(root, text="Hello!").pack() Tix.tixControl().pack() root.mainloop() When I run this, I get the following error: Traceback (most recent call last): File "TixTest.py", line 8, in ? Tix.tixControl().pack() AttributeError: 'module' object has no attribute 'tixControl' in the Tix module this widget is called Control. writing Tix.Control().pack() should work. - harold - -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Tix.FileSelectDialog wait for user?
Hi, I have a question concerning the Tix file select mechanisms. Unfortunately, I have very little experience with neither tk, Tkinter nor Tix. Somewhere in my GUI I have a save button. What I want is that pressing the button opens a file requester. The user can either select a filename or cancel the action. I have found Tix.FileSelectDialog which seems to be nice for the task. But how can I use this dialog after all? how can I e.g. attach a command to the "Ok"-Button. Or isn't there a simple function that 1.) opens the requester 2.) waits until the requester is closed 3.) returns either a string (filename) or None (canceled) so that I can just write something like: fname = FileSelect() if fname != None : do_something_with(fname) Damn, I hate Tk's and Tix' so called "manuals": The Tk manual takes a user and makes it into a grammar parser. Further information, like common usage or examples, that might normally be expected in a manual cannot be found with no additional arguments. The Tk manual returns the completely clueless programmer. Start to like pydoc(Tkinter) and pydoc(Tix), though :-) - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." -- http://mail.python.org/mailman/listinfo/python-list
pickling extension class
Hi all, I have a problem pickling an extension class. As written in the Extending/Embedding Manual, I provided a function __reduce__ that returns the appropreate tuple. This seams to work fine, but I still cannot pickle because of the following error: >>> from model import hyper >>> g = hyper.PeriodicGrid(4,4,1) >>> g.__reduce__() (,(4.,4.,1.)) >>> import pickle >>> pickle.dump(g,file("test","w")) Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/sw/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/sw/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/sw/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/sw/lib/python2.4/pickle.py", line 414, in save_reduce save(func) File "/sw/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid >>> dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] >>> hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? Any help appreceated, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
Re: pickling extension class
On 18.01.2005, at 20:31, Alex Martelli wrote: harold fellermann <[EMAIL PROTECTED]> wrote: File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? These symptomps are pretty weird -- let's try to pin things down a bit more. The relevant few lines of pickle.py are: try: __import__(module) mod = sys.modules[module] klass = getattr(mod, name) except (ImportError, KeyError, AttributeError): raise PicklingError( so, could you please edit your pickle.py to provide VASTLY more info, [...] and let us know exactly what his modified pickle.py outputs...? Here it goes...: OOPS, error (exceptions.ImportError): No module named hyper Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 1387, in dump Pickler(file, protocol, bin).dump(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 231, in dump self.save(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 414, in save_reduce save(func) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 765, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid I have noticed that the error does not occur, when the imported module ('hyper') is in the same directory as the script that pickles. When it is imported from a subpackage (like in the code I sent you) it goes wrong. - harold - -- Reality is for people who lack imagination. -- http://mail.python.org/mailman/listinfo/python-list
Re: Class introspection and dynamically determining functionarguments
On 20.01.2005, at 12:24, Mark English wrote: I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to restrict the functionality to these requirements. I am working on nearly the same thing! Small sort of generic attribute editor in Tkinter (and Tix). Altough my implementation is still very unpythonic (== ugly) in many places, it can edit the attributes of instances and classes, as well as generate new instances / classes. I would like to create new attributes or delete them as well, but haven't done it so far. A still faraway dream would be, to allow the user to enter source code, that will be compiled into byte code and assign it to the instance, so the user can modify code at run time (if it is possible to disallow access to insecure modules while code is compiled). Secondly, the code won't know exactly how to initialise the class instance used to determinte the attributes. Do I need to make it a prerequesite that all instances can be created with no arguments ? I did it this way, too. Maybe you can provide a parameterless __new__ in addition to the __init__. I imagine this is the way that e.g. pickle does the job. Well, I don't know. Let this sentence just be an invitation for an expert to write something here. Should I force/allow the user to pass an instance instead of a class ? However you like. I prefer passing classes, otherwise you end up in a situation where you need to create dummy instances that are only used as "copying templates". If you get an instance: foo = type(bar)() would give you an instance of the same class as bar. But this just looks like a hack to me when compared to foo = Bar(). Passing an instance allows you to look at its __dict__ of course. But you have no assurance that the variables you find there are present in all instances of that class. Phython is just to dynamic for that. Should I be using inspect.getargspec on the class __init__ method and then a loop with a try and a lot of except clauses, or is there a nicer way to do this ? Presumably the pickling code knows how do serialise/deserialise class instances but I'm not sure how I'd use this without already having a class instance to hand. Personally, I ended up writing a class Attribute that provides access to the attributes and allows more finetuning than a generic approach would do (think of e.g. validation). My overall setting works like this: For each attribute that you want to appear in the GUI you define an Attribute class Attribute(object) : def __init__(self, name, # name of the attribute type, # specifies the widget type values=None,# then OptionMenu is used instead validate=None, # if given, a callable that returns # either True or False get=None, # callable to get the actual value # None: generic getattr() widget_options={} # passed to the Tix widget used ) : pass # [...] The "controller" of an editable object gets the object and a list of those Attribute()'s. There is a generic one that handles validation and generic setattr(), but can be overwritten to allow more sophisticated stuff. When creating a new instance, I ask for initial arguments which I know (like __name__ and __doc__ if its a class that I create) in nearly the same way. If you already have your instance, it is possible to generate the Attribute()-list from the dict of this instance: attributes = [ Attribute(name,type(getattr(instance,name))) for name in dir(instance) ] Lastly, does such an app already exist ? As you see, my solution is not as general as what you might have in mind. I needed to finetune so much of the underlying generic plan, that it looks more like declaration-based now. Anyway, if you are interested: This is the edit part of my app (It's only the mapping from attributes to widgets, so no instance creation in this part). As this was only a short snippet in the project I am doing, I could, never give it the time it deserved. So I am sure that my code is not the best sollution, but maybe it serves as a starting point for further discussion. All the best, - harold - import Tkinter import Tix class Attribute(object) : def __init__(self, name, type, values=None, validate=None, get=None, widget_options={} ) :
Re: eval() in python
> the doc seems to suggest that eval is only for expressions... it says > uses exec for statements, but i don't seem to see a exec function? Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> s="print 'hello Xah Lee :-)'" >>> exec(s) hello Xah Lee :-) >>> - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called "brightness", but it doesn't seem to work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals and parser
Hi, On 22.06.2005, at 23:18, Michael Barkholt wrote: > Is there any detailed documentation on the structure of Pythons > internals, > besides the source code itself? > > More specifically I am looking for information regarding the C parser, > since > I am looking into the viability of using it in another project that > needs > to parse python code (and I would like the code to be written in C). maybe this link might help you: http://wiki.cs.uiuc.edu/cs427/PYTHON -- "Wahrheit ist die Erfindung eines Lügners" -- Heinz von Foerster -- http://mail.python.org/mailman/listinfo/python-list
Re: I need help figuring out how to fix this code.
Hi, > I need help figuring out how to fix my code. I'm using Python 2.2.3, > and > it keeps telling me invalid syntax in the if name == "Nathan" line. The problem is that you indent the if statement. the if/elif/else statements are part of the outer block, so they do not need indentation. > Here is the code if you need it. > #This program asks for a password, then asks for the user's name > after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" name = raw_input("What is your name, plase? ") if name == "Nathan" : print "What a great name!" elif name in ["Madonna","Cher"] : # in better than == here :) print "May I have your autograph please!" else : # don't forget the ":" print name, ", thats a nice name!" cheers, - harold - -- You can imagine the opposite -- Maurizio Nannucci -- http://mail.python.org/mailman/listinfo/python-list
trace function calls to get signatures
Hi all, I am trying to write a script that prints out the signatures of each function call that occurs during the execution of a second script which is invoked by my program. i.e. if the inspected program is 'foo.py': def bar(x,y,z=None) : pass bar(1,"a",bar) bar(2,int) the output of my script should be: foo.bar(int,str,function) foo.bar(int,type,NoneType) I thought I go for sys.settrace() and achieved the following: import sys import types def tracefunc(frame,event,arg) : if event is 'call' : return trace_call(frame,event,arg) else : return None def trace_call(frame,event,arg) : code = frame.f_code scope = frame.f_locals try : print code.co_name+"("+",".join( [ str(type(scope[var])).split("'")[1] for var in code.co_varnames ] )+")" except KeyError : pass return None if __name__ == "__main__" : prog = sys.argv[1] sys.argv.pop(0) sys.settrace(tracefunc) __import__(prog) the output of the above example is: bar(int,str,function) bar(int,type,NoneType) which is pretty close, but I need / would like to improve several things, but have no idea how to do it: 1. I would like to have not only the name of the functions and type arguments but their full package/module/class-path, e.g. xml.dom.pulldom.PullDOM.clear However, I cannot find a way from the frame object to the function object where I could find the information. 2. The KeyError in my code is raised by the "from XXX import" statement: "from distutils import setup" results in File "tracetest.py", line 28, in ? __import__(prog) File "/Volumes/space/Users/harold/uni/pace/dpd/setup.py", line 1, in ? from distutils.core import setup, Extension File "tracetest.py", line 5, in tracefunc if event is 'call' : return trace_call(frame,event,arg) File "tracetest.py", line 12, in trace_call print code.co_name+"("+",".join( KeyError: 'setup' does anyone know how I can circumvent this? 3. Is there any way to set the __name__ attribute for the inspected script to "__main__", so that tracing is really transparent? 4. finally, does a functionality like this already exist in the library or did anyone of you come up with an implementation? thanks, - harold - -- Military intelligence is a contradiction in terms. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: Conditionally implementing __iter__ in new style classes
> I'm trying to implement __iter__ on an abstract base class while I > don't > know whether subclasses support that or not. > Hope that makes sense, if not, this code should be clearer: > > class Base: > def __getattr__(self, name): > if name == "__iter__" and hasattr(self, "Iterator"): > return self.Iterator > raise AttributeError, name > > class Concrete(Base): > def Iterator(self): > yield 1 > yield 2 > yield 3 I don't know how to achieve it, but why don't you simply use class Base: pass class Concrete(Base): def __iter__(self) : yield 1 yield 2 yield 3 What is the advantage to have a baseclass that essentially does some method renaming __iter__ ==> Iterator? - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: inheriting file object
On 06.07.2005, at 18:58, Jeremy wrote: > Hello all, > I am trying to inherit the file object and don't know how to do it. I > need to open a file and perform operations on it in the class I am > writing. I know the simple syntax is: > > class MyClass(file): > ... > > but I don't know how to make it open the file for reading/writing. Can > anyone help me out with this? just invoke file.__init__ inside your own init. if you don't need to do any initializiation in myFile.__init__, just leave the method and file.__init__ will be invoked automatically. class myFile(file) : def __init__(self,fname,mode="r") : file.__init__(self,fname,mode) for line in myFile('testfile') : print line - harold - -- If your only tool is a hammer, every problem looks like a nail. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: inheriting file object
> I don't know if I should be inheriting file or just using a file > object. > How would I determine which one would be more appropriate? Inheritance is often refered to as an IS relation, whereas using an attribute is a HAS relation. If you inherit from file, all operations for files should be valif for your class also. Usually the file-operations would be directly inherited and not overwritten. However, if you don't want to expose all file functionalities, a HAS relation is more appropriate. if you plan to use your class as a file handle, e.g. for formatting output in a special way, I woould prefer to make the file an attribute: class myFile : def __init__(self,fname,mode="r") : self.file = file(fname,mode) def write_formatted(self,string) : # format string self.file.write() If you would tell as your use case, it would be easier to give you an advice. - harold - -- Yesterday is but today's memory and Tomorrow is today's dream. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Cmd.exe Window
On 07.07.2005, at 15:25, Giles Brown wrote: > Nah. You're missing my point. I only want the command window not to > be closed if there is an *exception*. Picky I know, but there you go. well, then register raw_input as exit function: >>> import atexit >>> atexit.register(raw_input) works fine in my terminal. should do in your framework also. cheers, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Cmd.exe Window
On 07.07.2005, at 15:43, harold fellermann wrote: > On 07.07.2005, at 15:25, Giles Brown wrote: > >> Nah. You're missing my point. I only want the command window not to >> be closed if there is an *exception*. Picky I know, but there you go. > > well, then register raw_input as exit function: > >>>> import atexit >>>> atexit.register(raw_input) > > works fine in my terminal. should do in your framework also. sorry, I did not think. if you want to wait for input _only_ if an exception occured, your exit function needs to check for the exception: >>> import atexit >>> >>> def wait_on_exc() : ... import sys ... if sys.exc_type : ... raw_input() ... >>> atexit.register(wait_on_exc) this should do the job, now. - harold - -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing Something Simple
Hi, > I have a list of variables, which I am iterating over. I need to set > the value of each variable. My code looks like: > > varList = [ varOne, varTwo, varThree, varFour ] > > for indivVar in varList: > indivVar = returnVarFromFunction() > > However, none of the variables in the list are being set. You only change the value of the local variable in the body of the for loop. it has no effect on the list. you could do e.g. varList = [vorOne,varTwo,varThree,varFour] for i in len(varList) : varList[i] = returnVarFromFunction() However, as in this example the former list values are not used anyway, you could just write: varList = [ returnVarFromFunction for i varList ] cheers, - harold - -- Tages Arbeit, abends Gäste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe -- http://mail.python.org/mailman/listinfo/python-list
Re: Missing Something Simple
>>> I have a list of variables, which I am iterating over. I need to set >>> the value of each variable. My code looks like: >>> >>> varList = [ varOne, varTwo, varThree, varFour ] >>> >>> for indivVar in varList: >>>indivVar = returnVarFromFunction() >>> >>> However, none of the variables in the list are being set. >>> >> >> You only change the value of the local variable in the body >> of the for loop. it has no effect on the list. you could do e.g. >> >> varList = [vorOne,varTwo,varThree,varFour] >> for i in len(varList) : >> varList[i] = returnVarFromFunction() >> >> However, as in this example the former list values are not used >> anyway, >> you could just write: >> >> varList = [ returnVarFromFunction for i varList ] >> > The problem I have, is the variables are referenced elsewhere. They > have been declared before being used in the list. Basically, I'm > after the Python way of using deferencing. so, if I understand you right, what you want to have is a list of mutable objects, whose value you can change without changing the objects' references. class Proxy : def __init__(self,val) : self.set(val) def set(self,val) : self.val = val def get(self) : return self.val a = Proxy(1) b = Proxy(2) c = Proxy(3) varList = [a,b,c] for i in varList : i.set(returnVarFromFunction()) print a,b,c prints whatever returnVarFromFunction has returned. n.b.: instead of the Proxy class, you can use any other mutable objects, e.g. lists. - harold - -- "All unsere Erfindungen sind nichts als verbesserte Mittel zu einem nicht verbesserten Zweck." -- H.D. Thoreau -- http://mail.python.org/mailman/listinfo/python-list
Re: automatic form filling
> I would like to know how I could automatically fill a > (search) form on a web page and download the resulting > html page. More precisely I would like to make a > program that would automatically fill the "Buscador > lista 40" (in spanish, sorry) form in the following > webpage: > http://www.los40.com/actualidad/listas/lista40.html > and download the results for several dates > (dia/mes/año = day/month/year). > I am not sure this is the right place to ask, but I > would be very grateful if anybody can help or redirect > me to another mailing list... The relevant part of the sites source code is the following: from the first line you can see that submitting the result will request the page "busquedas_b.html" -- so your script has to request this site directly with the form parameters given as additional data (method="POST"). which form parameters to pass can be seen in the name attributes of the input-tags, e.g. . urllib provides the methods urlopen and urlencode to setup the query string and fetch the result: from urllib import urlopen,urlencode form_data = { 'byDay' : '12' , 'byMonth' : '07' , 'byYear' : '2005' } html_data = urlopen( "http://www.los40.com/actualidad/listas/busquedas_b.html";, urlencode(form_data) ).read() print html_data - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I import a py script by its absolute path name?
> for f in os.listdir(os.path.abspath(libdir)): > module_name = f.strip('.py') > import module_name > > Obviously, this throws: > > ImportError: No module named module_name > > Is there some way to do this? have a look at help(__import__) to import a module whose name is given as a string. - harold - -- Tages Arbeit, abends Gäste, saure Wochen, frohe Feste! -- Johann Wolfgang v. Goethe -- http://mail.python.org/mailman/listinfo/python-list
How to extend inner classes?
Thank you very much. Of course I know how to do it in python. The problem is that I want to reimplement these classes as a python extension in C. The question is: how can I add class members (like e.g. inner classes) to a PyTypeObject defined in a C extension? - harold - > You can define a class variable Pos with the class Pos as its value > > class PeriodicGrid : > class Pos: > pass > Pos = Pos > > >>> grid = PeriodicGrid() > >>> grid.Pos() > <__main__.Pos instance at 0x00EEFAD0> > > Ciao > Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Keyword arguments - strange behaviour?
Hi, I cannot see any strange behavior. this code works exacly as you and I suspect: >>> def otherfunction(x) : ... return x ... >>> def function(arg=otherfunction(5)) : ... return arg ... >>> function(3) 3 >>> function() 5 Or is this not what you excepted? - harold - On 21.12.2004, at 15:47, [EMAIL PROTECTED] wrote: def function(arg=otherfunction(value)): return arg My expectation would have been that otherfunction(value) would be called if (and only if) the arg keyword parameter was missing from the function() call (ie. the optional value is evaluated the lazy way). Also, otherfunction would be called each and every time this function() is called without the arg keyword. (At least, I would have assumed this before today) Still, I can see why it's been implemented the way it has, it just seems a shame there isn't a neat shortcut to default lots of optional arguments to new mutable objects. And since I'm not the only one to fall into this trap it makes me wonder why the default behaviour isn't made to be what most people seem to expect? -- http://mail.python.org/mailman/listinfo/python-list -- Freunde, nur Mut, Lächelt und sprecht: Die Menschen sind gut -- Bloß die Leute sind schlecht. -- Erich Kästner -- http://mail.python.org/mailman/listinfo/python-list
copying classes?
Hi all, In the documentation of module 'copy' it is said that "This version does not copy types like module, class, function, method, stack trace, stack frame, file, socket, window, array, or any similar types." Does anyone know another way to (deep)copy objects of type class? What is special about the objects of these types that they cannot be easily copied? Any help appreciated, - harold - -- I like pigs. Dogs look up to us. Cats look down to us. Pigs treat us as equal. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Re: copying classes?
On 30.12.2004, at 01:24, It's me wrote: I would not think that a generic deepcopy would work for all cases. An object can be as simple as a number, for instance, but can also be as complex as the universe. I can't imagine anybody would know how to copy a complex object otherthen the object itself. I always think that a well designed object should have a copyme method. :=) take a look at the __setstate__ and __getstate__ documentation of copy (e.g. pickle) -- with them you can customize the copying task. Anyway, they work only on instance but not on class objects :( - harold - -- Military intelligence is a contradiction in terms. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: property and virtuality
Hello, I asked this question some time ago, but as I got no answer, so I just try it a second time. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
class attributes and inner classes in C extensions
Hello, I just posted this question with a wrong subject... So here again with a better one. I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? Thanks for your help, - harold - -- Always remember that you are unique; just like everyone else. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I am working on a C extension module that implements a bunch of classes. Everything works fine so far, but I cannot find any way to implement class attributes or inner classes. Consider you have the following lines of Python : class Foo : class Bar : pass spam = "foobar" How can this class be translated to a C extension? Is there anything comparable to PyMethodDef that can be used for other attributes than functions? O.k. I found it out now, and in order to improve the knwoledge base of the mailing list, I will answer my question myself. The PyTypeObject structure has a field tp_dict that holds the dictionary of the class object. You can initialize it with a dictionary that holds class attributes. If you provide a custom dictiomary, you must do so _before_ PyType_Ready() is called, because PyType_Ready adds other entries to this dictionary. This is my C extension of the above. It works great for me: static PyTypeObject FooType = { /* ... snip ... */ 0, // tp_dict /* ... snip ... */ }; static PyTypeObject FooBarType = { /* ... snip ... */ }; PyMODINIT_FUNC inithyper(void) { /* the following lines add class attributes to the types tp_dict: */ FooType.tp_dict = PyDict_New(); PyDict_SetItemString(FooBarType,"Bar",(PyObject *)&FooBarType); PyDict_SetItemString(FooBarType,"spam",PyString_FromString("foobar")); PyObject* m; if (PyType_Ready(&hFooType) < 0) return; if (PyType_Ready(&hFooBarType) < 0) return; m = Py_InitModule3("my_module", NULL, "some documentation"); Py_INCREF(&FooType); PyModule_AddObject(m, "Foo", (PyObject *)&FooType); Py_INCREF(&hyper_FooBarType); PyModule_AddObject(m, "Bar", (PyObject *)&FooBarType); } Documentation for tp_dict can be found in the API: http://docs.python.org/api/type-structs.html - harold - -- "2x2 = grün" -- Heinz von Foerster -- http://mail.python.org/mailman/listinfo/python-list
Re: class attributes and inner classes in C extensions
I think you could as well, after PyType_Ready() is called, set it yourself with PyObject_SetAttrString(FooType, "Bar", FooBarType); You *may* have to cast the FooType and FooBarType to (PyObject *), to avoid compiler warnings. I tried this. Its shorter and and works fine, too. thanks for the proposal. - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called "brightness", but it doesn't seem to work. -- Gallagher -- http://mail.python.org/mailman/listinfo/python-list
Re: Class, object question.
What I am wondering is if I have a 2nd init or something similar to create a vector. Such as what follows and if I can how do I go about implementing it? Class vector(point): def __init___(self, point1, point2): self.i = point2.get_x() - point1.get_x() self.j = point2.get_y() - point1.get_y() self.k = point2.get_z() - point1.get_z() def __init___(self, i, j, k): self.i = i self.j = j self.k = k That way I can define a vector either using 2 points or if I have the vector data itself? Well, what you want to do -- polymorphism of function signatures -- can be implemented like this: class vector_1(point) : def __init__(self,*args) : if len(args) == 2 and isinstance(args[0],point) and isinstance(args[1],point) : self.i = args[0].get_x() - args[1].get_x() self.j = args[0].get_y() - args[1].get_y() self.k = args[0].get_z() - args[1].get_z() elif len(args) == 3 : self.i,self.j,self.k = args else : raise ValueError, "wrong arguments for instance initialization" You can also find a nice implementation by Guido van Rossum using decorators at Artima (look for multimethods). However, I would prefer to avoid this sort of polymorphism because it only obfuscates your code. IMHO, there should be exactly one clear way to initialize an instance. Therefore, I suggest the provide a class method that serves as a special instance factory: class vector_2(point) : def __init__(self,i,j,k) : self.i = i self.j = j self.k = k @classmethod def difference(cls,point1,point2) : return cls( point1.get_x() - point2.get_x(), point1.get_y() - point2.get_y(), point1.get_z() - point2.get_z() ) # how to use it: point1 = Point(4,5,6) point2 = Point(1,2,3) vec = vector_2.difference(point1,point2) I wonder, why your vector inherits from point though. And of course, class is written lower case. Cheers, - harold - -- Es ist schon längst alles gesagt worden -- aber noch nicht von jedem. -- Karl Valentin -- http://mail.python.org/mailman/listinfo/python-list
richcmpfunc semantics
Hi all, I want to implement rich comparision in an extension class. Problem is I cannot find good documentation of the richcmpfunc semantics. Given the signature richcmpfunc compare(PyObject *,PyObject, int); I supposed the two objects passed are the ones to be compared. What is the meaning of the integer argument? Does it specify the kind of comparision operator (e.g. __eq__ or __le__), and if so, how? What is my richcmpfunc supposed to return? 0 or 1 indicating False or True? What has to be done, if the function is invoked for an operator I don't want to define? Maybe there is some good documentation available, but I cannot find it. So, any references or help is appreciated. Cheers, - harold - -- "Scientist are very good in answering the questions they choose to answer." -- Richard Alley -- http://mail.python.org/mailman/listinfo/python-list
Re: richcmpfunc semantics
Thank you Greg, I figured most of it out in the meantime, myself. I only differ from you in one point. What has to be done, if the function is invoked for an operator I don't want to define? Return Py_NotImplemented. (Note that's return, *not* raise.) I used PyErr_BadArgument(); return NULL; instead. What is the difference between the two and which one is to prefer. Also, do you need to increment the reference count of Py_NotImeplemented before returning it? Thanks, - harold - -- I like pigs. Dogs look up to us. Cats look down to us. Pigs treat us as equal. -- Winston Churchill -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent string.find method for a list of strings
I have read a text file using the command lines = myfile.readlines() and now I want to seach those lines for a particular string. I was hoping there was a way to "find" that string in a similar way as searching simply a simple string. I want to do something like lines.find.('my particular string') Is there a module that already exists that allows me to do this or will I have to created my own method? file.readlines() returns a list of lines. You can either call find on each element in this list, like: for line in myfile.readlines() : if line.find('my particular string') : do_something() of just read in the whole file, if you are not interested in the particular line, where 'my particular string occurs': myfile.read().find('my particular string') Cheers, - harold - -- "All unsere Erfindungen sind nichts als verbesserte Mittel zu einem nicht verbesserten Zweck." -- H.D. Thoreau -- http://mail.python.org/mailman/listinfo/python-list
curses for different terminals
Hi all, I want to use curses in a server application that provides a GUI for telnet clients. Therefore, I need the functionality to open and handle several screens. Concerning http://dickey.his.com/ncurses/ncurses-intro.html#init this can be done using the function newterm(type,ofp,ifp). However, this function seems not to be defined in the python library. Does anyone know how this can be done in python? cheers, - harold - -- Life is what happens while you're busy making other plans -- John Lennon -- http://mail.python.org/mailman/listinfo/python-list
Re: curses for different terminals
On 14.04.2005, at 19:17, Christos TZOTZIOY Georgiou wrote: On Thu, 14 Apr 2005 18:39:14 +0200, rumours say that harold fellermann <[EMAIL PROTECTED]> might have written: Hi all, I want to use curses in a server application that provides a GUI for telnet clients. Therefore, I need the functionality to open and handle several screens. Just to make sure we understand what you want to do: 1. Are you doing an single process application that produces output on many terminals? ie the program is kind of like a service? gotcha. I want to write a TCP server that handles incoming requests in threads (one thread per request using SocketServer.ThreadingTCPServer). Now, I want the server to use curses for client-server communication (client will be telnet). Thus, my programm runs in a single process (although several threads) and provides several curses screens (one for each client.) Concerning http://dickey.his.com/ncurses/ncurses-intro.html#init this can be done using the function newterm(type,ofp,ifp). However, this function seems not to be defined in the python library. Does anyone know how this can be done in python? Select one of the above, or describe more the desired situation if I didn't cover your case, and we will try to help you more. great, thanks, - harold - -- Dieses Schreiben wurde maschinell erstellt und bedarf daher keiner Unterschrift. -- -- http://mail.python.org/mailman/listinfo/python-list
ScientificPython - LeastSquareFit diverges
Dear all, I am trying to fit a powerlaw to a small dataset using Scientific.Functions.LeastSquares fit. Unfortunately, the algorithm seems to diverge and throws an OverflowException. Here is how I try it: >>> from Scientific.Functions.LeastSquares import leastSquaresFit >>> >>> data = [ ... (2.5, 589.0, 0.10001), ... (7.5, 442.0, 0.10001), ... (12.5, 96.0, 0.10001), ... (17.5, 36.0, 0.10001), ... (22.5, 16.0, 0.10001), ... (27.5, 7.0, 0.10001), ... (32.5, 6.0, 0.10001), ... (37.5, 3.0, 0.10001), ... (42.5, 3.0, 0.10001), ... (47.5, 1.0, 0.10001), ... (52.5, 3.0, 0.10001), ... (57.5, 1.0, 0.10001), ... (67.5, 1.0, 0.10001), ... (77.5, 2.0, 0.10001), ... (82.5, 1.0, 0.10001), ... (87.5, 2.0, 0.10001) ... ] >>> >>> def powerlaw((a,b),x) : ... return a*x**b ... >>> params,chisq = leastSquaresFit(powerlaw,(10,-3),data) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py", line 72, in leastSquaresFit next_chi_sq, next_alpha = _chiSquare(model, next_p, data) File "/usr/lib/python2.4/site-packages/Scientific/Functions/LeastSquares.py", line 22, in _chiSquare f = model(parameters, point[0]) File "", line 2, in powerlaw File "/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py", line 182, in __rpow__ return pow(other, self) File "/usr/lib/python2.4/site-packages/Scientific/Functions/FirstDerivatives.py", line 171, in __pow__ raise OverflowError, "Numerical result of pow(%s,%s) out of range." % (self.value,other.value-1) OverflowError: Numerical result of pow(2.5,8376.79243687) out of range. >>> I added some debugging output in /usr/lib/python-2.4/site-packages/Scientifc/Functions/LeastSquares.py in the function _chiSquare that prints the fit parameters during the Levenberg-Marquardt iteration. The procedure seems do diverge after the first step: ((10, [1]), (-3, [0, 1])) [(-67402.311817579117, [1]), (8377.7924368716158, [0, 1])] Note that I could easily fit the above data using gnuplots internal fitting procedure. Any idea what is going wrong here? Is it a known problem? Are there any work arounds or other packages? Any help is appreciated! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter help
hi, groves wrote: > Now let me tell you that i was able to create a simple listbox which > had 6 options which one can select, but Now what I want is that from > the available menu, if I select an option it should give me another > menu associated with that option. Its like digging up that option to do > advance search. If I understood you correctly, this is how I would go for it: consider to create all submenus during initialization but make them invisible (put each of them in a single frame) anf toggle the visibility of these frames in the handler of your option menu. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: ScientificPython - LeastSquareFit diverges
Thanks for your advices, Terry and Konrad, using the linear fit as initial condition for the pawerlow fit works pretty well for my data. (I already had the two calculations but performed them vice versa ... :-) Anyway, I had the impression that the leastSquaresFit in Scientific Python is an implementation of the Levenberg Marquardt algorithm as it is presented in the Numerical Recipes. Accoring to reviews, this algorithm is not famous for its stability (e.g. http://www.stanford.edu/class/cme302/wnnr/nr.html). Better implementations are out there (e.g. http://www.ics.forth.gr/~lourakis/levmar/). Are there any plans to improve the SciPy algorithm? Would it be a welcome contribution to SciPy to work this part out? - harold - -- http://mail.python.org/mailman/listinfo/python-list
how to switch from os.tmpnam to os.tmpfile
Hi, I need to create a temporary file and I need to retrieve the path of that file. os.tmpnam() would do the job quite well if it wasn't for the RuntimeWarning "tmpnam is a potential security risk to your program". I would like to switch to os.tmpfile() which is supposed to be safer, but I do not know how to get the path information from the file object returned by tmpfile(). any clues? thanks! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: From Python to Shell
> Im not a total noob but i don't know the command and the module to go > from python to the default shell. there are several ways depending on what exactly you want to achieve: sys.exit(return_value): terminates the python process and gives controll back to the shell os.system(command_string): execute command string in a subshell. result is the return value of command_str subprocess.Popen(command): starts command as a subprocess and allows you to "communicate" with that process, i.e. lets you send something to its stdin and retrieve data from its stdout and stderr streams. have a look at the docs of that module for more information. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: how to switch from os.tmpnam to os.tmpfile
Maric Michaud wrote: > Le Jeudi 08 Juin 2006 15:30, Harold Fellermann a écrit : > > to os.tmpfile() which is supposed to be safer, but I do not know how to > > get > > the path information from the file object returned by tmpfile(). any > > clues? > There is no path for tmpfile, once it's closed, the file and its content are > lost. from the doc : > " The file has no directory entries associated with it and will be > automatically deleted once there are no file descriptors for the file." > > You must maintain a reference to it in your program untill you don't need it > anymore. I am doing so. But still, I need its path. To give you some context: I have an app built on Tk that uses gnuplot behind the scenes. My application creates a temporary file where which gnuplot writes its results to (using the tkcanvas terminal). Later, I load the contents of that file into the a tk canvas. I don't care about the temporary file after my app is closed, so I have its reference all the time. But I need its path to tell both gnuplot and tk where to read/write data to/from. class PlotWindow(Tk.Canvas) : def plot(self,commands) : tmp = os.tmpnam() gnuplot = subprocess.Popen( "gnuplot", shell=True, stdin=subprocess.PIPE, stdout=file(tmp,"w") ) stdout,stderr = gnuplot.communicate(""" set terminal tkcanvas interact set output "%s" """ % tmp + commands) assert not stderr self.tk.call("source",tmp) self.tk.call("gnuplot",self._w) Of course, I could just use matplotlib or Gnuplot.py but the problem is not necessary enough to make any refacturing. If there is no way to use os.tmpfile(), I just go ahead with the security warning. Its only a small personal app, anyway. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: how to switch from os.tmpnam to os.tmpfile
Chris Lambacher wrote: > You should be able to find exactly what you need in the tempfile module. > http://docs.python.org/lib/module-tempfile.html thanks! tempfile.NamedTemporaryFile() is exaclty what I have been looking for. Using python for such a long time now, and still there are unknown goodies in the library, great :-) - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching and manipulating lists of tuples
MTD wrote: > Hello, > > I'm wondering if there's a quick way of resolving this problem. > > In a program, I have a list of tuples of form (str,int), where int is a > count of how often str occurs > > e.g. L = [ ("X",1),("Y",2)] would mean "X" occurs once and "Y" occurs > twice > > If I am given a string, I want to search L to see if it occurs already. > If it does, I find the corresponding tuple and increment the integer > part. If not, I append the new element with int = 1. > > e.g. > > algorithm(L, "X") would produce output L = [("X",2),("Y",2)] > algorithm(L,"Z") would produce L = [("X",1),("Y",2),("Z",1)] > > I tried to create an algorithm of the following form: > >>> def algorith(list,str): > ... flag = True > ... for l in list: > ... if l[0] == str: > ... l[1] += 1 > ... flag = False > ... if flag: > ... list.append((str,1)) > ... > > > But: > > >>> algorith(L,"X") > > gives: > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 5, in algorith > TypeError: object does not support item assignment Your approach does not work because the tuples in the list a imutable. The problem occurs in the line l[1] += 1. You could solve the problem by using lists of lists, rather than lists of tuples. However, if you only want to know the frequency of items in the list (i.e. want to build a histogram) and you are not interested in the original order of items in the list, a dictionary is suited better for this task, because you avoid the linear time behavior of: def histogram(liste) : result = {} for item in liste : result[item] = result.get(item,0) + 1 return result.items() -- http://mail.python.org/mailman/listinfo/python-list
Re: mp3 libs and programs
hi, Jay wrote: > I'm writing a python script that involves playing mp3 files. The first > approach I had was sending commands to unix command-line programs in > order to play them. I tired mpg123 and moosic, but there was a key > feature to my program's success that's missing. SEEK! I need to be > able to start playing a song at an arbitrary point in the song. I > can't find anything to let me do this. Does anyone have any advice or > has anyone needed something similar? check out pyxmms. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about extending the interperter
> The problem for me is that the pointer "p" in the last function points > to the arguments: > If a user caller foo("123") - p points to '123'. > What I need is to point it to the whole string received - 'foo > ("123")'. > > Is there a way I can do this? no. at least not a simple one. you can obtain the function name by func_name, as the corresponding python code suggests: >>> def f() : ... pass ... >>> print f.func_name f However, you still don't know, how the function has been invoked. Consider: >>> g=f >>> print g.func_name f of course, the situation can be much more sphisticated. f could be a value in a dict returned by some other function, and so on. Of course there are ways to inspect the source code (like pdb or exceptions do), but are you sure this is the functionality to want? Cheers, - harold - -- Learn from the mistakes of others. You can't live long enough to make them all yourself. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Declaring self in PyObject_CallMethod
Hi, > Calling a python method from C++ has the following signature: > > PyObject * > PyObject_CallMethod(PyObject *self, char *method_name, > char *arg_format, ...); > > I'm having trouble figuring out how to declare self. > > Let's say my python file is called stuff.py and is like the following, > doMath() is defined in stuff.py and is not part of any class: > > #stuff.py > > def doMath(): >val = val + 1 > > > In C++, I think my codes should be like the following: > > PyObject *resultObj = PyObject_CallMethod( self, "doMath", ""); > > What do I put for self? Any help please? it looks like you are confusing methods (bound to class objects) and functions (bound to modules). if your doMath is a function defined in a module, use PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw) i.e. PyObject resultObj = PyObject_Call(doMath,NULL,NULL); If, however, doMath is declared as a class-bound method, you have to use PyObject_CallMethod() with a pointer to an instance of this class as the first argument. Cheers, - harold - -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
Hi, > I want a reliable way of knowing when the child > thread finished execution so that I can make the main thread wait till > then. > > Any ideas? use a lock. the subthread allocates the lock and releases it after processing. the main thread must wait until the lock is released. otherwiese, use the higher level Threading module which provides a function Thread.join that allows the main thread to wait for the subthread. I think it uses the same mechanism that I explained above. - harold - -- Outside of a dog, a book is a man's best friend: and inside a dog, it's too dark to read. -- Groucho Marx -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
we had some off-group mails. A summary is posted to improve the knowledge base of the list. Prashanth wrote: > Hi, > > I can use the threading module but I am just looking if there is a > reliable way using the thread module. > > If I use a lock... > Let us assume that the child thread has done a lck.release() but does > not get a chance to quit before execution is whisked away from it and > given to the main thread. Now the main thread sees that the lock has > been released and quits. The child thread hasn't quit yet and we are > back in the same problem. > > Don't you think? Harold wrote: I think it depends on when you release the child lock. if you do it after refering to any data, e.g. as the last command in the child thread, you should be on the save side, no? - harold - > Yes, I can assume that in most cases. However I don't think it happens > so always. Even though infinitesimal, there is still a chance that it > will not quit. I am looking for a mechanism using which I can make > sure. I don't understand what you mean. Why should the following code fail in any case? import thread def parentThread() : lock = thread.allocate_lock() child = thread.start_new_thread(childThread,(parent,)) lock.acquire() def childThread(parent) : parent.lock.acquire() do_something_with_vars_from(parent) parent.lock.release() # don't do anything with parents vars after releasing the lock I did not test it, but I cannot see any reason why this should fail. > After the childThread executes parent.lock.release() execution may be > taken away from it and given to the parent thread(note that the child > thread hasn't quit yet). The parent thread which is waiting on the > lock gets released and quits. Now the "still running" child thread > tries to exit and based on my assumption attempts to call some cleanup > func in some module which has been GC'ed due to the exit of the parent > thread. This leads to an exception being thrown. o.k. with this assumption, things might become a little more tricky. one possibility: bind the modules you use to local variables in your child thread. then they won't be GC'ed before childThread stops. or (better): use Threading. it really isn't complicated to change your code and timing issues become much simpler. Referencing the module locally on the child thread does not seem like an elegant solution besides I don't know which modules are involved in cleaning up. Yes, I will use the Threading module but am just curious as to what can be done to reliably use thread module. -- http://mail.python.org/mailman/listinfo/python-list
Re: redirecting messgaef from sys.stdout
On 07.06.2005, at 16:43, Ahmad Hosseinzadeh wrote: > Hello, > > I’m trying to run an external program in my > application. Both are coded in python. I need to write > an independent module that is used in the main > application. Its responsibility is to run the external > program and redirect its stdout and stderr to the main > application. > The application’s stdout and stderr are set to an > object and they are not command prompt anymore. > The output is selected by a flag; if true the stdout > and stderr will be redirected to application’s stdout > and stderr. If false, the stdout and stderr will be > redirected o command prompt. I don’t know how to > redirect the output. > Can anyone help please? have a look at: http://www.python.org/doc/current/lib/module-popen2.html -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I know when a thread quits?
On 07.06.2005, at 16:44, harold fellermann wrote: > import thread > > def parentThread() : > lock = thread.allocate_lock() > child = thread.start_new_thread(childThread,(parent,)) > lock.acquire() > > def childThread(parent) : > parent.lock.acquire() > do_something_with_vars_from(parent) > parent.lock.release() > # don't do anything with parents vars after releasing the lock > > > I did not test it, but I cannot see any reason why this should fail. > >> After the childThread executes parent.lock.release() execution may be >> taken away from it and given to the parent thread(note that the child >> thread hasn't quit yet). The parent thread which is waiting on the >> lock gets released and quits. Now the "still running" child thread >> tries to exit and based on my assumption attempts to call some cleanup >> func in some module which has been GC'ed due to the exit of the parent >> thread. This leads to an exception being thrown. >> Referencing the module locally on the child thread does not seem like an >> elegant solution besides I don't know which modules are involved in >> cleaning I wander how much an issue this fear really is. To my understanding, this situation can only happen, when the child thread accessess a module that was imported locally within the parent thread. Does anyone with a better understanding of the internals of the interpreter know whether such a thing can occur? If so, in what circumstances? - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 15:52, Xavier Décoret wrote: > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have a=A() > and I want to write a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? the short answer is: no. the long answer: if you write >>> a=A() an instance of class A is created and bound to the local identifier 'a'. If you later write >>> a=5 the object 5 is reassigned to the same identifier, deleting whatever value was stored there before. The identifier itself does not impose any restrictions on the type of instances that can be bound to it. Binding an instance of class A in the first part, does not make the identifier of the kind 'can-only-bind-A-instances'. In other words: identifiers don't have types. Thus, there is no mechanism that allows to change the binding behavior of identifiers. As a general advise, don't try to write C++ in python. I think, for most cases, there are far better solutions than changing the assign operator anyway... explicit is better than implicit: If class A has only one dedicate value and no internal state, make it a construcotr call: >>> a=A(5) Otherwise, it is worth mentioning the name of the member to set. IMHO this increases the readability of your source code: >>> a.pressure=5 Cheers, - harold - -- "I was born not knowing and have had only a little time to change that here and there." -- Richard Feynman -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
> to return 'WHERE name LIKE %smith%'I have tried using escapes, > character codes for the % sign, and lots of other gyrations with no > success. The only thing that works is if I modify searchterm first: > >searchterm = 'smith' >searchterm ='%'+'smith'+'%' >sql += 'WHERE name LIKE %s' % searchterm > > Any Ideas? >>> "%%%s%%" % "here you go" '%here you go%' Cheers, - harold - -- If your only tool is a hammer, every problem looks like a nail. -- -- http://mail.python.org/mailman/listinfo/python-list
extending Python base class in C
Hi all, I once read that it is possible to use a python base class for a C extension class. To be precise, I want to achieve the following behavior: class PythonClass : pass class CClass(PythonClass) : "this class should be implemented as C extension" pass Unfortunately, google could not find me the right reference. Does anyone know how to do it, or where I can find relevant information? Thanks, - harold - -- Je me suis enfermé dans mon amour -- je rève. -- Paul Eluard -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling assignation
On 13.06.2005, at 19:23, Terry Reedy wrote: > > "harold fellermann" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> if you write >>>>> a=A() >> an instance of class A is created and bound to the local identifier >> 'a'. > > I think it perhaps better to think of the label 'a' being bound to the > object rather than vice versa. For one, a label can only be bound > (stuck > to, like a stick note) to one object at a time while one object can > have > many labels (and other references) stuck to it. > >> If you later write >>>>> a=5 >> the object 5 is reassigned to the same identifier, > > Or one could say that the label 'a' is removed from the A() object and > reassigned to the 5 object. Since the 5 object may have numerous other > connections, and since those connections are unaffected by the new > connection to 'a', whereas the previous assignment of 'a' is broken, I > think it better to say that 'a' is being reassigned, not 5. yeah. I have never seen it this way, but you are right! Binding the identifier/label to the object is a much better perspective. thanks for the lesson :) - harold - -- Ceci n'est pas une signature. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: translating C++ exceptions to python
On 13.06.2005, at 13:23, [EMAIL PROTECTED] wrote: > Hi all, > > I have a C++ library I call from python. The problem is I have c++ > exceptions that i want to be translated to python. I want to be able to > do stuff like: > try: > my_cpp_function() > except cpp_exception_1: > do_stuff > except cpp_exception_2: > do_other_stuff > > any ideas how can i do the translation? If you do not already use it, have a look at http://www.boost.org/libs/python/ a C++ -- library to wrap the Python C API, i.e. it helps you to extend Python in C++. AFAIK it has fascilities to transform exceptions from one type into the other. - harold - --- Everybody lies. but it does not matter, as no one listens. --- -- http://mail.python.org/mailman/listinfo/python-list
Problem with simple C extension
Am I stupid or what? I want to implement a very simple extension class in C (as I did it many times before...) The python equivalent of my class whould look like: class physics_DPD : def __init__(self,cutoff,friction,noise,dt) : self.cutoff = cutoff self.friction = friction self.noise = noise self.dt = dt That's all fir the start. Simple, heh? My C implementation is the following: #include #include "structmember.h" // PhysicsDPD instance structure typedef struct { PyObject_HEAD double cutoff; double friction; double noise; double dt; } hyper_PhysicsDPD; //-- // tp_init //-- static int hyper_PhysicsDPD_init(hyper_PhysicsDPD *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args,"", &self->cutoff, &self->friction, &self->noise, &self->dt )) return -1; printf("%f %f %f %f\n",self->cutoff,self->friction,self->noise,self->dt); return 1; } //-- // method table //-- static PyMethodDef hyper_PhysicsDPD_methods[] = { {NULL} /* Sentinel */ }; //-- // instance members //-- static PyMemberDef hyper_PhysicsDPD_members[] = { {"cutoff", T_DOUBLE, offsetof(hyper_PhysicsDPD,cutoff), 0, "cutoff radius"}, {"friction", T_DOUBLE, offsetof(hyper_PhysicsDPD,friction), 0, "friction"}, {"noise", T_DOUBLE, offsetof(hyper_PhysicsDPD,noise), 0, "noise"}, {"dt", T_DOUBLE, offsetof(hyper_PhysicsDPD,dt), 0, "time step"}, {NULL} /* Sentinel */ }; //-- // type structure //-- static PyTypeObject hyper_PhysicsDPDType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "simulation.hyper.physics_DPD", /* tp_name */ sizeof(hyper_PhysicsDPD), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE ,/* tp_flags */ "DPD physics", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ hyper_PhysicsDPD_methods, /* tp_methods */ hyper_PhysicsDPD_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)hyper_PhysicsDPD_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* freefunc tp_free */ 0, /* inquiry tp_is_gc */ 0, /* PyObject *tp_bases */ 0, /* PyObject *tp_mro */ 0, /* PyObject *tp_cache */ 0, /* PyObject *tp_subclasses */ 0, /* PyObject *tp_weaklist */ 0, /* destructor tp_del */ }; //-- // module hyper //-- static PyMethodDef hyper_methods[] = { {NULL} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inithyper(void) { PyObject* m; m
Re: Problem with simple C extension
On 14.06.2005, at 18:58, harold fellermann wrote: > Am I stupid or what? Yes I was ... > // PhysicsDPD instance structure > typedef struct { >PyObject_HEAD >double cutoff; >double friction; >double noise; >double dt; > } hyper_PhysicsDPD; > > > // > // tp_init > // > static int > hyper_PhysicsDPD_init(hyper_PhysicsDPD *self, PyObject *args, PyObject > *kwds) > { >if (!PyArg_ParseTuple(args,"", > &self->cutoff, > &self->friction, > &self->noise, > &self->dt > )) > return -1; > >printf("%f %f %f > %f\n",self->cutoff,self->friction,self->noise,self->dt); > >return 1; > } format string must be "" - as the members are defined as doubles, not floats. Sorry to bother you. - harold - -- A country without army is like a fish without bicycle. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: extending Python base class in C
> "harold fellermann" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > Hi all, > > I once read that it is possible to use a python base class for a C > extension class. On 14.06.2005, at 09:29, Grigoris Tsolakidis wrote: > There was good article of how to do this on DDJ home page www.ddj.com unfortunately, I could not find it yet. I managed to do the following: I the initmodule function of my extension, I import the module and look for the class I want to use as a base class: PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; This gives me a pointer to the class I want to use as base class. Does anyone know how to assign this to the extension class? I tried to build a tuple (BaseClass,) and assign it (after the respective PyType_Ready call) to CClass.__bases__ like this: PyObject_SetAttrString( &cclassType, "__bases__", Py_BuildValue("(O,)",base_class) ); but this raises a TypeError when executed during import: TypeError: can't set attributes of built-in/extension type 'ext_module.CClass' Any ideas how to proceed? - harold - -- You can imagine the opposite -- Maurizio Nannucci -- http://mail.python.org/mailman/listinfo/python-list
Re: extending Python base class in C
Yah! Finally, I got the thing to work. Here is how I did it. /* import the module that holds the base class */ PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; /* get a pointer to the base class */ PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; /* assign it as base class */ cclassType.tp_bases = Py_BuildValue("(O)",BaseClass); I am doing all this before the call to PyType_Ready() -- as Scoot Daniels suggested. Using the python API's SetAttrString() did not work (I suppose for the same reason, why assigning cls.__bases__ does not work in pure python either). I also checked cclassType.tp_base = (PyTypeObject *) base_class; which also works and I am not aware of the difference of these two slots. Anyway, for my simple purposes it works just fine. - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." -- http://mail.python.org/mailman/listinfo/python-list
Re: dir() with string as argument
On 16.06.2005, at 20:59, Shankar Iyer ([EMAIL PROTECTED]) wrote: > Hi, > > Suppose I have a string, sModuleName, that contains the name of a > module. I now want to see what functions are in that module, but if I > call dir(sModuleName), I instead get the list of operations that can > be done on a string. Is there any way to convert the string into a > format that I could feed to dir to cause the desired effect? I think > I could modify the string a bit and then use the exec command, but I > was advised against that on this board last week. you have to import the module: name = "sys" mod = __import__(name) dir(mod) - harold - -- Bitte verlassen Sie diese Welt so, wie Sie sie vorfinden möchten. -- -- http://mail.python.org/mailman/listinfo/python-list
Re: design question: no new attributes
Hi Alan, > One last point. While I remain interested in examples of how > "late" addition ofattributesto class instances is useful, > I must note that everyone who responded agreed that it > has been a source of bugs. This seems to argue against a > general ban on "locking" objects in some way, in some > circumstances. If you want to restrict "late" addition of attributes, no-one will prevent you to do so. Arnaud has already given you an example implementation. Here is mine: >>> class Foo(object) : ... ... _locked = False ... ... def __setattr__(self,attr,var) : ... if self._locked and not attr in dir(self): ... raise RuntimeError ... else : ... object.__setattr__(self,attr,var) ... ... def lock(self) : ... self._locked = True ... >>> foo = Foo() >>> foo.bar = 'allowed' >>> foo.lock() >>> foo.spam = 'fails' Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __setattr__ NotImplementedError >>> >>> foo.bar = 'still works' See how it works? The lock method *dynamically* adds the attribute foo._locked *after* initialization to the instance. Before the call of foo.lock() foo._locked is a class attribute. Now you might argue that one should better set foo._locked = False in the __init__ method rather than as a class attribute. Something like: class Foo(object) : def __init__(self) : self._locked = False But no! The initialization would trigger Foo.__setattr__(foo,'_locked',False) which naturally runs into an attribute error since __setattr__ looks up this attribute. So this very same implementation is one of the pro examples you asked for :-) cheers, - harold - -- http://mail.python.org/mailman/listinfo/python-list
passing options to __import__
Dear list, I looked through the list but could not find any solutions for my current problem. Within my program, I am importing a module via __import__(module_name,globals(),locals()) and I want to pass comand line options to this module. I would prefer not to save them in a config module or a Config class but rather use the globals and locals dictionaries that are given to __import__. Unfortunately, they don't show up in the globals or locals in the module. Even setting them specifically by params = globals() params['module_opts'] = module_opts __import__('my_module',params,locals()) does not work. When I put the debug statement print 'module_opts' in globals() into my_module, it prints 'False'. Unfortunately, the docs for __import__ are a bit vague about the precise role of the globals argument. Is there any way, to acheive what I am trying, or do I need to fall back on a config module/class? Thanks! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Better writing in python
Hi Alexandre, On Oct 24, 2:09 pm, Alexandre Badez <[EMAIL PROTECTED]> wrote: > I'm just wondering, if I could write a in a "better" way this code Please tell us, what it is you want to achieve. And give us some context for this function. > lMandatory = [] > lOptional = [] > for arg in cls.dArguments: > if arg is True: > lMandatory.append(arg) > else: > lOptional.append(arg) > return (lMandatory, lOptional) This snippet will seperate d.Arguments into two lists: one that holds all elements that are references to True(!) and another list that holds the rest. The condition 'if args is True' will only be hold if arg actually _is_ the object _True_. This is probably not what you want. Apart from that, you might go with lMandatory = [ arg for arg in cls.dArguments if condition() ] lOptional = [ arg for arg in cls.dArguments if not condition() ] the second line could be rewritten lOptional = list(set(cls.dArguments)-set(lMandatory)) If lMandatory and lOptional do not need to be lists, you can also write lMandatory = set(arg for arg in cls.dArguments if condition()) lOptional = set(cls.dArguments) - lMandatory But please, give us some more context of what you want to do. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Protocols for Python?
[EMAIL PROTECTED] wrote: > Still, I'm designing an application that I want to be extendable by > third-party developers. I'd like to have some sort of documentation > about what behavior is required by the components that can be added to > extend the application. I'd thought I might try documenting these > behaviors as "protocols" instead of creating abstract classes with no > method implementations. Use doc strings :-) They are easy to learn, easy to understand (once you learned how to write meaningful ones, that is), integrated into the core language and supported by IDEs and editors. Combine a good documentation with proper exception handling and extending your application will be easy. Bateries inluded, you know. -- http://mail.python.org/mailman/listinfo/python-list
Re: python game with curses
Jerry, if you want anyone to answer your question, please read this: http://www.catb.org/~esr/faqs/smart-questions.html -- http://mail.python.org/mailman/listinfo/python-list
__getattr__ for global namespace?
Hi, I am writing an application that initializes the global namespace, and afterwards, leaves the user with the python prompt. Now, I want to catch NameErrors in user input like e.g. >>> some_name Traceback (most recent call last): File "", line 1, in ? NameError: name 'some_name' is not defined For classes, there are the __getattr__ and __getattribute__ functions. I wonder if there is some related function for (failed) global attribute lookup that is invoked with name as its argument instead. I consulted the docs, but could not find anything. Any ideas? - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ for global namespace?
Great! sys.excepthook() is exactly what I was looking for. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I do this with python ?
Better go for the subprocess module. It is supposed to replace os.popen and has a much nicer interface. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: redirecting print to a a file
>>> import sys >>> sys.stdout = file("output","w") >>> print "here you go" -- http://mail.python.org/mailman/listinfo/python-list
scientific libraries for python
Hi all, I want to use the current need for a Levenberg-Marquardt least squares fitting procedure for my long term desire to dive into scientific libraries for python. However, I am always confused by the shear sheer variety of available packages and the fact that some of them (Numeric, Numarray) seem to be outdated. http://wiki.python.org/moin/NumericAndScientific gives a nice overview of the most popular packages. According to this listing, ScientificPython and PyDSTool seem most appropriate for what I generally work on (simulations of dynamical systems and data analysis). Before I start to dive into one of these packages (I would go for ScientificPython from what I know so far), I want to ask about your experiences. Is there a good reason to choose one instead of the other? Or do they even work together, in the sense that I can use PyDSTool to generate data to be later analyzed by ScientifPython without much timeconsuming conversion a.s.o. in between? Thanks for any suggestions! - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: what is the difference between tuple and list?
The main difference is that lists are mutables while tuples are not. Tuples are fine if you only want to group some objects (e.g. as a return value) and access their members as in >>> t = (1,2,3,4) >>> t[2] 3 Lists give you a lot more flexibility, because they are mutable: you can change the order of elements (e.g. sort), or delete or append items (all that this is not possible for tuples). These features make lists the primary data structures for stacks, queues, a.s.o. So, whenever you want to change what objects are in your collection or their ordering, use lists, otherwise, use tuples. Note, that this does not mean, that the items themselves cannot be changed. You can perfectly well change an object (e.g. dictionary) that resides in a tuple: >>> t = ({},) # tuple with empty dict as its only item >>> t[0]["foo"] = "bar" But if you e.g. want to exchange, that dictionary by another, you need to go for a list instead of a tuple. Hope that made sense... - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Help System For Python Applications
I usually go for the webbrowser package that allows me to launch the systems webbrowser and opens my html help files. It is really simple: >>> import webbrowser >>> webbrowser.open("file:///path_to/help.html#topic") and thats all there is to do. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: sorting a list slice
Fredrik Lundh wrote: > George Sakkis wrote: > > > It would be useful if list.sort() accepted two more optional > > parameters +1 > useful for what? what's the use case ? Actually, I was in need of such a construct only few weeks ago. The task was to organize playlists of an mp3 player. I wanted to sort future entries but not past ones (according to an index in the list that seperates past from future). I can imagine many more situations in which sorting part of a list is usefull. While I agree that the improvement of the additional keywords is minor, I think that the additional load they impose on the sort function is also minor. In my oppinion, this is a straight-forward extension of what we already find in other places in the library. I would like to see it in a future version. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with the strip string method
> Thanks to all respondents, Steve Holden > is right, I expected more than I should > have. Others have explained why all your examples work as they should. >From your exmaples, it seems like you would like strip to remove the leading and trailing characters from EVERY LINE in your string. This can be done by the simple construct >>> my_string = ' foo\n bar ' >>> '\n'.join(line.strip() for line in my_string.split('\n')) 'foo\nbar' If you need this construct at several places, define a function def line_strip(string,sep='\n') : return sep.join(line.strip() for line in string.split(sep)) cheers, - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating classes and objects more than once?
On Nov 27, 6:42 pm, Viktor Kerkez <[EMAIL PROTECTED]> wrote: > Is this a bug? It is not a bug: the dictionaries are different because they are loaded from different modules. >>> import os >>> import test.data >>> test.data >>> os.chdir('test') >>> import data >>> data >>> test.data is data False -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
On Dec 4, 10:39 am, Cong Ma <[EMAIL PROTECTED]> wrote: > Lawrence D'Oliveiro wrote: > > for \ > > Entry \ > > in \ > > sorted \ > > ( > > f for f in os.listdir(PatchesDir) if PatchDatePat.search(f) != > > None > > ) \ > > : > > Patch = (open, > > gzip.GzipFile)[Entry.endswith(".gz")](os.path.join(PatchesDir, Entry), "r") > > ... read from Patch ... > > Patch.close() > > #end for > > The "if ... != None" is not necessary... "if PatchDatePat.search(f)" is OK. > And I don't like it... Maybe the whole if clause is not necessary? This is how I would try it: for Entry in filter(PatchDatePat.search, os.listdir(PatchesDir)) : fname = os.path(PatchesDir, Entry) Patch = file(fname) if fname.endswith('.gz') else GzipFile(fname) # ... read from Patch ... Patch.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling, sum-comprehension vs reduce
> doesnt sum first construct the list then sum it? > def com(lst): > return sum(x for x in lst) You construct a generator over an existing list in your code. Try sum([x for x in lst]) to see the effect of additional list construction. And while you're at it, try the simple sum(lst). Cheers, - harold - -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Linear Programming on Ubuntu
> > http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > Scroll down. > > Yes, many of those seem to be deprecated, without destinations to > links, most are poorly or not documented at all. The few that are, I > still can't get running. Of those 254, I think I have tried at least > 10 pages worth. Still no luck. > > # lpsolvpy - Can't get it to compile - dependency problems. > # Lp_solve5 - NO python binding yet. Volunteers needed for python > bindings. > # pycplex - You need to compile the CPX.so module. Change the required > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > sure what to do here. > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > I missed the second link to the python bindings, looked all over the > glpk site for anything about python. > # SciPy -- http://www.scipy.org - supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. > # pySimplex - (broken link)(broken link) > # Simplex - link is broken, but nothing is mentioned > > I'll take a closer look at glpk's python bindings and if there is any > documentation on them, maybe I'll have some luck. btw, I have been > looking for something that works, I have over 5 packages on my desktop > that I have tried to get up and running, but none of them seem to > work. glpk makes 6. You are right that this is an unsatisfying experience. Fortunately, the referred site is a wiki. Why don't you edit it and delete the broken links or add the package that did the job for you to the list, so that others do not need to go through the same hassle. - harold - -- http://mail.python.org/mailman/listinfo/python-list
Problem combining Scientific (leastSquaresFit) and scipy (odeint)
Hi, I need to perform leastSquaresFit of a model that is given by a differential equation for which there seems to be no analytic solution. So, I am trying to solve the ODE numerically (using scipy.integrate.odeint) within the function I provide to leastSquaresFit as a model: def func(L, t, a, k) : return -k * L * (1 - ( 1 - a*L**(-1./3) )**3.) def model((k, L0, a), t) : solution = odeint( func, array(L0[0]), array([0,t]), args=(a,k) ) return L0 - solution[1][0] params, chisq = leastSquaresFit(model, params, data) Unfortunately, this approach runs into an error (ValueError: shape mismatch: objects cannot be broadcast to a single shape) that seems to stem from the fact that leastSquaresFit is based on automatic derivation (DerivVar), and according to the manual "the function [that defines the model] may only use the mathematical functions known to the module FirstDerivatives". What is a good solution or workaround to this problem which appears to be quite a standard situation to me? Thanks for any help, harold. -- http://mail.python.org/mailman/listinfo/python-list