Re: how to add a string to the beginning of a large binary file?
could ildg wrote: I want to add a string such as "I love you" to the beginning of a binary file, How to? and how to delete the string if I want to get the original file? You shouldn't use Python to write a virus :-) -pu -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Shell Editor Question
The Python shell you get with IDLE is actually not a system shell like cmd.exe or sh, bsh, csh etc. It is a shell that allows the Python interpreter to evaluate each line of Python code as you type. This is why when you type 'hello.py' it tells you 'hello.py' is not defined. On a higher level it simply tells you: you haven't initialized this object called hello.py in memory and therefore the error. Also you can't run python anything because in the interpreter python *hasn't* been assigned any value. Also, you can't quit the Python interpreter shell by typing exit. You'll need to do a Control-D & Enter ;-) Hope this makes sense. Good luck. Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: save configuration information in a global class
Su Wei <[EMAIL PROTECTED]> wrote: > if i have a xml file like this: > > > > > > i want to save this information,and used by other moduls later. > > how should i do it? ths First you need an xml library. There's one built into Python, but ElementTree is a simpler one: http://effbot.org/zone/element-index.htm I've saved your text into a file named 'temp.xml': py> print open('temp.xml').read() Now let's parse that file: py> from elementtree import ElementTree py> actionmappings = ElementTree.parse('temp.xml').getroot() py> for action in actionmappings: ... print action.attrib ... {'path': 'cpuInformation', 'type': 'CPUAction', 'next': 'CPUFrameGUI'} {'path': 'cdromInformation', 'type': 'CDROMAction', 'next': 'CDROMFrameGUI'} Note that I now have an object that I've named 'actionmappings' which contains all the data I need. How do you want the information from the XML file to be available? If you're happy navigating the XML structure, you can just pass this object around. If you included the code above in a module called, say, 'progconfig', then you could access this info in another file like: improt progconfig # the following should give you 'cpuInformation' progconfig.actionmappings[0].attrib['path'] If you don't like the format the XML file gives you, you'll need to give us more information on how you'd like to reformat it. STeVe P.S. Please make sure you reply to the list. I probably won't be able to answer again tonight, but someone else on the list may... -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get TabError?
"Mr. Magoo" wrote: >> $ python -t test.py >> test.py: inconsistent use of tabs and spaces in indentation >> hello >> goodbye > > On more question. When using py_compile from with a script, is there any > way to force the -t flag? if you want to check for tab problems from inside a script, use the tabnanny module: http://effbot.org/librarybook/tabnanny.htm -- http://mail.python.org/mailman/listinfo/python-list
Re: save configuration information in a global class
Su Wei <[EMAIL PROTECTED]> wrote: > if i want to make a global class to save configuration information of > app that is read from a xml file,what can i do? Just put it in a module. Say, 'progconfig.py'. Your configuration code can then look like: import progconfig # parse configuration information from an XML file for name, value in configuration_information: setattr(progconfig, name, value) Now all you have to do to use this information is to import the same module in your other modules, e.g.: import progconfig # do whatever you normally do in this module, e.g. if progconfig.sayhello: print "say hello" STeVe -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: how to get the class instance given a module object?
Tian wrote: import ModuleA classname = "Dog" module = globals()["ModuleA"] classobj = ??? <---using classname instanct = classobj() classobj = getattr(module, classname) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Newbie Shell Editor Question
Hi Everyone, I am new to python. I have just installed it. I am went to the python website and used it to download python and a beginners tutorial. I set the environment variables as explained in the faq. However when I start idle and run a program from it; I get the following types of errors; however I can run the same programs no problem from my command prompt. Can anyone please tell me what I am doing wrong? I thought Idle was used to test programs in. I am able to open a new window and write code, save it and then run that code; but just not if I type it into the main idle window directly. Any help would greatly appreciated, thank you. Kash This is my error: IDLE 1.1 >>> python hello.py SyntaxError: invalid syntax >>> python hello SyntaxError: invalid syntax >>> exit 'Use File/Exit or your end-of-file key to quit IDLE' >>> print "Hello" Hello >>> hello Traceback (most recent call last): File "", line 1, in -toplevel- hello NameError: name 'hello' is not defined >>> hello.py Traceback (most recent call last): File "", line 1, in -toplevel- hello.py NameError: name 'hello' is not defined >>> -- http://mail.python.org/mailman/listinfo/python-list
newbie question: how to get the class instance given a module object?
I have a module called ModuleA.py, in which there is a class called Dog, what should I put in the "" part to get the instance of class Dog??? import ModuleA classname = "Dog" module = globals()["ModuleA"] classobj = ??? <---using classname instanct = classobj() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to organize source code and "import"s???
Tian wrote: I also have some problem about the "import". How should I design my packages? Say, I have all code locates at c:\projects\sami, "c:\project" is in my PYTHONPATH environment variable. Suppose my folder structure is like this: c: projects\ <-this directory is in PYTHONPATH sami\ __init__.py main.py xmlparser.py window.py proc.py support\ __init__.py helper.py plugins\ __init__.py BaseClass.py<---no instance for this one ExtClassA.py ExtClassB.py ExtClassC.py ExtClassD.py Each file in \projects\sami\plugins contains a class with a same name as the file, (ExtClassA.py has class ExtClassA), the instance of these classes need to be created at runtime while functions in xmlparser.py is parsing an XML file. main.py is the start point of the program. Other files in the \projects\sami\ and projects\sami\support are supporting modules. 1. What should I write in each __init__.py ??? If I understand your intent correctly here, you shouldn't need anything in any of them. In "main.py", if I need functions in "proc.py", should I write "import proc"? If I need functions in "helper.py", can i write "import support.helper"?? No, you should use absolute imports and write: import sami.proc import sami.support.helper or perhaps import sami.proc as samiproc import sami.support.helper as samihelper 2. What is the best way to make instance of a class from a string type name? Why do you expect to need to do this? Usually you can just import the class's module directly and then use getattr, e.g.: py> modules = [__import__('sami.plugins.%s' % filename[:-3], ... globals(), locals(), ['ExtClass']) ...for filename in os.listdir('sami/plugins') ...if filename.endswith('.py') ...and filename not in ['BaseClass.py', '__init__.py']] py> modules [, ] py> modules[0] py> modules[0].ExtClass py> getattr(modules[0], 'ExtClass') See the documentation for __import__ for more details[1]. But How can I import all "ExtClass?.py"? I would do this as above, using __import__. STeVe [1] http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Doug Helm wrote: > form = cgi.FieldStorage() > if lobjUp.Save('filename', 'SomeFile.jpg'): > class BLOB(staticobject.StaticObject): > def Save(self, pstrFormFieldName, pstrFilePathAndName): > form = cgi.FieldStorage() You are instantiating cgi.FieldStorage twice. This won't work for POST requests, because instantiating a FieldStorage reads the form data from the standard input stream (the HTTP request). Try to create a second one and cgi will try to read all the form data again; this will hang, waiting for the socket to send it a load more data which will not be forthcoming. When using CGI, parse the input only once, then pass the results (a FieldStorage object if you are using the cgi module) in to any other functions that need to read it. -- Andrew Clover mailto:[EMAIL PROTECTED] http://www.doxdesk.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to add a string to the beginning of a large binary file?
On Sunday 27 March 2005 07:56 pm, could ildg wrote: > I want to add a string such as "I love you" to the beginning of a binary > file, How to? and how to delete the string if I want to get the original > file? There are many ways. Define large. -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Overriding methods in classes you don't control
Look up "Aspect Oriented Programming" and Python. You should find several packages that can do this, together with discussions of how to make cuts and all that fun stuff. The feeling of power is very heady - until you have to maintain the resulting mess. John Roth "Alex VanderWoude" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Is there a way to override a method on a class whose source you cannot change in such a way that you can hook into that method's code? After doing some research, it appears that one way to do such a thing is to create a new (non-class) method, and then assign the new method to the class in question, thus replacing the existing class method. However, I have read vague hints in the documentation that this is not a good thing to do (?). Furthermore, you probably need access to the source code of the method you are replacing so that you can duplicate and modify it in your method. Now in this particular case that is true, but what I really want to know is whether or not there is an accepted Pythonic way to do this. Here's the situation. I'm using wxPython, and I want to make an enhancement in the __init__ method of all the frame classes. The ideal place to do this is in wxFrame.__init__, since any change there will automatically be inherited by the other frame classes (for example, wxMDIParentFrame). Obviously I can inherit from wxPython and make the changes in my subclass, but then I would have to also subclass wxMDIParentFrame and duplicate my enhancements there, and then use only my subclasses rather than the wx*** classes. Basically I want to change wxFrame.__init__ so that it looks sort of like this: def __init__(self, *args, **kwargs): # Some enhancements here. # The original code of this method, including the call to its ancestor. # Some more enhancements here. And then I can replace wxFrame's __init__ with my new version by assigning it before any frames are instantiated. Now I can do this since I have access to the wxPython source code. However, I would prefer to have some generalized way of grabbing the original code and inserting it where that middle comment is. That way, my enhancements will continue to work even with other versions of wxPython (assuming of course that my enhancements don't rely on anything in the original code, which they don't). Or am I barking up the wrong tree entirely? - Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: How to organize source code and "import"s???
"Tian" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] I am writing a python program which needs to support some plug-ins. I have an XML file storing some dynamic structures. XML file records some class names whose instance needs to be created in the run time while parsing the XML file. I wonder what is the best solution for this problem? I also have some problem about the "import". How should I design my packages? Say, I have all code locates at c:\projects\sami, "c:\project" is in my PYTHONPATH environment variable. Suppose my folder structure is like this: c: projects\ <-this directory is in PYTHONPATH sami\ __init__.py main.py xmlparser.py window.py proc.py support\ __init__.py helper.py plugins\ __init__.py BaseClass.py<---no instance for this one ExtClassA.py ExtClassB.py ExtClassC.py ExtClassD.py Each file in \projects\sami\plugins contains a class with a same name as the file, (ExtClassA.py has class ExtClassA), the instance of these classes need to be created at runtime while functions in xmlparser.py is parsing an XML file. main.py is the start point of the program. The solution to most dynamic import issues lies in the __import__() function, which is the very first function documented in the built-in functions page. I've found that keeping it as simple as possible helps a lot. Just load the module, get the address of the top level module from the __import()__ function, and use getattr() to trace down the chain of modules to the class you want to access. Other files in the \projects\sami\ and projects\sami\support are supporting modules. 1. What should I write in each __init__.py ???f Nothing. In "main.py", if I need functions in "proc.py", should I write "import proc"? If I need functions in "helper.py", can i write "import support.helper"?? what else should I do to support all these? If you know you're going to need something, just import it. There's no need to get fancy unless you've got import loops. Then you need to break them and do the other accesses dynamically after the modules have finished loading. 2. What is the best way to make instance of a class from a string type name? One method I have successfully tried is using "from SomeWhere import *", then get class from globals() and make instance. Use the getattr() function. But How can I import all "ExtClass?.py"? Where should I write these import codes? If you want to import all the names in a module, look in the module's __dict__. That's not recommended, however. If you want to import all the modules in a directory, then you need to read the directory (see the os module) and import them individually. John Roth -- http://mail.python.org/mailman/listinfo/python-list
Re: Overriding methods in classes you don't control
Alex VanderWoude wrote: Basically I want to change wxFrame.__init__ so that it looks sort of like this: def __init__(self, *args, **kwargs): # Some enhancements here. # The original code of this method, including the call to its ancestor. # Some more enhancements here. And then I can replace wxFrame's __init__ with my new version by assigning it before any frames are instantiated. Maybe you can do something like: oldinit = wxFrame.__init__ def newinit(self, *args, **kwargs): # Some enhancements here. oldinit(self, *args, **kwargs) # Some more enhancements here. wxFrame.__init__ = newinit that is, save the old __init__ method so that it can be accessed from within your new __init__ method. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Overriding methods in classes you don't control
On Mon, 28 Mar 2005 03:57:16 GMT, Alex VanderWoude <[EMAIL PROTECTED]> wrote: >Is there a way to override a method on a class whose source you cannot > change in such a way that you can hook into that method's code? After doing > some research, it appears that one way to do such a thing is to create a new > (non-class) method, and then assign the new method to the class in question, > thus replacing the existing class method. However, I have read vague hints > in the documentation that this is not a good thing to do (?). Furthermore, > you probably need access to the source code of the method you are replacing > so that you can duplicate and modify it in your method. Now in this > particular case that is true, but what I really want to know is whether or > not there is an accepted Pythonic way to do this. > > Here's the situation. I'm using wxPython, and I want to make an enhancement > in the __init__ method of all the frame classes. The ideal place to do this > is in wxFrame.__init__, since any change there will automatically be > inherited by the other frame classes (for example, wxMDIParentFrame). > Obviously I can inherit from wxPython and make the changes in my subclass, > but then I would have to also subclass wxMDIParentFrame and duplicate my > enhancements there, and then use only my subclasses rather than the wx*** > classes. > > Basically I want to change wxFrame.__init__ so that it looks sort of like > this: > > def __init__(self, *args, **kwargs): > # Some enhancements here. > # The original code of this method, including the call to its > ancestor. > # Some more enhancements here. > > And then I can replace wxFrame's __init__ with my new version by assigning > it before any frames are instantiated. from thirdparty.project import Something orig = Something.meth def new(x, y, z): foo() orig(x, y, z) bar() Something.meth = new HTH, Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: Python List Issue
Thanks, thats a really handy function "Ron_Adam" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > On Sun, 27 Mar 2005 09:01:20 GMT, "Nick L" <[EMAIL PROTECTED]> > wrote: > > >I've hit a brick wall on something that I'm guessing is pretty simple but > >it's driving me nuts. > > Yes, I've ran across that too a few times. > > >How on earth can I make a complete seperate copy of a list with out it > >being a attached to the original in any way shape or form so that I can > >modifiy if at will and not worry about the original? > > This routine copies a list of lists. > > > # Makes a copy of a list of lists > # Containing simple data. > def copylistlist(alist): > if type(alist) is list: > copy = [] > for i in alist: > if type(i) is list: > i = copylistlist(i) > copy.append(i) > return copy > > bob = [[[0, 0]]] > final = copylistlist(bob) > > print 'bob:'bob > print 'Final:'final > > > This still doesn't create new items within the new list. but with > literal data consisting of letters and numbers, it will work. > > If you are working with a data tree, you may be able to modify this to > do what you want. Just add a test in the inner loop for the data you > want to modify. > > > >Any ideas, suggestions, comments are greatly appreciated > >thanks > > > >Nick > > Hope that helps. > > Ron_Adam > > -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting matrixes
Here's the solution to previous post. --- perl code: sub sort_matrix($$) { my $ref_matrix = $_[0]; my @indexMatrix = @{$_[1]}; my @indexes = map {$_->[0]} @indexMatrix; my @operators = map {$_->[1] ? ' cmp ' : ' <=> '} @indexMatrix; my @directions = map {$_->[2]} @indexMatrix; my $body_code = ''; my @body_array; for (my $i = 0; $i <= $#indexes; $i++) { if ($directions[$i]) { push(@body_array, "(\$a->[$i]" . $operators[$i] . "\$b->[$i])"); } else { push(@body_array, "(\$b->[$i]" . $operators[$i] . "\$a->[$i])"); }; }; $body_code = join( ' or ', @body_array); my $array_code = '(map { [' . join(q(, ), map {"\$_->[$_]"} @indexes) . ', $_]} @$ref_matrix)'; my $code = "map {\$_->[-1]} (sort { $body_code} $array_code)"; my @result = eval $code; return [EMAIL PROTECTED]; }; -- Python code # python v 2.4 def sort_matrix(matrix, directives): result=matrix for dir in directives: if dir[1]: if dir[2]: result.sort(lambda x,y: cmp( str(x[dir[0]]), str(y[dir[0]])) ) else: result.sort(lambda x,y: cmp( str(x[dir[0]]), str(y[dir[0]])), None, True) else: if dir[2]: result.sort(lambda x,y: cmp(float(x[dir[0]]), float(y[dir[0]])) ) else: result.sort(lambda x,y: cmp(float(x[dir[0]]), float(y[dir[0]])), None, True ) return result m = [ [3, 99, 'a'], [2, 77, 'a'], [1, 77, 'a'] ] print sort_matrix(m,[ [2,True,True], [1,False,True] ]) The Python code has not been tested much. http://xahlee.org/perl-python/sort_matrix.html Xah [EMAIL PROTECTED] â http://xahlee.org/PageTwo_dir/more.html â -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
Jp Calderone wrote: On Sun, 27 Mar 2005 14:39:06 -0800, James Stroud <[EMAIL PROTECTED]> wrote: "ATT/GATA/G" gets split to [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] I have written a very ugly function to do this (listed below for the curious), but intuitively I think this should only take a couple of lines for one skilled in regex and/or listcomp. Any takers? >>> import re >>> s = 'ATT/GATA/G' >>> re.findall('(./.|.)', s) ['A', 'T', 'T/G', 'A', 'T', 'A/G'] >>> If it is really important to have ['A'] instead of 'A', etc, looping over the result and noticing strings of length 3 vs length 1, then applying the appropriate transformation, should be simple enough. >>> [x.split('/') for x in ['A', 'T', 'T/G', 'A', 'T', 'A/G']] [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] >>> /m -- http://mail.python.org/mailman/listinfo/python-list
How to organize source code and "import"s???
I am writing a python program which needs to support some plug-ins. I have an XML file storing some dynamic structures. XML file records some class names whose instance needs to be created in the run time while parsing the XML file. I wonder what is the best solution for this problem? I also have some problem about the "import". How should I design my packages? Say, I have all code locates at c:\projects\sami, "c:\project" is in my PYTHONPATH environment variable. Suppose my folder structure is like this: c: projects\ <-this directory is in PYTHONPATH sami\ __init__.py main.py xmlparser.py window.py proc.py support\ __init__.py helper.py plugins\ __init__.py BaseClass.py<---no instance for this one ExtClassA.py ExtClassB.py ExtClassC.py ExtClassD.py Each file in \projects\sami\plugins contains a class with a same name as the file, (ExtClassA.py has class ExtClassA), the instance of these classes need to be created at runtime while functions in xmlparser.py is parsing an XML file. main.py is the start point of the program. Other files in the \projects\sami\ and projects\sami\support are supporting modules. 1. What should I write in each __init__.py ??? In "main.py", if I need functions in "proc.py", should I write "import proc"? If I need functions in "helper.py", can i write "import support.helper"?? what else should I do to support all these? 2. What is the best way to make instance of a class from a string type name? One method I have successfully tried is using "from SomeWhere import *", then get class from globals() and make instance. But How can I import all "ExtClass?.py"? Where should I write these import codes? -- http://mail.python.org/mailman/listinfo/python-list
Overriding methods in classes you don't control
Is there a way to override a method on a class whose source you cannot change in such a way that you can hook into that method's code? After doing some research, it appears that one way to do such a thing is to create a new (non-class) method, and then assign the new method to the class in question, thus replacing the existing class method. However, I have read vague hints in the documentation that this is not a good thing to do (?). Furthermore, you probably need access to the source code of the method you are replacing so that you can duplicate and modify it in your method. Now in this particular case that is true, but what I really want to know is whether or not there is an accepted Pythonic way to do this. Here's the situation. I'm using wxPython, and I want to make an enhancement in the __init__ method of all the frame classes. The ideal place to do this is in wxFrame.__init__, since any change there will automatically be inherited by the other frame classes (for example, wxMDIParentFrame). Obviously I can inherit from wxPython and make the changes in my subclass, but then I would have to also subclass wxMDIParentFrame and duplicate my enhancements there, and then use only my subclasses rather than the wx*** classes. Basically I want to change wxFrame.__init__ so that it looks sort of like this: def __init__(self, *args, **kwargs): # Some enhancements here. # The original code of this method, including the call to its ancestor. # Some more enhancements here. And then I can replace wxFrame's __init__ with my new version by assigning it before any frames are instantiated. Now I can do this since I have access to the wxPython source code. However, I would prefer to have some generalized way of grabbing the original code and inserting it where that middle comment is. That way, my enhancements will continue to work even with other versions of wxPython (assuming of course that my enhancements don't rely on anything in the original code, which they don't). Or am I barking up the wrong tree entirely? - Alex -- http://mail.python.org/mailman/listinfo/python-list
how to add a string to the beginning of a large binary file?
I want to add a string such as "I love you" to the beginning of a binary file, How to? and how to delete the string if I want to get the original file? thanks. -- http://mail.python.org/mailman/listinfo/python-list
File Uploads -- Windows Server
I should have been more clear in my subject line. I was also the poster in the "File Uploads" topic. I'm not having any luck getting file uploads to work (multi-part HTML form) on a Windows server. I'm using a very close approximation of public domain code that I found. I've tried a couple of different implementations (very similar), but I am essentially using the following test code: http://www.voidspace.org.uk/python/cgi.shtml#upload which does *not* work on my Windows / IIS server. I have CGIs (py and pyc files) configured as follows: C:\Python\Python.Exe -u %s %s C:\Python is (of course) where Python is installed on my machine. -u allows for binary data to be processed (I believe) I'm not sure what %s %s does (would be nice to know...) Anyway, I believe I have write permissions in the directory that I'm trying to write (and would expect an error if I didn't)... I'm not getting any error. I submit a multi-part form to save a file attachment to disk, and the post just hangs. Does anyone have any ideas on this? Has anyone made CGI file uploads work in a Windows / IIS environment? Thanks much for any help that you can provide. Doug -- http://mail.python.org/mailman/listinfo/python-list
Newbie Printing Question
I'm just starting to work with Python. Have had a little experience with basic. I am using Python on a Windows XP system. How to I print a line of output generated in a python script to a printer attached to the windows computer? -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
Ron Garret wrote: In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: Why don't you just write a function to create class objects? def f(*params): class C(...): ... # based on params return C I suppose I could. When I originally started writing this code I wanted each of the generated classes to have its own name, and I didn't realize that you could accomplish this by assigning to cls.__name__ after you created it. Yeah, that's what I'd do: py> def f(name): ... class C(object): ... pass ... C.__name__ = name ... return C ... py> f('D') py> f('Foo') STeVe -- http://mail.python.org/mailman/listinfo/python-list
Use informative subject lines! (was Re: Dumb*ss newbie Q)
A subject line should say what the message is about, for example "Create HTML tag using objects (newbie Q)" and enable people who are not interested in or knowledgable about a topic to skip it, while grabbing the attention of people who are knowledgable/interested. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
On Sun, 27 Mar 2005 14:39:06 -0800, James Stroud <[EMAIL PROTECTED]> wrote: >Hello, > >I have strings represented as a combination of an alphabet (AGCT) and a an >operator "/", that signifies degeneracy. I want to split these strings into >lists of lists, where the degeneracies are members of the same list and >non-degenerates are members of single item lists. An example will clarify >this: > >"ATT/GATA/G" > >gets split to > >[['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] Here's two ways without using regular expression. Both about the same. s = list("ATT/GATA/G") result = [] while len(s)>0: a = [s.pop(0)] if s[0] == '/': b = s.pop(0) a.append(s.pop(0)) result.append(a) print result [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] s = "ATT/GATA/G" result = [] while len(s)>0: if s[1:2] == '/': result.append([s[0],s[2]]) s = s[3:] else: result.append([s[0]]) s = s[1:] print result [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
Brian van den Broek wrote: Much nicer than mine. =| :-) ^ | (hats off) Cool ascii art (but thanks for the translation)! Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
In article <[EMAIL PROTECTED]>, Steven Bethard <[EMAIL PROTECTED]> wrote: > Ron Garret wrote: > > I need to dynamically generate new types at run time. I can do this in > > two ways. I can use the "type" constructor, or I can generate a "class" > > statement as a string and feed that to the exec function. The former > > technique is much cleaner all else being equal, but I want to be able to > > specify the __slots__ class variable for these new types, and it seems > > that to do that I need to use the latter method. Is that true? Is it > > really impossible to specify __slots__ using the "type" constructor? > > Why don't you just write a function to create class objects? > > def f(*params): > class C(...): > ... # based on params > return C I suppose I could. When I originally started writing this code I wanted each of the generated classes to have its own name, and I didn't realize that you could accomplish this by assigning to cls.__name__ after you created it. So I started down the road of using the type constructor. But there's not really a good reason for it now. Maybe I'll go back and change my code. rg -- http://mail.python.org/mailman/listinfo/python-list
passing input to running loop
I'm still very new to Python, after decideding to learn a true programming language (rather then a scripting language, i like to think i'm a intermediate PHP user). I decided for my first project I would try to make a IRCbot. It would run on the commandline with a frontend for commands such as "reconnect", "quit", "changeserver", etc. My problem is while I have the bot to a state where it connects to the server (with the use of IRCLib), I don't know how to have the frontend interface with the program while the irc connection loop is in the background. My thoughts are that I could have each of the loops running on a diffrent thread while events watch the channel for the bots commands (!op etc.). Only problem I have no idea on how to implement these ideas or even if this is the right way to go about it. So I'm asking if anyone has a good threading or event tutorial, or if they would show me the basics in a post. I'm also asking if I should be going about this problem in this fashion at all. Thanks for any help, lotmr Code for the client (not including irclib): -note: im using 'pass' as a placeholder for future IRC commands -note2: the code in comments is an example of how I would like the frontend to work in the end. (except without pausing the loop which is what happens right now as it waits for input). #!usr/bin/python #Filename: NIRC Core import sys import irc def giveop(user): pass def ip(): pass def uptime(): pass def auth(user,password,ip): pass def kill(user): pass def mute(user): pass def servertest(): pass NIRC=irc.IRC_Object( ) conn=NIRC.new_connection( ) s = raw_input('Enter Start Command : ') if s == 'quit': quit() if s == 'ircstart': conn.nick='Nilzirc' conn.ident='nilzirc' conn.server=('irc.deltaanime.net', 6667) conn.realname='Noobwrangler McNeal' print 'Connection Started' while 1: NIRC.main_loop( ) #n = raw_input('Enter Bot Commands : ') #if n == 'quit': #break print 'Ending IRC communication' -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
In article <[EMAIL PROTECTED]>, Leif K-Brooks <[EMAIL PROTECTED]> wrote: > Ron Garret wrote: > > I need to dynamically generate new types at run time. I can do this in > > two ways. I can use the "type" constructor, or I can generate a "class" > > statement as a string and feed that to the exec function. The former > > technique is much cleaner all else being equal, but I want to be able to > > specify the __slots__ class variable for these new types, and it seems > > that to do that I need to use the latter method. Is that true? Is it > > really impossible to specify __slots__ using the "type" constructor? > > Using __slots__ with type() works for me: > > Python 2.3.5 (#2, Feb 9 2005, 00:38:15) > [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> FooClass = type('foo', (object, ), {'__slots__': 'foo'}) > >>> foo = FooClass() > >>> foo.bar = 1 > Traceback (most recent call last): >File "", line 1, in ? > AttributeError: 'foo' object has no attribute 'bar' > >>> foo.foo = 2 Well, whaddya know. I don't know how I got the idea that this didn't work. Maybe I left out an underscore when I tried it. Thanks! rg -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
On Sunday 27 March 2005 05:04 pm, Michael Spencer wrote: > >>> def group(src): > ... stack = [] > ... srciter = iter(src) > ... for i in srciter: > ... if i == "/": > ... stack[-1].append(srciter.next()) > ... else: > ... stack.append([i]) > ... return stack Very pretty: group("AGC/C/TGA/T") [['A'], ['G'], ['C', 'C', 'T'], ['G'], ['A', 'T']] -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb*ss newbie Q
On Mon, 28 Mar 2005 01:15:34 +, Jp Calderone wrote: > > Notice that you have a method named "url" as well as an attribute > named "url". You have the same problem for "thumb". These methods > and attributes are in collision with each other. When you try to > look up the attribute, you might get the method. When you try to > look up the method, you might get the attribute. It is > deterministic, but depends on the order in which you do things, and > highly confusing no matter what. Avoid naming attributes and > methods the same thing. DUH!!! works like a charm Thanks! -- use munged address above to email me SpamTrap [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
133+ Tutorials and counting...
..and there are more seemingly every day... Table of Contents Beginners (12) Database (6) Extending and Embedding (4) General and Advanced (15) Grimoire (1) GUI Programming: General and Miscellaneous (6) GUI Programming: Tkinter (4) GUI Programming: wxPython and PythonCard (7) GUI Programming: pyGTK and Gnome (6) GUI Programming: QT and KDE (1) HTML and XML (9) IDE's and Editors (4) Internet, CGI, and Web Frameworks (9) Jython (5) Mac and Apple (8) Math, Science, Physics and Bioinformatics (10) Microsoft Windows (6) Objects, Metaclasses and Introspection (3) References (8) Specific Topics including Sorting, Threads, RE, Curses, OpenOffice, RDF, ZeroConf, Console, Flash, Doxygen and PiPy(12) Testing, Test Driven Progamming, Unit Test (2) Unicode (2) at www.awaretek.com/tutorials.html -- http://mail.python.org/mailman/listinfo/python-list
Python Cookbook, 2'nd. Edition is published
See http://www.oreilly.com/catalog/pythoncook2/index.html I don't see it on Amazon yet, but you can order it from O'Reilly. Ron Stephens www.awaretek.com -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
Michael Spencer said unto the world upon 2005-03-27 20:04: James Stroud wrote: Hello, I have strings represented as a combination of an alphabet (AGCT) and a an operator "/", that signifies degeneracy. I want to split these strings into lists of lists, where the degeneracies are members of the same list and non-degenerates are members of single item lists. An example will clarify this: "ATT/GATA/G" gets split to [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] >>> def group(src): ... stack = [] ... srciter = iter(src) ... for i in srciter: ... if i == "/": ... stack[-1].append(srciter.next()) ... else: ... stack.append([i]) ... return stack ... >>> group("ATT/GATA/G") [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] >>> Michael Much nicer than mine. =| :-) ^ | (hats off) I've got to get iterators into my working vocabulary! Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Dumb*ss newbie Q
On Sun, 27 Mar 2005 17:06:05 -0800, Captain Dondo <[EMAIL PROTECTED]> wrote: > [snip] > > def url (self): > self.url = ... > > def thumb (self): > self.thumb = ... > > [snip] > > The problem is that m.html in the test section fails with > > TypeError: cannot concatenate 'str' and 'instancemethod' objects > > [snip] Notice that you have a method named "url" as well as an attribute named "url". You have the same problem for "thumb". These methods and attributes are in collision with each other. When you try to look up the attribute, you might get the method. When you try to look up the method, you might get the attribute. It is deterministic, but depends on the order in which you do things, and highly confusing no matter what. Avoid naming attributes and methods the same thing. Jp -- http://mail.python.org/mailman/listinfo/python-list
Dumb*ss newbie Q
OK, I know this is covered somewhere in Python 101, but for the life of me I cannot figure this out. I really need a basic intro to Python book I am trying to do something very simple - create an HTML tag using objects: class Movie: def __init__ (self, t="", a="", d=""): # # Create an instance of Movie # self.title = t self.audience = a self.driver = d def set_title (self, new_title): self.title = new_title def set_audience (self, audience): # # Only 3 valid values: kids, parents, guests # self.audience = audience def set_driver (self, new_driver): self.driver = new_driver def url (self): self.url = "avi://" + self.audience + "/" + self.title + "/" + self.driver def thumb (self): self.thumb = self.audience + "/tn/" + self.title + ".jpg" def html (self): print " " + self.title + "" # # Code to test this class # if __name__ == '__main__': print " Test 1 " m=Movie("Fate_is_the_Hunter") m.set_audience ("kids") m.set_title ("Fate_is_the_Hunter") m.set_driver ("X=hermes.seiner.lan:xv,athena.seiner.lan:xmga,default:x11;console=vesa") m.html () print "*** Finish ***" The problem is that m.html in the test section fails with TypeError: cannot concatenate 'str' and 'instancemethod' objects I got it working once. The output should be something like this: Fate_is_the_Hunter but then I made some minor edits and I can't get it to work again Where do I find documentation on Python classes? Or how do I convert one to the other? Or, how do I get the above to work? This is the first time I've really tried to work with a class I've defined myself and I obviously don't know what I am doing On a minor note, if you look at the audience method, I want to limit it to 3 values. How do I do that? TIA --Yan -- use munged address above to email me SpamTrap [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
James Stroud wrote: Hello, I have strings represented as a combination of an alphabet (AGCT) and a an operator "/", that signifies degeneracy. I want to split these strings into lists of lists, where the degeneracies are members of the same list and non-degenerates are members of single item lists. An example will clarify this: "ATT/GATA/G" gets split to [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] >>> def group(src): ... stack = [] ... srciter = iter(src) ... for i in srciter: ... if i == "/": ... stack[-1].append(srciter.next()) ... else: ... stack.append([i]) ... return stack ... >>> group("ATT/GATA/G") [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] >>> Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get rid of FutureWarning: hex/oct constants...
On Sun, 27 Mar 2005 12:48:46 +0200, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= <[EMAIL PROTECTED]> wrote: >Bengt Richter wrote: >> >>> hex(-2*0x4000+0x40047a80) >> __main__:1: FutureWarning: hex()/oct() of negative int will return a signed >> string in Python 2.4 >> and up >> '0xc0047a80' >> >> That "signed string" is a unary minus expression using an absolute value >> forced by the inadequacy >> of the literal representation syntax. >> IOW, IMO '-' + hex_literal_of(abs(x)) is not a decent hex_literal_of(-x) !! > >This has been discussed over and over, but since you bring it up again: It seems you have a different concept of "this" than I ;-) > >There are no hex literals for negative numbers, just as there are no >decimal literals for negative number. A literal, by nature, in any >base, is non-negative. You are talking about what _is_, not what _can be_ ;-) IMO a literal is a source-context-compatible string representing an abstract value (which typically has an alternate representation in the running-program context). AFAIK there is no law against representing negative numbers as such with whatever literal spellings are deemed useful. > >If you disagree: Is 0xFFF6 a positive or a negative number? That is conventionally a positive number, because the python 2.4 hex syntax is interpreted that way, as it should be now. With a leading 16x prefix instead of 0x the rules would/could change. See below. I am trying to propose an alternate (additional, not replacement) syntax, which you could call base-complement. The base is specified by a prefixed x where is encoded in decimal. Zero is not a legal base, so there is no problem recognizing current hex literals. The digits following x result from the numeric value's being encoded with the base radix, and the most significant _must_ be zero or base-1 and may be repeated leftwards as far as desired without changing the value, which is computed by something like: For digits on the right side (following the x): >>> def bcdecode(s, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'): ... if s == digits[0]: return 0 ... acc = s[0].lower() == digits[B-1] and -B**len(s) or 0 ... for i, c in enumerate(s[::-1]): ... acc += digits.index(c)*B**i ... return acc ... For the whole literal (which you need, unless you are assuming you know the base and that first digits are sign or sign leftwards-replications according to base-complement convention) >>> def blitdec(s): ... xpos = s.lower().index('x') ... base = int(s[:xpos]) ... return bcdecode(s[xpos+1:], base) ... >>> blitdec('2x011') 3 >>> blitdec('2x0011') 3 >>> blitdec('2x101') -3 >>> blitdec('2x1101') -3 >>> blitdec('16x0fff6') 65526 >>> blitdec('16x6') -10 >>> hex(blitdec('16x0fff6')) '0xfff6' >>> hex(blitdec('16x6')) '-0xa' Urk! ;-/ For backwards compatibility, hex will have to do that, but there IMO there should be a base-complement output format available too, so e.g., (to give it a name) baselit(blitdec('16x6'), 16) => '16xf6' #(normalized to single sign digit unless explicitly formatted) BTW, >>> blitdec('8x03') 3 >>> blitdec('8x73') -5 >>> blitdec('10x03') 3 >>> blitdec('10x93') -7 The point is a bit-visualization-friendly literal representation (when desired, and for which you'd normally use base 2, 8, or 16 ;-) of all integers. And also it could be nice to be able to write (impossible now) >>> compiler.parse('x=16x6','single') and get Module(None, Stmt([Assign([AssName('x', 'OP_ASSIGN')], Const(-10))])) instead of (the result of what you have to write now) Module(None, Stmt([Assign([AssName('x', 'OP_ASSIGN')], UnarySub(Const(10)))])) BTW, I see the code above needs some cleaning and another .lower() or two but I am too lazy to fix or optimize, and the corresponding literal-formatting code is left as an exercise ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
James Stroud said unto the world upon 2005-03-27 17:39: Hello, I have strings represented as a combination of an alphabet (AGCT) and a an operator "/", that signifies degeneracy. I want to split these strings into lists of lists, where the degeneracies are members of the same list and non-degenerates are members of single item lists. An example will clarify this: "ATT/GATA/G" gets split to [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] I have written a very ugly function to do this (listed below for the curious), but intuitively I think this should only take a couple of lines for one skilled in regex and/or listcomp. Any takers? James p.s. Here is the ugly function I wrote: def build_consensus(astr): consensus = [] # the lol that will be returned possibilities = [] # one element of consensus consecutives = 0 # keeps track of how many in a row for achar in astr: if (achar == "/"): consecutives = 0 continue else: consecutives += 1 if (consecutives > 1): consensus.append(possibilities) possibilities = [achar] else: possibilities.append(achar) if possibilities: consensus.append(possibilities) return consensus Hi, in the spirit of "Now I have two problems" I like to avoid r.e. when I can. I don't think mine avoids a bit of ugly, but I, at least, find it easier to grok (YMMV): def build_consensus(string): result = [[string[0]]] # starts list with a list of first char accumulate = False for char in string[1:]: if char == '/': accumulate = True else: if accumulate: # The pop removes the last list appended, and we use # its single item to build then new list to append. result.append([result.pop()[0], char]) accumulate = False else: result.append([char]) return result (Since list.append returns None, this could use accumulate = result.append([result.pop()[0], char]) in place of the two lines in the if accumulate block, but I don't think that is a gain worth paying for.) HTH, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
Ron Garret wrote: I need to dynamically generate new types at run time. I can do this in two ways. I can use the "type" constructor, or I can generate a "class" statement as a string and feed that to the exec function. The former technique is much cleaner all else being equal, but I want to be able to specify the __slots__ class variable for these new types, and it seems that to do that I need to use the latter method. Is that true? Is it really impossible to specify __slots__ using the "type" constructor? Using __slots__ with type() works for me: Python 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> FooClass = type('foo', (object, ), {'__slots__': 'foo'}) >>> foo = FooClass() >>> foo.bar = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'foo' object has no attribute 'bar' >>> foo.foo = 2 -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
No, I am on a Linux server. I am not sure how CGI is configured because I do not control the server, I only use it. bye, Dimitri On Sun, 27 Mar 2005 16:19:00 -0700, Doug Helm <[EMAIL PROTECTED]> wrote: > Thanks, Dimitri. Yes, I found that same code too and tried it with the > exact same result as the code I've uploaded (just hangs). But, OK. You > have it working, so it must be a systems issue. Are you also on a Windows > IIS web server? Do you have CGI configured the same way (i.e. .py = > python.exe -u %s %s)? > > Thanks. > > Doug > > "dimitri pater" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > Maybe this helps: > > http://www.voidspace.org.uk/python/cgi.shtml#upload > > > > I use it, it works for fine me > > Maybe it will give you some clues on how to tweak your own script. > > > > Dimitri > > > > > > On Sun, 27 Mar 2005 10:32:20 -0700, Doug Helm <[EMAIL PROTECTED]> > wrote: > > > Hey, Folks: > > > > > > I'm trying to write a very simple file upload CGI. I'm on a Windows > server. > > > I *am* using the -u switch to start Python for CGIs, as follows: > > > > > > c:\python\python.exe -u %s %s > > > > > > I *do* have write permissions on the directory I'm trying to write to. > But, > > > when I click submit, it just hangs. Any help would be greatly > appreciated. > > > Thanks. Here's the code... > > > > > > Upload.py > > > > > > import cgi > > > > > > print "content-type: text/html\n\n" > > > > > > form = cgi.FieldStorage() > > > if not form: > > > print """ > > > > > > > > > > > > > > enctype="multipart/form-data"> > > > > > > > > > > > > > > > > > > """ > > > else: > > > import BLOB > > > lobjUp = BLOB.BLOB() > > > if lobjUp.Save('filename', 'SomeFile.jpg'): > > > print """ > > > > > > > > > > > > File successfully saved. > > > > > > > > > """ > > > else: > > > print """ > > > > > > > > > > > > Unable to save file. > > > > > > > > > """ > > > > > > -- > > > > > > Blob.py > > > > > > import cgi > > > import staticobject > > > > > > cTrue = 1 > > > cFalse = 0 > > > > > > try: > > > import msvcrt,os > > > msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 > > > msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 > > > except ImportError: > > > pass > > > > > > class BLOB(staticobject.StaticObject): > > > > > > def __init__(self): > > > self.initializing = cTrue > > > staticobject.StaticObject.__init__(self) > > > self.initializing = cFalse > > > > > > def Save(self, pstrFormFieldName, pstrFilePathAndName): > > > > > > # tried this first -- same result -- just hangs... > > > #try: > > > # form = cgi.FieldStorage() > > > # item = form[pstrFormFieldName] > > > # if item.file: > > > #data = item.file.read() > > > #f = open(pstrFilePathAndName,'wb') > > > #f.write(data) > > > #f.close() > > > #return cTrue > > > # else: > > > #return cFalse > > > #except: > > > # return cFalse > > > > > > form = cgi.FieldStorage() > > > f = open(pstrFilePathAndName,'wb') > > > f.write(form[pstrFormFieldName].value) > > > f.close() > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > -- > > Please visit dimitri's website: www.serpia.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Thanks, Dimitri. Yes, I found that same code too and tried it with the exact same result as the code I've uploaded (just hangs). But, OK. You have it working, so it must be a systems issue. Are you also on a Windows IIS web server? Do you have CGI configured the same way (i.e. .py = python.exe -u %s %s)? Thanks. Doug "dimitri pater" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Maybe this helps: > http://www.voidspace.org.uk/python/cgi.shtml#upload > > I use it, it works for fine me > Maybe it will give you some clues on how to tweak your own script. > > Dimitri > > > On Sun, 27 Mar 2005 10:32:20 -0700, Doug Helm <[EMAIL PROTECTED]> wrote: > > Hey, Folks: > > > > I'm trying to write a very simple file upload CGI. I'm on a Windows server. > > I *am* using the -u switch to start Python for CGIs, as follows: > > > > c:\python\python.exe -u %s %s > > > > I *do* have write permissions on the directory I'm trying to write to. But, > > when I click submit, it just hangs. Any help would be greatly appreciated. > > Thanks. Here's the code... > > > > Upload.py > > > > import cgi > > > > print "content-type: text/html\n\n" > > > > form = cgi.FieldStorage() > > if not form: > > print """ > > > > > > > > > enctype="multipart/form-data"> > > > > > > > > > > > > """ > > else: > > import BLOB > > lobjUp = BLOB.BLOB() > > if lobjUp.Save('filename', 'SomeFile.jpg'): > > print """ > > > > > > > > File successfully saved. > > > > > > """ > > else: > > print """ > > > > > > > > Unable to save file. > > > > > > """ > > > > -- > > > > Blob.py > > > > import cgi > > import staticobject > > > > cTrue = 1 > > cFalse = 0 > > > > try: > > import msvcrt,os > > msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 > > msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 > > except ImportError: > > pass > > > > class BLOB(staticobject.StaticObject): > > > > def __init__(self): > > self.initializing = cTrue > > staticobject.StaticObject.__init__(self) > > self.initializing = cFalse > > > > def Save(self, pstrFormFieldName, pstrFilePathAndName): > > > > # tried this first -- same result -- just hangs... > > #try: > > # form = cgi.FieldStorage() > > # item = form[pstrFormFieldName] > > # if item.file: > > #data = item.file.read() > > #f = open(pstrFilePathAndName,'wb') > > #f.write(data) > > #f.close() > > #return cTrue > > # else: > > #return cFalse > > #except: > > # return cFalse > > > > form = cgi.FieldStorage() > > f = open(pstrFilePathAndName,'wb') > > f.write(form[pstrFormFieldName].value) > > f.close() > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Please visit dimitri's website: www.serpia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
[Ron Garret] > Is it really impossible to specify __slots__ using the "type" > constructor? It does not work? I vaguely remember having needed to do this once or twice, and it worked immediatly as expected. Unless I remember wrongly, you only have to preset `__slots__' in the dict you give to `type'. -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
In article <[EMAIL PROTECTED]>, James Stroud <[EMAIL PROTECTED]> wrote: > Hello, > > I have strings represented as a combination of an alphabet (AGCT) and a an > operator "/", that signifies degeneracy. I want to split these strings into > lists of lists, where the degeneracies are members of the same list and > non-degenerates are members of single item lists. An example will clarify > this: > > "ATT/GATA/G" > > gets split to > > [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] How about this? import re s = "ATT/GATA/G" result1 = re.findall(r"./.|.", s) consensus = [c.split("/") for c in result1] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
On Sun, 27 Mar 2005 14:39:06 -0800, James Stroud <[EMAIL PROTECTED]> wrote: >Hello, > > I have strings represented as a combination of an alphabet (AGCT) and a an > operator "/", that signifies degeneracy. I want to split these strings into > lists of lists, where the degeneracies are members of the same list and > non-degenerates are members of single item lists. An example will clarify > this: > > "ATT/GATA/G" > > gets split to > > [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] > > I have written a very ugly function to do this (listed below for the > curious), > but intuitively I think this should only take a couple of lines for one > skilled in regex and/or listcomp. Any takers? >>> import re >>> s = 'ATT/GATA/G' >>> re.findall('(./.|.)', s) ['A', 'T', 'T/G', 'A', 'T', 'A/G'] >>> If it is really important to have ['A'] instead of 'A', etc, looping over the result and noticing strings of length 3 vs length 1, then applying the appropriate transformation, should be simple enough. Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
Using a parser may sound like overkill, but why not when it's this easy? Get the latest pyparsing at http://pyparsing.sourceforge.net. -- Paul from pyparsing import oneOf, Group, OneOrMore, Literal testdata = "ATT/GATA/G" marker = oneOf( "A T G C") SLASH = Literal("/").suppress() genDegenList = OneOrMore( Group( marker + SLASH + marker ) | Group( marker ) ) print genDegenList.parseString( testdata ) (prints: [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] -- http://mail.python.org/mailman/listinfo/python-list
String Splitter Brain Teaser
Hello, I have strings represented as a combination of an alphabet (AGCT) and a an operator "/", that signifies degeneracy. I want to split these strings into lists of lists, where the degeneracies are members of the same list and non-degenerates are members of single item lists. An example will clarify this: "ATT/GATA/G" gets split to [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] I have written a very ugly function to do this (listed below for the curious), but intuitively I think this should only take a couple of lines for one skilled in regex and/or listcomp. Any takers? James p.s. Here is the ugly function I wrote: def build_consensus(astr): consensus = [] # the lol that will be returned possibilities = [] # one element of consensus consecutives = 0 # keeps track of how many in a row for achar in astr: if (achar == "/"): consecutives = 0 continue else: consecutives += 1 if (consecutives > 1): consensus.append(possibilities) possibilities = [achar] else: possibilities.append(achar) if possibilities: consensus.append(possibilities) return consensus -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: putting the output of a print statement into a string
Thanks, man! That was one fast reply... Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, Jon Perez wrote: > > >>Question: >> >>Is there a way to somehow put the output of 'print exc_obj' into >>a string? > > > There are ways to do even that, but maybe ``str(exc_obj)`` is enough for > your needs!? > > Ciao, > Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: putting the output of a print statement into a string
In <[EMAIL PROTECTED]>, Jon Perez wrote: > Question: > > Is there a way to somehow put the output of 'print exc_obj' into > a string? There are ways to do even that, but maybe ``str(exc_obj)`` is enough for your needs!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
putting the output of a print statement into a string
There are objects whose repr() is not the same as what gets printed out when you apply the print statement to them. Usually these are complex objects like exceptions. Example: >>> import smtplib >>> server=smtplib.SMTP("smtp.yourisp.com") >>> try: server.sendmail("[EMAIL PROTECTED]", "[EMAIL PROTECTED]","message") except smtplib.SMTPRecipientsRefused, senderrs: exc_obj=senderrs >>> repr(exc_obj) '' >>> print exc_obj {'[EMAIL PROTECTED]': (550, 'Verification failed for <[EMAIL PROTECTED]>\nunrouteable mail domain "in88validdomain.com"\nSender verify failed')} Question: Is there a way to somehow put the output of 'print exc_obj' into a string? -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
Ron Garret wrote: I need to dynamically generate new types at run time. I can do this in two ways. I can use the "type" constructor, or I can generate a "class" statement as a string and feed that to the exec function. The former technique is much cleaner all else being equal, but I want to be able to specify the __slots__ class variable for these new types, and it seems that to do that I need to use the latter method. Is that true? Is it really impossible to specify __slots__ using the "type" constructor? Why don't you just write a function to create class objects? def f(*params): class C(...): ... # based on params return C STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Maybe this helps: http://www.voidspace.org.uk/python/cgi.shtml#upload I use it, it works for fine me Maybe it will give you some clues on how to tweak your own script. Dimitri On Sun, 27 Mar 2005 10:32:20 -0700, Doug Helm <[EMAIL PROTECTED]> wrote: > Hey, Folks: > > I'm trying to write a very simple file upload CGI. I'm on a Windows server. > I *am* using the -u switch to start Python for CGIs, as follows: > > c:\python\python.exe -u %s %s > > I *do* have write permissions on the directory I'm trying to write to. But, > when I click submit, it just hangs. Any help would be greatly appreciated. > Thanks. Here's the code... > > Upload.py > > import cgi > > print "content-type: text/html\n\n" > > form = cgi.FieldStorage() > if not form: > print """ > > > > enctype="multipart/form-data"> > > > > > > """ > else: > import BLOB > lobjUp = BLOB.BLOB() > if lobjUp.Save('filename', 'SomeFile.jpg'): > print """ > > > > File successfully saved. > > > """ > else: > print """ > > > > Unable to save file. > > > """ > > -- > > Blob.py > > import cgi > import staticobject > > cTrue = 1 > cFalse = 0 > > try: > import msvcrt,os > msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 > msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 > except ImportError: > pass > > class BLOB(staticobject.StaticObject): > > def __init__(self): > self.initializing = cTrue > staticobject.StaticObject.__init__(self) > self.initializing = cFalse > > def Save(self, pstrFormFieldName, pstrFilePathAndName): > > # tried this first -- same result -- just hangs... > #try: > # form = cgi.FieldStorage() > # item = form[pstrFormFieldName] > # if item.file: > #data = item.file.read() > #f = open(pstrFilePathAndName,'wb') > #f.write(data) > #f.close() > #return cTrue > # else: > #return cFalse > #except: > # return cFalse > > form = cgi.FieldStorage() > f = open(pstrFilePathAndName,'wb') > f.write(form[pstrFormFieldName].value) > f.close() > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Specifying __slots__ in a dynamically generated type
Ron Garret wrote: > > I need to dynamically generate new types at run time. I can do this in > two ways. I can use the "type" constructor, or I can generate a "class" > statement as a string and feed that to the exec function. The former > technique is much cleaner all else being equal, but I want to be able to > specify the __slots__ class variable for these new types, and it seems > that to do that I need to use the latter method. Is that true? Is it > really impossible to specify __slots__ using the "type" constructor? This simple testscript class Meta(type): def __init__(*args): print args return type(*args[1:]) class Foo(object): __metaclass__ = Meta __slots__ = "foo", "bar" Foo() shows that __slots__ is just a part of the type's dict. So you can simply specify it. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
ANN: Brazil organises its first PyConDayBrasil
Inspired by the PyCon tradition, the Brazilian Python Community is organising a PyCon-like event called: PyConDayBrasil. We have gathered 14 people to give speeches exclusively about Python in an event that will take place in April 28th/29th. The event's URL is below (only in Brazilian Portuguese pt-br): http://www.pythonbrasil.com.br/moin.cgi/PyConDayBrasil We hope that this event will not be just a standalone happening, but the beginning of a tradition. Moreover, we will strive to find sponsors to allow us to invite international speakers in the following years. To illustrate the scope of PyConDayBrasil, this year's program is composed by: - Python applications to science and engineering (Vinicius Franco do Nascimento) - Molecular Alignment Analysis in Python (Frederico Gonzalez Colombo Arnoldi) - Python in Undergraduate Courses (Marco André Lopes Mendes) - Exploring Boa Constructor (Luciano Pacheco) - Python refreshes your thinking (Osvaldo Santana Neto) - Plone for Pythonistas (Fabiano "Xiru" Weimar dos Santos) - Python-Fu inside Gimp (Joao S. O. Bueno Calligaris) - The Language Boo by its Creator (Rodrigo "Bamboo" de Oliveira) - Zope 3: Reality or myth (Luciano Ramalho) - Python Game Programming (Gustavo Barbieri) - Advanced CMF and Plone Development (Jean Rodrigo Ferri) - And now something completely different: Pyrotecnical Show (Rodrigo Senra) - Python Puzzles and Other Curiosities (Gustavo Niemeyer) - Content publishing in the PUSH model (Sidnei da Silva) I'd like to thank the python developers and the python community in general for these outstanding: tool, culture and community. best regards, Rod Senra -- ,_ | ) Rodrigo Senra |(__ --- _((|__|] GPr Sistemas http://www.gpr.com.br _ |(|___|] IC - Unicamp http://www.ic.unicamp.br/~921234 ___(|__|] L___(|_|]--- -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
Reinhold Birkenfeld wrote: Jacob Lee wrote: About slices: I agree that Python's slice boundaries (some_list[a:b] being all elements with a <= index < b) are counterintuitive at first. But this method does satisfy some handy properties, the first of which being: l[:n] + l[n:] = l And best of all, this is true for _every_ n, at least for the standard slice implementations... Secondly, the range() function behaves identically to slices, meaning that for i in range(10): will iterate 10 times, and for i in range(len(l)): will iterate over the indices of the sequence l. If you had l[a:b] be inclusive on both a and b (instead of inclusive on a and exclusive on b), you would have to be adding and subtracting one in all of these examples, leading that much more easily to off-by-one errors. It would be not so much adding/subtracting if list indices started at 1, but who on earth would want that? ;) Reinhold You certainly do get lots of adding/subtracting even if they start at 1. For example the length of lst[a : b] would be (a - b + 1). I certainly had my share of fencepost problems in Fortran I, II, IV, V ... --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for a 10-14 years old?
On 2005-03-27, Joal Heagney <[EMAIL PROTECTED]> wrote: > Couldn't help myself. I had to write the Dragon Fractal in python.turtle >:) > That's nice. I ported it to use the pygsear Turtle class. http://www.nongnu.org/pygsear/ --- Dragon.py 2005-03-27 08:48:13.0 -0500 +++ pDragon.py 2005-03-27 16:33:48.0 -0500 @@ -1,9 +1,14 @@ """Generates the L-System for the Dragon Fractal, using -the turtle module.""" +the pygsear.Drawable.Turtle class.""" -import re, turtle +import re +#import turtle +from pygsear.Drawable import Turtle from math import sin, pi +turtle = Turtle() +#turtle.visible = False + """The default L-System rules for the dragon fractal are: Angle 45 degrees Starting Axiom FX @@ -65,7 +70,7 @@ red = 1.0 green = 0.0 blue = 1.0 - fract -return red, green, blue +return red*255, green*255, blue*255 # The default is that the turtle will only move one pixel def parser(parsestring, distance=1, angle=45): @@ -73,13 +78,14 @@ newstring = re.sub("X", "", parsestring) newstring = re.sub("Y", "", newstring) # Clear the screen -turtle.clear() +#turtle.clear() strlen = len(newstring) colorinc = 1.0 / float(strlen) -turtle.color(colorator(0)) +turtle.set_color(colorator(0)) for i in range(strlen): value = newstring[i] -turtle.color(colorator(float(i) * colorinc)) +color = colorator(float(i) * colorinc) +turtle.set_color(color) if value == "+": turtle.right(angle) elif value == "-": @@ -87,7 +93,7 @@ elif value == "F": turtle.forward(distance) # Hide the cursor -turtle.color(1.0,1.0,1.0) +turtle.uclear() def run(count=15, distance=1, angle=45, width=1): string = "FX" @@ -96,14 +102,15 @@ count -= 1 # "Hide" the cursor while we are moving it. ##print string -turtle.width(width) -turtle.color(1.0,1.0,1.0) +turtle.set_width(width) +#turtle.color(1.0,1.0,1.0) # Move the cursor so the turtle won't go off the screen. # You might want to resize the turtle screen while the program is doing this -turtle.setx(100) -turtle.sety(-200) +#turtle.setx(100) +#turtle.sety(-200) parser(string, distance=distance, angle=angle) if __name__ == "__main__": run(15) +raw_input() -- http://mail.python.org/mailman/listinfo/python-list
Specifying __slots__ in a dynamically generated type
I need to dynamically generate new types at run time. I can do this in two ways. I can use the "type" constructor, or I can generate a "class" statement as a string and feed that to the exec function. The former technique is much cleaner all else being equal, but I want to be able to specify the __slots__ class variable for these new types, and it seems that to do that I need to use the latter method. Is that true? Is it really impossible to specify __slots__ using the "type" constructor? rg -- http://mail.python.org/mailman/listinfo/python-list
Re: Pre-PEP: Dictionary accumulator methods
Michele Simionato wrote: FWIW, here is my take on the defaultdict approach: def defaultdict(defaultfactory, dictclass=dict): class defdict(dictclass): def __getitem__(self, key): try: return super(defdict, self).__getitem__(key) except KeyError: return self.setdefault(key, defaultfactory()) return defdict d = defaultdict(int)() d["x"] += 1 d["x"] += 1 d["y"] += 1 print d d = defaultdict(list)() d["x"].append(1) d["x"].append(2) d["y"].append(1) print d Michele Simionato Very pretty! =) It does mean, however, that if the defaultfactory function takes any arguments, you have to wrap the function to make this work. I'd probably prefer something like: py> def defaultdict(*args, **kwargs): ... defaultfactory, args = args[0], args[1:] ... class defdict(dict): ... def __getitem__(self, key): ... try: ... return super(defdict, self).__getitem__(key) ... except KeyError: ... return self.setdefault(key, defaultfactory( ... *args, **kwargs)) ... return defdict ... py> d = defaultdict(int)() py> d['x'] += 1 py> d['x'] += 1 py> d['y'] += 1 py> d {'y': 1, 'x': 2} py> d = defaultdict(list, [0])() py> d['x'].append(1) py> d['x'].append(2) py> d['y'].append(1) py> d {'y': [0, 1], 'x': [0, 1, 2]} That said, I still think a dictools module is a better solution to this problem. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Pre-PEP: Dictionary accumulator methods
Michele Simionato wrote: I am surprised nobody suggested we put those two methods into a separate module (say dictutils or even UserDict) as functions: from dictutils import tally, listappend tally(mydict, key) listappend(mydict, key, value) Sorry to join the discussion so late (I've been away from my email for a week) but this was exactly my reaction too. In fact, I have a 'dicttools' module with similar methods in it: # like "tally" but without ability to set increment def counts(iterable, key=None): result = {} for item in iterable: # apply key function if necessary if key is None: k = item else: k = key(item) # increment key's count try: result[k] += 1 except KeyError: result[k] = 1 return result # like "listappend" but with the option to use key and value funcs def groupby(iterable, key=None, value=None): result = {} for item in iterable: # apply key function if necessary if key is None: k = item else: k = key(item) # apply value function if necessary if value is None: v = item else: v = value(item) # append value to key's list try: result[k].append(v) except KeyError: result[k] = [v] return result These two functions have covered all my use cases for "tally" and "listappend" -- I always want to perform the increments or list appends over a sequence of values, so having functions that operate on sequences covers all my needs. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform distribution of standalone executable
don't count out py2exe, especially if your using pywin32's -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
I very much take your point. And thanks: that answers my syntax question (I think!) -- *and* tells me that I don't care. Charles Hartman On Mar 27, 2005, at 2:16 PM, [EMAIL PROTECTED] wrote: ... >>> simpler == complexities True >>> I've not the glimmer of a clue which would be faster, and don't care to check -- the evil way could be 5 times faster, and I wouldn't want it in my code :-) Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Python List Issue
On Sun, 27 Mar 2005 09:01:20 GMT, "Nick L" <[EMAIL PROTECTED]> wrote: >I've hit a brick wall on something that I'm guessing is pretty simple but >it's driving me nuts. Yes, I've ran across that too a few times. >How on earth can I make a complete seperate copy of a list with out it >being a attached to the original in any way shape or form so that I can >modifiy if at will and not worry about the original? This routine copies a list of lists. # Makes a copy of a list of lists # Containing simple data. def copylistlist(alist): if type(alist) is list: copy = [] for i in alist: if type(i) is list: i = copylistlist(i) copy.append(i) return copy bob = [[[0, 0]]] final = copylistlist(bob) print 'bob:'bob print 'Final:'final This still doesn't create new items within the new list. but with literal data consisting of letters and numbers, it will work. If you are working with a data tree, you may be able to modify this to do what you want. Just add a test in the inner loop for the data you want to modify. >Any ideas, suggestions, comments are greatly appreciated >thanks > >Nick Hope that helps. Ron_Adam -- http://mail.python.org/mailman/listinfo/python-list
help with getting selection from wxChoice with out after it has changed
I want to get the selection of several wxChoice boxes. But i do not want to have to catch the events for all the boxes I should be able to access the current selection outside of an event,but i am not seeing how to do this. This is a hack of the wxpython choice demo to demonstrate my question #- comment marks are for indention #import wx #class TestChoice(wx.Dialog): #def __init__(self, parent): ##self.log = log #wx.Dialog.__init__(self, parent, -1) # #sampleList = ['zero', 'one', 'two', 'three', 'four', 'five', # 'six', 'seven', 'eight'] # #wx.StaticText(self, -1, "This example uses the wxChoice control.", (15, 10)) #wx.StaticText(self, -1, "Select one:", (15, 50), (75, -1)) #self.ch = wx.Choice(self, -1, (100, 50), choices = sampleList) #self.Bind(wx.EVT_CHOICE, self.EvtChoice, self.ch) # # #def EvtChoice(self, event): #print('EvtChoice: %s\n' % event.GetString()) #self.ch.Append("A new item") # ##-changed here - from event.GetSelection() #if self.ch.GetSelection() == 'one': #print('Well done!\n') # # #if __name__ == "__main__": #app = wx.PySimpleApp(0) #wx.InitAllImageHandlers() #Dialog_Main = TestChoice(None) #app.SetTopWindow(Dialog_Main) #Dialog_Main.Show() #app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: mysteriously nonfunctioning script - very simple
Heiko Wundram <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... > Why not try the following: I did try it, and it didn't work either. It appears there must be something wrong with my computer, hopefully something benign. Thanks anyway. Peace, STM -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
Brian van den Broek said unto the world upon 2005-03-27 14:12: Charles Hartman said unto the world upon 2005-03-27 13:35: On Mar 27, 2005, at 1:18 PM, Brian van den Broek wrote: >>> def some_arbitrary_function(y): ... return ( (y * 42) - 19 ) % 12 ... >>> [some_arbitrary_function(len(x)) for x in lines.split()] [5, 5, 11, 11, 5, 11, 5, 11] >>> I could be missing some edge cases, but it seems to me that if you have list comps you don't really need map, filter, and the like. The map portion can be done by nested function applications in the list comp itself. A good point, and I think I see that. But ultimately what I'm wondering is whether a construction like this [1]: for s in possScansions: for a in algorithms: (feet, test) = self.DoAlgorithm(a, s) complexities[(s, a)] = (self._measureComplexity(feet, test), len(feet)) can be condensed in one or more of these ways. (Whether the result would be readable / maintainable is a separate question. So is whether it would be more efficient. At the moment I'm just trying to get clear about the syntax.) [1] possScansions is a list of strings; algorithms is a list of ints; feet is a list of strings; test is a list of Booleans. complexities is a dictionary whose keys are those two-item tuples and whose values are the integers returned by self._measureComplexity Charles Hartman Hi Charles, Is the code below the sort of thing you had in mind? (I should be quite upset if I actually came across such code in the wild.) >>> # set-up with arbitrary functions, etc. >>> string_list = ['a', 'list of', 'arbitrary', 'strings'] >>> int_list = [3, 5, 42] >>> def some_function(a, s): ... if len(a) > s: ... chunk = a[s:] ... else: ... chunk = None ... return len(a) > s, chunk ... >>> def another_function(x, y): ... if y: ... return x + len(y) ... else: ... return x ... >>> complexities = {} >>> simpler = {} >>> # The structure you have above -- modulo that I flipped >>> # the order of arguments in the first function due to >>> # inattention (it doesn't matter, though). >>> for s in string_list: ... for i in int_list: ... (feet, test) = some_function(s, i) ... simpler[(s, i)] = another_function(feet, test) ... >>> # The evil way: >>> # (Please don't do this, at least IMHO) >>> for t in [(s, i, another_function(*some_function(s, i))) for s in string_list for i in int_list]: ... complexities[(t[0], t[1])] = t[2] ... >>> simpler == complexities True >>> I've not the glimmer of a clue which would be faster, and don't care to check -- the evil way could be 5 times faster, and I wouldn't want it in my code :-) Sorry for the self-reply, but I just saw how to crank the evil up a notch, and get it as a one-liner to boot: >>> complexities = {} >>> side_effect_list = [complexities.__setitem__((s, i), another_function(*some_function(s, i))) for s in string_list for i in int_list] >>> simpler == complexities True >>> side_effect_list [None, None, None, None, None, None, None, None, None, None, None, None] >>> Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best GUI toolkit in Python,Tkinter,wxPython,QT,GTK?
+1 Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: list.count() with no arguments
Johan Hahn wrote: Wouldn't it be nice if list.count, called without any arguments, returned a dict with the list's unique items as keys and their frequency of occurance as values? No. It would require all sequences to support this protocol, which would be tedious to implement. Some day, we may have a bag type, so it would be better if this type supported frequency counting. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python List Issue
> See copy.deepcopy(). It will make sure that everything gets copied and > nothing just referenced (more or less). So far copy.deepcopy() seems to be working perfectly. Thanks for the input Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
Charles Hartman said unto the world upon 2005-03-27 13:35: On Mar 27, 2005, at 1:18 PM, Brian van den Broek wrote: >>> def some_arbitrary_function(y): ... return ( (y * 42) - 19 ) % 12 ... >>> [some_arbitrary_function(len(x)) for x in lines.split()] [5, 5, 11, 11, 5, 11, 5, 11] >>> I could be missing some edge cases, but it seems to me that if you have list comps you don't really need map, filter, and the like. The map portion can be done by nested function applications in the list comp itself. A good point, and I think I see that. But ultimately what I'm wondering is whether a construction like this [1]: for s in possScansions: for a in algorithms: (feet, test) = self.DoAlgorithm(a, s) complexities[(s, a)] = (self._measureComplexity(feet, test), len(feet)) can be condensed in one or more of these ways. (Whether the result would be readable / maintainable is a separate question. So is whether it would be more efficient. At the moment I'm just trying to get clear about the syntax.) [1] possScansions is a list of strings; algorithms is a list of ints; feet is a list of strings; test is a list of Booleans. complexities is a dictionary whose keys are those two-item tuples and whose values are the integers returned by self._measureComplexity Charles Hartman Hi Charles, Is the code below the sort of thing you had in mind? (I should be quite upset if I actually came across such code in the wild.) >>> # set-up with arbitrary functions, etc. >>> string_list = ['a', 'list of', 'arbitrary', 'strings'] >>> int_list = [3, 5, 42] >>> def some_function(a, s): ... if len(a) > s: ... chunk = a[s:] ... else: ... chunk = None ... return len(a) > s, chunk ... >>> def another_function(x, y): ... if y: ... return x + len(y) ... else: ... return x ... >>> complexities = {} >>> simpler = {} >>> # The structure you have above -- modulo that I flipped >>> # the order of arguments in the first function due to >>> # inattention (it doesn't matter, though). >>> for s in string_list: ... for i in int_list: ... (feet, test) = some_function(s, i) ... simpler[(s, i)] = another_function(feet, test) ... >>> # The evil way: >>> # (Please don't do this, at least IMHO) >>> for t in [(s, i, another_function(*some_function(s, i))) for s in string_list for i in int_list]: ... complexities[(t[0], t[1])] = t[2] ... >>> simpler == complexities True >>> I've not the glimmer of a clue which would be faster, and don't care to check -- the evil way could be 5 times faster, and I wouldn't want it in my code :-) Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
Giovanni Bajo wrote: Terry Reedy wrote: 3) Sometimes the structure of the algorithm is not the structure of the code as written, people who prefer that the indentation reflects the structure of the algorithm instead of the structure of the code, are forced to indent wrongly. Do you have any simple examples in mind? Yes. When I use PyQt (or similar toolkit), I would like to indent my widget creation code so that one indentiation level means one level down into the widget tree hierarchy: v = VBox(self) # sons of v indented here w = HBox(self) # sons of w here QLabel("hello", w) QLabel("world", w) QButton("ok", v) In fact, I am used to do this very thing in C++, and it helps readability a lot. But in Python it's really easy to use a declarative construct instead, maybe something as simple as a nested list of classes and constructor arguments, and use some simple machinery to build the object graph. This way you avoid having the code and indentation saying different things, like in your example above, where it seems that w is not in fact a child of v. I don't know anything about PyQt though, so if I'm wrong about that I apologise - but the point still stands, since it's confusing to read it. /patrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Cross platform distribution of standalone executable
Mahesh wrote: > Hi, > > One of my clients does not want the Python VM installed on his > production machine (because it is not a supported IT language) so the > only way I can program in Python and release the application to him is > to make a standalone executable and deploy it. The last time I looked > at something like this, Macmillan installer was a good contender but > now that website seems to be AWOL. > > Are there any alternate installers out there? Googling didn't bring up > any other maintained installer. > > This installer should be able to build on Windows, Linux and AIX. Take a look at cx_Freeze: http://starship.python.net/crew/atuining/cx_Freeze/ Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
On Mar 27, 2005, at 1:18 PM, Brian van den Broek wrote: >>> def some_arbitrary_function(y): ... return ( (y * 42) - 19 ) % 12 ... >>> [some_arbitrary_function(len(x)) for x in lines.split()] [5, 5, 11, 11, 5, 11, 5, 11] >>> I could be missing some edge cases, but it seems to me that if you have list comps you don't really need map, filter, and the like. The map portion can be done by nested function applications in the list comp itself. A good point, and I think I see that. But ultimately what I'm wondering is whether a construction like this [1]: for s in possScansions: for a in algorithms: (feet, test) = self.DoAlgorithm(a, s) complexities[(s, a)] = (self._measureComplexity(feet, test), len(feet)) can be condensed in one or more of these ways. (Whether the result would be readable / maintainable is a separate question. So is whether it would be more efficient. At the moment I'm just trying to get clear about the syntax.) [1] possScansions is a list of strings; algorithms is a list of ints; feet is a list of strings; test is a list of Booleans. complexities is a dictionary whose keys are those two-item tuples and whose values are the integers returned by self._measureComplexity Charles Hartman -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the best GUI toolkit in Python,Tkinter,wxPython,QT,GTK?
Maurice LING wrote: > That's almost like asking which way of cooking chicken is the best? > steam, fried, stew, roast? BBQ'ed of course. I believe that fits your point. :) Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for a 10-14 years old?
On Fri, 25 Mar 2005 00:50:36 -0700, Jules Dubois <[EMAIL PROTECTED]> wrote: >On Wednesday 23 March 2005 22:03, [EMAIL PROTECTED] <[EMAIL PROTECTED]> >(<[EMAIL PROTECTED]>) wrote: > >> Is there something out there like "Python for kids" which would explain >> *basic* programming concepts in a way which is accessible and >> entertaining for kids aged 10-14 > >It's not what you asked for, but you should consider Squeak Smalltalk and >eToys. The GUIs that we use today are largely the work of Alan Kays's >group at Xerox in the 1970s. Dr. Kay has spent the last 35 years trying to >make computers educational and fun for children. If you're interested, see > > http://www.squeak.org/ (The Squeak Smalltalk site) > http://www.squeakland.org/ (The eToys site) > >Squeak runs on Linux, MacOS, and even Windows, and it's free. I again take the opportunity to raise a hand in protest. Going to these sites I learn that Kay is the "Father of the Personal Computer" working from "a deep understanding of how children learn". He also may be someone who married himself to a bad idea 30 years ago, in which he has invested too much, thereby crippling his ability to confront scientific evidnce in an evenhanded manner. He is also someone ex of Disney, now of HP, who lectures us on the destructive infleunce of the profit motive on the development of computer science and its capacity to enhance our world. I understand better how Xah Lee got to be Xah Lee when confronted with the cult of Kay. Art -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
Charles Hartman said unto the world upon 2005-03-27 09:51: I understand this toy example: lines = "this is a group\nof lines of\nwords" def getlength(w): return len(w) s = map(getlength, [word for ln in lines.split() for word in ln.splitlines()]) (now s is [4, 2, 1, 5, 2, 5, 2, 5]) My question is whether there's any compact way to combine function calls, like this (which doesn't work): lines = "this is a group\nof lines of\nwords" def getlength(w): return len(w) def timestwo(x): return x * 2 s = map(timestwo(getlength), [word for ln in lines.split() for word in ln.splitlines()]) (Under the WingIDE I get this traceback: "/Applications/WingIDE-Professional-2.0.2/WingIDE.app/Contents/MacOS/ src/debug/server/_sandbox.py", line 1, in ? # Used internally for debug sandbox under external interpreter File "/Applications/WingIDE-Professional-2.0.2/WingIDE.app/Contents/MacOS/ src/debug/server/_sandbox.py", line 1, in addone # Used internally for debug sandbox under external interpreter TypeError: unsupported operand type(s) for +: 'function' and 'int' ) I hope the question is clear enough. I have a feeling I'm ignoring a simple technique . . . Charles Hartman Hi Charles, perhaps I'm distracted by the `toy' nature of the examples, but maybe this will help: >>> lines = "this is a group\nof lines of\nwords" >>> [len(x) for x in lines.split()] [4, 2, 1, 5, 2, 5, 2, 5] >>> [len(x)*2 for x in lines.split()] [8, 4, 2, 10, 4, 10, 4, 10] >>> def some_arbitrary_function(y): ... return ( (y * 42) - 19 ) % 12 ... >>> [some_arbitrary_function(len(x)) for x in lines.split()] [5, 5, 11, 11, 5, 11, 5, 11] >>> I could be missing some edge cases, but it seems to me that if you have list comps you don't really need map, filter, and the like. The map portion can be done by nested function applications in the list comp itself. Best, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert the contents of a string into name of variable
Erwan VITIERE a écrit : Hello, I want to convert the contents of a string into name of variable. For example: var1="toto" ... toto=5 print toto exec "toto = 5" print toto But I would use another solution if possible. -- http://mail.python.org/mailman/listinfo/python-list
File Uploads
Hey, Folks: I'm trying to write a very simple file upload CGI. I'm on a Windows server. I *am* using the -u switch to start Python for CGIs, as follows: c:\python\python.exe -u %s %s I *do* have write permissions on the directory I'm trying to write to. But, when I click submit, it just hangs. Any help would be greatly appreciated. Thanks. Here's the code... Upload.py import cgi print "content-type: text/html\n\n" form = cgi.FieldStorage() if not form: print """ """ else: import BLOB lobjUp = BLOB.BLOB() if lobjUp.Save('filename', 'SomeFile.jpg'): print """ File successfully saved. """ else: print """ Unable to save file. """ -- Blob.py import cgi import staticobject cTrue = 1 cFalse = 0 try: import msvcrt,os msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 except ImportError: pass class BLOB(staticobject.StaticObject): def __init__(self): self.initializing = cTrue staticobject.StaticObject.__init__(self) self.initializing = cFalse def Save(self, pstrFormFieldName, pstrFilePathAndName): # tried this first -- same result -- just hangs... #try: # form = cgi.FieldStorage() # item = form[pstrFormFieldName] # if item.file: #data = item.file.read() #f = open(pstrFilePathAndName,'wb') #f.write(data) #f.close() #return cTrue # else: #return cFalse #except: # return cFalse form = cgi.FieldStorage() f = open(pstrFilePathAndName,'wb') f.write(form[pstrFormFieldName].value) f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
"Reinhold Birkenfeld" <[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] >>s t r i n g >> ^ ^ ^ ^ ^ ^ ^ >> 0 1 2 3 4 5 6 >> >> so that [1:2] is "t". > > Incidentally, the Python Tutorial tells us exactly the same... Ah! I've just forgotten that... Javier ___ Javier Bezos | Mem. A multilingual system for LaTeX jbezos at wanadoo dot es | http://mem-latex.sourceforge.net .|: -- http://mail.python.org/mailman/listinfo/python-list
Cross platform distribution of standalone executable
Hi, One of my clients does not want the Python VM installed on his production machine (because it is not a supported IT language) so the only way I can program in Python and release the application to him is to make a standalone executable and deploy it. The last time I looked at something like this, Macmillan installer was a good contender but now that website seems to be AWOL. Are there any alternate installers out there? Googling didn't bring up any other maintained installer. This installer should be able to build on Windows, Linux and AIX. Thanks, Mahesh -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tkinter] LONG POST ALERT: Setting application icon on Linux
Here is a short program that sets Tk's window icon on Linux. My window manager is icewm, and it uses a scaled version of the "flagup" image both at the upper-left corner of the window and on the task bar entry for the window. import Tkinter app = Tkinter.Tk() app.iconbitmap("@/usr/X11R6/include/X11/bitmaps/flagup") app.mainloop() As often happens, the Tkinter documentation doesn't tell the whole story---you have to dig into the Tk documentation. I started with "man n wm", and read the following: If bitmap is specified, then it names a bitmap in the standard forms accepted by Tk (see the Tk_GetBitmap manual entry for details). OK, on to Tk_GetBitmap... @fileName FileName must be the name of a file containing a bitmap description in the standard X11 or X10 format. and I happened to know that some bitmaps in this format exist in the directory I mentioned above. Note that the "standard X11 format" is monochrome, so you will not be able to use color images with "iconbitmap" on Linux. Tk doesn't support _NET_WM_ICON for setting full-color icons. Jeff pgpyC2wnrfybL.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Panel problems
Howdy, I am having some problems woth sizers adding panels to a scrolledwindow. I have 3 classes (wx.Panels) which I want to add to a ScrolledWindow (The Parent). I can get it to work except the ScrollWindow never scrolls. Also as I am new to (wx)Python, so I am sure it is a simple mistake. But what I cannot figure out is the creation order of Frames to Panels to Windows, sizers, blah...Is this infomation laid out some where? Any help would be apperciated. class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, style=wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN | wx.NO_FULL_REPAINT_ON_RESIZE) self.MaintPanel = wx.ScrolledWindow(self, -1, style=wx.SUNKEN_BORDER | wx.CLIP_CHILDREN) self.MaintPanel.SetScrollRate(10, 10) # Do I need another Sizer in here somewhere?? #Parent Sizer #self.mainsizer = wx.BoxSizer(wx.VERTICAL) #self.SetSizer(self.mainsizer) #self.SetSize(( 700, 600 )) #self.Centre() self.subsizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.subsizer) self.SetSize(( 700, 600 )) self.Centre() # Add subPanels # All of the sub panels work fine pnl1 = subPanel1(self) pnl2 = subPanel2(self) pnl3 = subPanel3(self) self.subsizer.AddMany([ (pnl1, 1, wx.EXPAND), (pnl2, 1, wx.EXPAND), (pnl3, 1, wx.EXPAND)]) # Add Main Panel self.MaintPanel.SetAutoLayout(True) self.MaintPanel.SetSizer(self.subsizer) self.Layout() Thanks in advance Scott -- http://mail.python.org/mailman/listinfo/python-list
Re: Python List Issue
"Nick L" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I've hit a brick wall on something that I'm guessing is pretty simple but > it's driving me nuts. I noticed that with python lists, generally when > you > make a copy of a list (ie, List1 = List2) Python is not C, etc. Assigning a name to an object *never* makes a copy. Assigning a second name creates an alias. Aliases are problems in any language that allows them (which C does also, via pointers). Consider Nick_PythonLearner = Nick_L > List1 just becomes a reference to List2 Ditto for the two Nick names, but better said, both names refer to the same person (or list). > and any modifications done to List1 affects List2. and ditto for a person with more than one name -- which is almost everyone in the modern world (Nick, Mr. L, etc). > Ok I can live with this Good. Name confusion is everywhere. > but I want to make a completely seperate [sic] copy not attached to the > original in anyway. So then I used this method. List1 = List2[:] For a shallow (one level) copy, List1=list(List2) is now prefered. For a deep (complete, all-level) copy, follow Kern's advice: copy.deepcopy. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get TabError?
In article <[EMAIL PROTECTED]>, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > $ python -t test.py > test.py: inconsistent use of tabs and spaces in indentation > hello > goodbye On more question. When using py_compile from with a script, is there any way to force the -t flag? M -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get TabError?
In article <[EMAIL PROTECTED]>, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote: > "Mr. Magoo" wrote: > > > Can someone provide a snippet which, when run, generates a TabError? > > > > I can only seem to get SyntaxError and IndentationError. > > $ python -c "print repr(open('test.py').read())" > 'if 1:\n\tprint "hello"\nprint "goodbye"\n' > > $ python test.py > hello > goodbye > > $ python -t test.py > test.py: inconsistent use of tabs and spaces in indentation > hello > goodbye > > $ python -tt test.py > File "test.py", line 3 > print "goodbye" > ^ > TabError: inconsistent use of tabs and spaces in indentation > > Thanks. Is there a reason (good or otherwise :-) why py_compile dumps this and IndentationError in a different format than SyntaxError? M -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
Charles Hartman wrote: > On Mar 27, 2005, at 11:50 AM, Nicolas Évrard wrote: > >>> >>> I hope the question is clear enough. I have a feeling I'm ignoring a >>> simple technique . . . >> >> lambda ! >> >> map(lambda x: timestwo(getlength(x)), ...) > > Ah, lambda! I've heard so much bad-mouthing of lambda that I forgot to > learn it . . . This is quite cool, and it looks as though it would work > with more complicated function calls than the ones in my toy example. > Thanks. Always keep in mind that a local named function can always be used instead of lambda. Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
Javier Bezos wrote: > MetaFont explains this by saying that the index > doesn't refer to a character but to a position > between characters, which when traslated to Python > would mean: > >s t r i n g > ^ ^ ^ ^ ^ ^ ^ > 0 1 2 3 4 5 6 > > so that [1:2] is "t". Incidentally, the Python Tutorial tells us exactly the same... Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
Jacob Lee wrote: > About slices: > > I agree that Python's slice boundaries (some_list[a:b] being all elements > with a <= index < b) are counterintuitive at first. But this method does > satisfy some handy properties, the first of which being: > l[:n] + l[n:] = l And best of all, this is true for _every_ n, at least for the standard slice implementations... > Secondly, the range() function behaves identically to slices, meaning that > for i in range(10): > will iterate 10 times, and > for i in range(len(l)): > will iterate over the indices of the sequence l. > > If you had l[a:b] be inclusive on both a and b (instead of inclusive on a > and exclusive on b), you would have to be adding and subtracting one in > all of these examples, leading that much more easily to off-by-one errors. It would be not so much adding/subtracting if list indices started at 1, but who on earth would want that? ;) Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
"Giovanni Bajo" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Terry Reedy wrote: > >>> 3) Sometimes the structure of the algorithm is not the structure >>> of the code as written, people who prefer that the indentation >>> reflects the structure of the algorithm instead of the structure >>> of the code, are forced to indent wrongly. >> >> Do you have any simple examples in mind? > > Yes. When I use PyQt (or similar toolkit), I would like to indent my > widget > creation code so that one indentiation level means one level down into > the > widget tree hierarchy: > > v = VBox(self) ># sons of v indented here >w = HBox(self) ># sons of w here >QLabel("hello", w) >QLabel("world", w) >QButton("ok", v) > > In fact, I am used to do this very thing in C++, and it helps readability > a > lot. > > I know I can add "if 1:" to do such a thing, but that's beyond the point. > I'm > just showing that there are simple and reasonable examples of cases where > you > would like to indent your code in different ways and you can't. I would call the above an indication of the structure of the output rather than of the algorithm, which is quite linear. Nonetheless, I can see it as a reasonable alternate reason for wanting to indent. Thanks for the response. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
On Mar 27, 2005, at 11:50 AM, Nicolas Évrard wrote: I hope the question is clear enough. I have a feeling I'm ignoring a simple technique . . . lambda ! map(lambda x: timestwo(getlength(x)), ...) Ah, lambda! I've heard so much bad-mouthing of lambda that I forgot to learn it . . . This is quite cool, and it looks as though it would work with more complicated function calls than the ones in my toy example. Thanks. Charles Hartman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python slogan, was Re: Grouping code by indentation - feature or ******?
Kent Johnson wrote: >> Wikiquote is nice. I missed it because I googled for Mark Twain and parts of >> the Churchill quote -- for that I'm now convinced it is as wikiquote gives >> a slightly longer excerpt and the date and location of the speech (November >> 11, 1947, in the House of Commons). > > Interesting that in the quote on wikiquote, Churchill indicates that the > sentiment is not original > with him: > "Indeed, it has been said that democracy is the worst form of government > except all those other > forms that have been tried from time to time." > > Note the "it has been said"... Though this may be a tricky style issue. I don't know whether some parts of the country would have cited only the first part, discrediting Mr Churchill. In Germany, a sentence like this would be readily welcomed by the "BILD" newspaper... Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tkinter] LONG POST ALERT: Setting application icon on Linux
Jeff Epler wrote: > Here is a short program that sets Tk's window icon on Linux. My window > manager is icewm, and it uses a scaled version of the "flagup" image > both at the upper-left corner of the window and on the task bar entry > for the window. > > import Tkinter > app = Tkinter.Tk() > app.iconbitmap("@/usr/X11R6/include/X11/bitmaps/flagup") > app.mainloop() > > As often happens, the Tkinter documentation doesn't tell the whole > story---you have to dig into the Tk documentation. I started with "man > n wm", and read the following: > If bitmap is specified, then it names a bitmap in the standard > forms accepted by Tk (see the Tk_GetBitmap manual entry for > details). > OK, on to Tk_GetBitmap... > @fileName FileName must be the name of a file containing a > bitmap description in the standard X11 or X10 format. > and I happened to know that some bitmaps in this format exist in the > directory I mentioned above. Note that the "standard X11 format" is > monochrome, so you will not be able to use color images with > "iconbitmap" on Linux. Tk doesn't support _NET_WM_ICON for setting > full-color icons. > > Jeff Thanks for this, Jeff - I'll do some digging in the Tk docs. My problem is that I'm trying to use iconwindow() to use a colour image, as opposed to iconbitmap(), although if push comes to shove I suppose I could use that. Thanks again for the quick response - on Easter weekend too! Tim J -- Website: www DOT jarmania FULLSTOP com -- http://mail.python.org/mailman/listinfo/python-list
Re: Turn of globals in a function?
On 26 Mar 2005 22:51:14 -0800, [EMAIL PROTECTED] (Oren Tirosh) wrote: >Ron_Adam <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>... >> Is there a way to hide global names from a function or class? >> >> I want to be sure that a function doesn't use any global variables by >> mistake. So hiding them would force a name error in the case that I >> omit an initialization step. This might be a good way to quickly >> catch some hard to find, but easy to fix, errors in large code blocks. > >def noglobals(f): >. import new >. return new.function( >. f.func_code, >. {'__builtins__':__builtins__}, >. f.func_name, >. f.func_defaults, >. f.func_closure >. ) > >You can use it with the Python 2.4 @decorator syntax: > >@noglobals >def a(...): >. # code here Cool! I haven't played with decorators yet. :) I noticed the 'new' module is depreciated. It referred me to call the object type directly instead. So this is probably the better way. def noglobals(f): return type(f)( f.func_code, {'__builtins__':__builtins__}, f.func_name, f.func_defaults, f.func_closure ) @noglobals def a(): global x try: x except: x=0 x += 1 return x x = 5 for n in range(10): print a() print x # x is still 5 So this is another, but longer, way to do a generator. >>> print type(a).__doc__ function(code, globals[, name[, argdefs[, closure]]]) Create a function object from a code object and a dictionary. The optional name string overrides the name from the code object. The optional argdefs tuple specifies the default argument values. The optional closure tuple supplies the bindings for free variables. >>> What are 'free variables'? And is there a way to directly read what names in a function are set with the global statement? (Other than looking at the monitor. ;) Ron_Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get TabError?
"Mr. Magoo" wrote: > Can someone provide a snippet which, when run, generates a TabError? > > I can only seem to get SyntaxError and IndentationError. $ python -c "print repr(open('test.py').read())" 'if 1:\n\tprint "hello"\nprint "goodbye"\n' $ python test.py hello goodbye $ python -t test.py test.py: inconsistent use of tabs and spaces in indentation hello goodbye $ python -tt test.py File "test.py", line 3 print "goodbye" ^ TabError: inconsistent use of tabs and spaces in indentation -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get TabError?
When running with "-tt", you can get this error. [EMAIL PROTECTED] src]$ python -tt Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> exec "def f():\n\ta\nb" Traceback (most recent call last): File "", line 1, in ? File "", line 3 b ^ TabError: inconsistent use of tabs and spaces in indentation pgpMSKzPbMB1C.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
hospedagem de sites - planos de hospedagem - hospedagem 41677
Tudo sobre hospedagem de sites , planos profissionais , economicos e muitos outros , sua empresa na internet por apenas 2,99 ao mês! http://www.hosting4u.com.br hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem hospedagem site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site site dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio dominio webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger webdesiger registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro registro website website website website website website website website website website website website website website website website website website website website website website website website website website website website website website profissional profissional profissional profissional profissional profissional profissional profissional desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver desenvolver hospedagem php hospedagens php hospedagens de sites hospedagens de páginas hospedagens de webpages hospedagens de homepages hospedagens mysql hospedagens sql hospedagens de site hospedagens baratas hospedagens profissionais hospedagem php hospedagem de sites hospedagem de site hospedagem de páginas hospedagem de webpages hospedagens de homepages hospedagem mysql hospedagem sql hospedagem de site hospedagem barata hospedagem profissional host hospedagem de site -- http://mail.python.org/mailman/listinfo/python-list
How to get TabError?
Can someone provide a snippet which, when run, generates a TabError? I can only seem to get SyntaxError and IndentationError. Thanks, M -- http://mail.python.org/mailman/listinfo/python-list
Re: Grouping code by indentation - feature or ******?
"Jacob Lee" <[EMAIL PROTECTED]> escribió en el mensaje >> things which compesate that (another annoying point >> of Python are slices -- mine are always off by 1). >About slices: Thank you, but I knew the motivations for this odd behaviour, which can be found as well in, for example, MetaFont. However, I disagree. > satisfy some handy properties, the first of which being: > l[:n] + l[n:] = l I don't think l[:5] + l[5:] = l is a handy property and to me is clearly counterintuitive. Further, I don't understand why l[a:b] has a behaviour which does't depend on its own logic but on that of certain constructs containing slices but which aren't the slices themselves. If you have to add or substract 1 in an expression containing slices (or contained in a slice), this belongs to the logic of the expression, not to the slices syntax. MetaFont explains this by saying that the index doesn't refer to a character but to a position between characters, which when traslated to Python would mean: s t r i n g ^ ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 6 so that [1:2] is "t". Javier ___ Javier Bezos| TeX y tipografía jbezos at wanadoo dot es| http://perso.wanadoo.es/jbezos |... CervanTeX (Spanish TUG) | http://www.cervantex.org -- http://mail.python.org/mailman/listinfo/python-list
list.count() with no arguments
Wouldn't it be nice if list.count, called without any arguments, returned a dict with the list's unique items as keys and their frequency of occurance as values? >>> [1,2,1,'a'].count() {'a': 1, 1: 2, 2: 1} >>> 'hello world'.count() {' ': 1, 'e': 1, 'd': 1, 'h': 1, 'l': 3, 'o': 2, 'r': 1, 'w': 1} ...johahn -- http://mail.python.org/mailman/listinfo/python-list
Re: list-comprehension and map question (simple)
* Charles Hartman [16:51 27/03/05 CEST]: I understand this toy example: lines = "this is a group\nof lines of\nwords" def getlength(w): return len(w) s = map(getlength, [word for ln in lines.split() for word in ln.splitlines()]) (now s is [4, 2, 1, 5, 2, 5, 2, 5]) My question is whether there's any compact way to combine function calls, like this (which doesn't work): lines = "this is a group\nof lines of\nwords" def getlength(w): return len(w) def timestwo(x): return x * 2 s = map(timestwo(getlength), [word for ln in lines.split() for word in ln.splitlines()]) I hope the question is clear enough. I have a feeling I'm ignoring a simple technique . . . lambda ! map(lambda x: timestwo(getlength(x)), ...) -- (°> Nicolas Évrard / ) Liège - Belgique ^^ -- http://mail.python.org/mailman/listinfo/python-list