Re: [Tutor] general import VS importing inside a function
"Fidel Sanchez-Bueno" wrote What is the best aproach when it comes to import??, is allways better to make all the import calls in the global scope, making the overall runtime of the program better because the program is not going to import something everytime a function is called, or is better to make specific import's inside a function making the function completely portable?? The general concensus is to keep all imports together at the top of the module. I do occasionally put an import inside a function but only if a) its in an exceptioon block that I don;t expect to be used AND b) the module takes significant time to load and I care about performance Those two things don't happen very often so 99% of the time all imports go at the top. and another thing, making specific import, makes the program less, how you said this "RAM eater" (sorry my native language is spanish and i dont now how to translate "cosume menos recursos" google says "cosumes less resources", but anyway i hope you get it) Unless the module has huge data structures populated within it thats unlikely to be a significant issue. Usually the memory consumption comes from the main execution code where the data is defined not the module code. On a huge project that might be an issue but not on the average Python project. I say this because, for example when i'm in the interactive shell and import big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond, and if am only going to use like 4 or 5 function inside NumPy i think is better to say just "from Numpy import foo, bar, qux etc" Thats a different question. :-) If you are only using a few names from the module the "from x imporrt y " style is good. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] general import VS importing inside a function
On Fri, Aug 28, 2009 at 10:34 PM, Fidel Sanchez-Bueno wrote: > What is the best aproach when it comes to import??, is allways better to > make all the import calls in the global scope, making the overall runtime of > the program better because the program is not going to import something > everytime a function is called, or is better to make specific import's > inside a function making the function completely portable?? Imports are conventionally put at the start of a module. Generally the unit of reuse in Python is a module, not a function, so you don't limit portability by putting the imports at the top of a module. > and another thing, making specific import, makes the program less, how you > said this "RAM eater" (sorry my native language is spanish and i dont now > how to translate "cosume menos recursos" google says "cosumes less > resources", but anyway i hope you get it) Modules are only loaded once, at the first import. The loaded modules are cached in sys.modules. So subsequent imports are fast (just a dictionary lookup) and don't consume any resources. > I say this because, for example when i'm in the interactive shell and import > big things like Scipy, and NumPy, python takes 3 to 5 seconds to respond, > and if am only going to use like 4 or 5 function inside NumPy i think is > better to say just "from Numpy import foo, bar, qux etc" but i would > actually like to read this from someone that knows about programming and not > just me making asumptions... It will take the same amount of time for the import with either style of import. It is the initial load of the module that takes time and memory. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 12:24 -0400, Dave Angel wrote: > > Thank you Dave, very helpful as ever. I made a few tests and experiments > > to understand better, and I feel I am understanding how it works. > > Although the mechanic of this is increasingly clear, the logic behind is > > still a bit obscure: here comes a silly test on which results I have > > questions about > > > > == > > > > class A(object): > > variable = 0 > > @classmethod > > def cm(cls): > > cls.variable += 3 > > > > class B(A): > > pass > > > > class C(B): > > pass > > > > a = A() > > b = B() > > c = C() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > b.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > c.cm() > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > a.variable = 7 > > A.variable = 4 > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > print '---' > > B.variable = 'x' > > print A.variable, a.variable > > print B.variable, b.variable > > print C.variable, c.variable > > > > == > > > > Now, the output of this test is as follows (I manually added the numbers > > on the right for reference in the remaining of the post): > > > > 0 0 # 1 > > 0 0 > > 0 0 > > --- > > 3 3 # 2 > > 3 3 > > 3 3 > > --- > > 3 3 # 3 > > 6 6 > > 6 6 > > --- > > 3 3 # 4 > > 6 6 > > 9 9 > > --- > > 4 7 # 5 > > 6 6 > > 9 9 > > --- > > 4 7 # 6 > > x x > > 9 9 > > > > #1 is plain obvious. > > > > #2 came as a bit of surprise: "Ah-ah!... so the class variable is the > > same for all the hierarchy of classes! I would have guessed each class > > had its own variable..." > > > > #3 and #4 are bigger surprises: "Uh? let me understand better, so... it > > must be like branches... as soon as I say that B.variable is different > > than its ancestors, all the descendants of B get updated... Yet, it's > > strange: this very thread on the mailing list has started with me asking > > about the order of declaration for classes, and I have been told that > > class variables are processed as soon as the interpreter hits the class > > definition... so I would have expected that C.variable would have been > > initialised already and would not dynamically change when B.variable > > does..." > > > > #5 confused me: it seems that a.variable can refer to both the class > > variable or a newly created object property... that sounds like a > > never-ending source of bugs to me: it is me who has then to remember if > > a given syntax refers to a class variable or to an object method? > > > > #6 really make no sense to me: it seems that the class variable of C has > > not been changed this time (as it did in #3)... > > > > The points above confuse me even more about the "design purposes" of > > classmethods and staticmethods... > > > > Any help/feedback, very much appreciated. > > > > mac. > > > > > > > Great questions. I love a person who is organized as you are. And as > willing to learn. > > #3 and #4 - First let me point out that these are not class variables, > but class attributes. It's unfortunate that you called the attributes > with the label 'variable'. I frequently make the same mistake (call it > sloppy mistake), but it might matter somewhere in the following > discussion. A class variable is simply a "variable" which references > the class. Think of it as an alias for the class. Just like a list > variable is a variable which references a list. If you do: > newclass = A > > then you can use newclass in exactly the same way as A. a = > newclass(), print newclass.variable, etc. > > A class attribute, on the other hand, is what other languages would call > a field of the class. And it definitely does get initialized when the > class is executed. That's important in the earlier discussion because > the *right-hand-side* has to be valid at that time, which is why you had > the forward referencing problem. So in the following code: > > n = 12 > class A(object): > attr = n > > n = 42 > > > the attribute A.attr is a reference to 12, not 42. The confusion in > this #3 and #4 case is that when some later expression tries to use a > particular class attribute there are some rules for lookup. I don't > know the correct terminology, but I think of this as the "." operator. > When I say C.variable, the first search is in the classes dictionary. > If it's not found there, then it searches in the parent class' > dictionary, and so on. The attribute is not copied, there's just a > search order when it's accessed. > > #5 - It'
Re: [Tutor] Declaration order of classes... why it is important?
On Fri, 2009-08-28 at 18:03 +0100, Alan Gauld wrote: > "Mac Ryan" wrote > > > I am not sure I understood the difference between staticmethod end > > classmethod, though, even if I can guess it has to do with subclassing, > > I think it is mainly historical. staticmethod came first (I think) and > classmethod > was an improvement a couple of versions later. I think classmethod is the > preferred choice nowadays. > > > Also, what is the advantage of using a method at class level rather than > > using it at object instance > > There are two common cases: > > 1) You want to do something at the class level rather than instance > level - such as find all instances, or keep a count of all instances. > Or you may have a method or variable that affects all instances > simultaneously - perhaps activates or disables all network connections > say. > > 2) You want somethig that can be done without creating an instance, > or at least does not depend on whether any instances exist yet. This > is very common in Java which doesn't support standalone functions > but is not needed so much in Python because a module function is > usually a better option. > > You can also use it to provide meta-class programming features > and other tricks, but frankly thats usually being too clever for your > own good! :-) > > HTH, Thank you Alan, that totally answer my question about classmethods. :) What is still unclear to me, is what the staticmethods are for, though: since the reference to the object instance or to the class object are stripped away from the call, I wonder why not to use a module function instead. The only difference I can think of between the two (static method and module function) is that the namespaces they "live in" are different (mymodule.function vs. mymodule.myclass.function)... but I suspect there must be a better and more important design reason to have them implemented in the core... Many thanks in advance for your help, Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
On Fri, Aug 28, 2009 at 10:16 PM, Ishan Puri wrote: emma = nltk.corpus.gutenberg.words('austen-emma.txt') len(emma) > 192427 > > So this is the number of words in a particular 'austen-emma.txt'. How would > I do this > with my IM50re.txt? It > seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg > corpus installed with NLTK. > Like this many examples are given for different analyses that can be done > with NLTK. However they all seem to be specific > to one of the texts above or another one already installed with NLTK. I am > not sure how to apply these examples to my own corpus. This is pretty much the next line in the "Loading your own Corpus" example. After >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] you should be able to do my_words = wordlists.words('IM50re.txt') len(my_words) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
> What is still unclear to me, is what the staticmethods are for, though: > since the reference to the object instance or to the class object are > stripped away from the call, I wonder why not to use a module function > instead. First recall that xsstatic methods were historically the first attempt at giving Python class methods. (They were called staticmethods because C++ and Java define their class methods using the label 'static' ) The static method is still inside the class so it provides namespace protection. Thus if we want to create a search class method in each of three classes within the same module we can do so, whereas a module function would need to take the class as an input parameter and probably then do a if/else type switch statement to manipulate/access the class attributes etc. Or you write 3 functions, one per class. Neither is very OO in approach. But a classmethod would be equally suitable, if not better. > The only difference I can think of between the two (static method and > module function) is that the namespaces they "live in" are different And that is significant. Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
Damon Timm wrote: Sorry for the double post! Went off by mistake before I was done ... Anyhow, I would like to have a tuple defined at the beginning of my code that includes classes *before* they are defined ... as such (this is on-the-fly-hack-code just for demonstrating my question): What you want to do can be done with a helper function (e.g. Sync.find_sync() below), but I smelled a bad class design. Anyway, here is how you would do it... class Video(object): url = '...' def sync(self): sync = Sync.find_sync(self.url) class Sync(object): class NoSuitableSync(Exception): pass @staticmethod def find_sync(url): for S in Sync.__subclasses__(): if S.RE.match(url): return S(url) raise Sync.NoSuitableSync() class SyncYoutube(Sync): RE = re.compile(r'some regex here') class SyncBlip(Sync): RE = re.compile(r'other regex here') what I suggest you could do: class Video(object): # Video is a mixin class def __init__(self, url): self.url = url def sync(self): # source agnostic sync-ing or just undefined pass @staticmethod def find_video(url): for sc in Video.__subclasses__(): if sc.RE.match(url) return sc(url) class Youtube(Video): RE = re.compile('... some regex here ...') def sync(self): # costum sync-ing pass class Blip(Video): RE = re.compile('... other regex here ...') def sync(self): # costum sync-ing pass a = Video.find_video('http://www.youtube.com/') that way, url detection will only happen on class initialization instead of every time sync is called. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] general import VS importing inside a function
thanks both (Alan and Kent)! now am clear about the right way of making import.. salu2.. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Declaration order of classes... why it is important?
On Sat, 2009-08-29 at 11:44 +, ALAN GAULD wrote: > First recall that xsstatic methods were historically the first attempt at > giving Python class methods. (They were called staticmethods because > C++ and Java define their class methods using the label 'static' ) > ... > > The only difference I can think of between the two (static method and > > module function) is that the namespaces they "live in" are different > > And that is significant. > > Alan G Ok, now I am an happy man. :) Thank you for your time! Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to convert binary files back to text files?
Hello! I want to convert compiled files to text files. I believe compiled files are binary files. I am able to convert a given string to binary and back to text. But when it comes to a file it is proving to be impossible. def p(a): s=open(a,'rb') for x in s: d=map(lambda y:chr(int(y,2)),x) print d s.close() >>> p("C:/pp.txt") Traceback (most recent call last): File "", line 1, in p("C:/pp.txt") File "", line 5, in p d=map(lambda y:chr(int(y,2)),x) File "", line 5, in d=map(lambda y:chr(int(y,2)),x) ValueError: invalid literal for int() with base 2: 'f' Please some one point where the problem is. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert binary files back to text files?
>On 8/29/09, Geneviève DIAGORN wrote: > > >Bonjour, > >Je suis absente jusqu'au 02/09 inclus. > >En cas d'urgence Soprane, contacter notre adresse générique > >projet.sopr...@teamlog.com. > >Cordialement. > > >Geneviève I dont know your language.Please communicate in English. I am using the code below to conver string to bin and back. def tobin(astr): z=map(lambda x: bin(ord(x)),astr) return z def tostring(blist): z=map(lambda x: chr(int(x,2)),l) return ''.join(z) I dont believe it is impossible on files. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
Hi Everyone - thanks for your responses. Answered my direct questions: [1] can't be done at the top and [2] would have to move the tuple somewhere else as well as gave me some new ideas about completely rethinking the design ... I love keeping the RE definitions with the child classes ... makes it easy just to add a child anywhere without having to fool with the original code. One of my issues has been fixed using the @staticmethod decorator (which I did not know about). Here is what I have now, and my final question (perhaps) follows. #this is a django app, by the way class Video(models.Model): url = models.URLField('Video URL') # more fields and functions here def sync(self): 'Update videos external data - for children only' pass @staticmethod def add_video(url): 'add a video only if it matches correct regex -- need ExceptionHandler' for sc in Video.__subclasses__(): if sc.RE.match(url): return sc(url=url) class YoutubeVideo(Video): RE = re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*') def sync(self): # do custom syncing here print "am syncing a YOUTUBE video" class ViemoVideo(Video): RE = re.compile(r'([^(]|^)http://(www.|)vimeo\.com/(?P\d+)\S*') def sync(self): # do custom syncing here print "am syncing a VIMEO video" ## So, this is *great* because now I can "add_video" without knowing the video url type at all. >>> v = Video.add_video(url="http://www.youtube.com/watch?v=UtEg3EQwN9A";) >>> v >>> Perfect! The last part is figuring out the syncing -- what I would like to do would be either: >>> Video.sync_all_videos() #create another static method Or, if I had to, create another function that did a: >>> for video in Video.objects.all(): # object.all() is a django function that >>> returns everything ... video.sync() However, I am not sure how to determine the "actual" class of a video when I am dealing only with the parent. That is, how do I call a child's sync() function when I am dealing the parent object? As suggested (in email below) I could re-run the regex for each parent video for each sync, but that seems like it could be an expensive operation (supposing one day I had thousands of videos to deal with). Is there another easy way to find the "real" class of an object when dealing with the parent? I know so little, I have to think there might be something (like the @staticmethod decorator!). Thanks again! Damon On Sat, Aug 29, 2009 at 8:05 AM, Lie Ryan wrote: > what I suggest you could do: > > class Video(object): > # Video is a mixin class > def __init__(self, url): > self.url = url > def sync(self): > # source agnostic sync-ing or just undefined > pass > �...@staticmethod > def find_video(url): > for sc in Video.__subclasses__(): > if sc.RE.match(url) > return sc(url) > class Youtube(Video): > RE = re.compile('... some regex here ...') > def sync(self): > # costum sync-ing > pass > class Blip(Video): > RE = re.compile('... other regex here ...') > def sync(self): > # costum sync-ing > pass > a = Video.find_video('http://www.youtube.com/') > > that way, url detection will only happen on class initialization instead of > every time sync is called. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert binary files back to text files?
On Sat, 2009-08-29 at 18:42 +0530, prasad rao wrote: > >On 8/29/09, Geneviève DIAGORN wrote: > >Bonjour, > >Je suis absente jusqu'au 02/09 inclus. > >En cas d'urgence Soprane, contacter notre adresse générique > >projet.sopr...@teamlog.com. > >Cordialement. > > >Geneviève > > I dont know your language.Please communicate in English. The message just says the person is out of office until the second of september. Unluckily her company (which is an IT company!!!) seems to be unable to properly configure an autoresponder... Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
Hi, Yes! It works! I guess I am asking how did you know to use wordlists.words('IM50re.txt')? Is this a specific command, as I believe it was not in the book? Thanks. From: Kent Johnson To: Ishan Puri Cc: *tutor python Sent: Saturday, August 29, 2009 3:34:09 AM Subject: Re: [Tutor] NLTK On Fri, Aug 28, 2009 at 10:16 PM, Ishan Puri wrote: emma = nltk.corpus.gutenberg.words('austen-emma.txt') len(emma) > 192427 > > So this is the number of words in a particular 'austen-emma.txt'. How would > I do this > with my IM50re.txt? It > seems the code "nltk.corpus.gutenberg.words" is specific to some Gutenberg > corpus installed with NLTK. > Like this many examples are given for different analyses that can be done > with NLTK. However they all seem to be specific > to one of the texts above or another one already installed with NLTK. I am > not sure how to apply these examples to my own corpus. This is pretty much the next line in the "Loading your own Corpus" example. After >>> from nltk.corpus import PlaintextCorpusReader >>> corpus_root='C:\Users\Ishan\Documents' >>> wordlists = PlaintextCorpusReader(corpus_root, 'IM50re.txt') >>> wordlists.fileids() ['IM50re.txt'] you should be able to do my_words = wordlists.words('IM50re.txt') len(my_words) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Store Class in Tuple Before Defining it ...
Damon Timm wrote: Hi Everyone - thanks for your responses. Answered my direct questions: [1] can't be done at the top and actually you can, but it's opening a can of worms that I wouldn't dare to go near: VIDEO_RE = { re.compile(r'regex here'): 'Youtube', re.compile(r'regex there'): 'Vimeo', re.compile(r'regex over here'): 'Blip', ) or VIDEO_TYPES = { 'Youtube': re.compile(r'regex here'), 'Vimeo': re.compile(r'regex here'), 'Blip': re.compile(r'regex here'), } [2] would have to move the tuple somewhere else as well as gave me some new ideas about completely rethinking the design ... I love keeping the RE definitions with the child classes ... makes it easy just to add a child anywhere without having to fool with the original code. One of my issues has been fixed using the @staticmethod decorator (which I did not know about). Here is what I have now, and my final question (perhaps) follows. #this is a django app, by the way class Video(models.Model): url = models.URLField('Video URL') # more fields and functions here def sync(self): 'Update videos external data - for children only' pass You may want to raise an exception or `assert False` here since Video.sync() should never be called (because children class must always override it). Alternatively, you can just not define sync so it raises AttributeError. @staticmethod def add_video(url): 'add a video only if it matches correct regex -- need ExceptionHandler' for sc in Video.__subclasses__(): if sc.RE.match(url): return sc(url=url) class YoutubeVideo(Video): RE = re.compile(r'([^(]|^)http://www\.youtube\.com/watch\?\S*v=(?P[A-Za-z0-9_-]+)\S*') def sync(self): # do custom syncing here print "am syncing a YOUTUBE video" class ViemoVideo(Video): RE = re.compile(r'([^(]|^)http://(www.|)vimeo\.com/(?P\d+)\S*') def sync(self): # do custom syncing here print "am syncing a VIMEO video" ## So, this is *great* because now I can "add_video" without knowing the video url type at all. v = Video.add_video(url="http://www.youtube.com/watch?v=UtEg3EQwN9A";) v Perfect! The last part is figuring out the syncing -- what I would like to do would be either: Video.sync_all_videos() #create another static method Or, if I had to, create another function that did a: for video in Video.objects.all(): # object.all() is a django function that returns everything ... video.sync() However, I am not sure how to determine the "actual" class of a video when I am dealing only with the parent. That is, how do I call a child's sync() function when I am dealing the parent object? Just run v.sync(); python's object model will determine the correct .sync() to call (i.e. v.sync() will call YoutubeVideo.sync(v) if isinstance(v, YoutubeVideo); OR ViemoVideo.sync(v) if isinstance(v, ViemoVideo); etc). This is known as `polymorphism`, in OOP terms. As suggested (in email below) I could re-run the regex for each parent video for each sync, but that seems like it could be an expensive operation (supposing one day I had thousands of videos to deal with). You're on the right mindset. It's not just an expensive operation, rechecking the url type on every function calls defeats the whole purpose of OOP. Check the url type only once when you instantiate the video container class, and use polymorphism for the rest of the day. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Initialize Class Variables by Dictionary ...
Hi again - thanks for your help with my question early today (and last night). Tried searching google for this next question but can't get an answer ... here is what I would like to do (but it is not working) ... >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} >>> class Test(): ... def __init__(self): ... for key in dict: ... self.key = dict[key] ... >>> t = Test() >>> t.test1 Traceback (most recent call last): File "", line 1, in AttributeError: Test instance has no attribute 'test1' >>> t.key 'value3' Can I do what I am dreaming of ? Thanks, Damon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Initialize Class Variables by Dictionary ...
On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote: > Hi again - thanks for your help with my question early today (and last > night). Tried searching google for this next question but can't get > an answer ... here is what I would like to do (but it is not working) > ... > > >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} > >>> class Test(): > ... def __init__(self): > ... for key in dict: > ... self.key = dict[key] > ... > >>> t = Test() > >>> t.test1 > Traceback (most recent call last): > File "", line 1, in > AttributeError: Test instance has no attribute 'test1' > >>> t.key > 'value3' > > Can I do what I am dreaming of ? Yes you can, but not that way. Here is how I did on my console: >>> class A(object): ... pass ... >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> setattr(A, 'test1', 'mytest') >>> dir(A) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test1'] >>> A.test1 'mytest' So, the key here is to use the setattr() builtin function. However keep in mind that I am a python beginner, so you would probably like to hear from some real tutors before implementing this solution all over your code... Mac. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] update html pages using python
Hi, I was wondering if anyone could point me in the right direction as far as the best way to use python to update html. Specifically, I have a python script which coordinates the rendering of image sequences to disk (rendered from Nuke, the compositing program) and also automates the creation of Quicktime movies based on these sequences. Added on to the end of this program, I would like to have a function which updates a cell in a table on a webpage to change the status of the shot from "in progress" to "new version ready for review". I have a reasonable understanding of text file reading, writing and parsing, but I was wondering if there is a module or some such thing that handles this kind of thing well. Ultimately I want to set up a page with a table of thumbnail images corresponding to sequences each with their own colour coding indicating status. Thanks for any help Pete ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] NLTK
On Sat, Aug 29, 2009 at 2:08 PM, Ishan Puri wrote: > Hi, > Yes! It works! I guess I am asking how did you know to use > wordlists.words('IM50re.txt')? Is this a specific command, as I believe it > was not in the book? It is taken directly from the example in the book: >>> wordlists.fileids() ['README', 'connectives', 'propernames', 'web2', 'web2a', 'words'] >>> wordlists.words('connectives') Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert binary files back to text files?
On Sat, Aug 29, 2009 at 9:02 AM, prasad rao wrote: > Hello! > I want to convert compiled files to text files. > > I believe compiled files are binary files. I don't understand what you are trying to do. Do you mean compiled Python files, e.g. .pyc files? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Initialize Class Variables by Dictionary ...
Hey! I am a newbie too but it works for me: >>> class Test(object): ... def __init__(self,dict): ... for key in dict: ... self.__setattr__(key,dict[key]) ... >>> t = Test() >>> t.test1 'hi there' >>> t.test2 'not so much' >>> t.test3 'etc' Thanks! On Sat, Aug 29, 2009 at 4:59 PM, Mac Ryan wrote: > On Sat, 2009-08-29 at 16:31 -0400, Damon Timm wrote: >> Hi again - thanks for your help with my question early today (and last >> night). Tried searching google for this next question but can't get >> an answer ... here is what I would like to do (but it is not working) >> ... >> >> >>>dict = {'test1': 'value1', 'test2': 'value2', 'test3': 'value3'} >> >>> class Test(): >> ... def __init__(self): >> ... for key in dict: >> ... self.key = dict[key] >> ... >> >>> t = Test() >> >>> t.test1 >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: Test instance has no attribute 'test1' >> >>> t.key >> 'value3' >> >> Can I do what I am dreaming of ? > > Yes you can, but not that way. Here is how I did on my console: > class A(object): > ... pass > ... dir(A) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', > '__str__', '__subclasshook__', '__weakref__'] setattr(A, 'test1', 'mytest') dir(A) > ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', > '__str__', '__subclasshook__', '__weakref__', 'test1'] A.test1 > 'mytest' > > So, the key here is to use the setattr() builtin function. > > However keep in mind that I am a python beginner, so you would probably > like to hear from some real tutors before implementing this solution all > over your code... > > Mac. > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert binary files back to text files?
"prasad rao" wrote I want to convert compiled files to text files. I believe compiled files are binary files. If you are talking about compiled executables made from C++ for example yes. But... I am able to convert a given string to binary and back to text. They are not just binary representations of the source code thay are translations of the C++ instruictions into the native binary codes of the target computer plus a whole bunch of housekeeping binary code that sets up the runtime environment. Decompiling a binary back to source code is incredibly difficult and even when done right the resulting code is barely recognisable compared to the original - for example a for loop may come out as a while loop - especially in C++ - and all variable names may be totally changed because the bninary doesn't need them (it uses memory addresses not names) So if thats what you are aiming for it won;t ever work. And a lot of software companies will be very happy that it won;t or lots of people would be stealing their proprietary and copyright code! But when it comes to a file it is proving to be impossible. Yes, see above... def p(a): s=open(a,'rb') for x in s: I doubt this will work for a binary file, you usually have to use read() and provide a buffer size. d=map(lambda y:chr(int(y,2)),x) This is assuming that the binary digits are all stored in individual lines, which is not the case, they are stored consecutively with no breaks, thats wgy you need to use read() and tell it how many bytes you want to read. What you appear to be doing is the equivalent to od -a in Unix - ie dump a file in its ascii representation. It would be instructive for you to try that command if you have access to a Unix box... Try it on a text file then try it on an executable file then try it on a compiled Pyhthon module. Finally try using the dis module in Python to look at the disassembled pcode - or just read the documentation for dis... p("C:/pp.txt") OK, Now you appear to be examining a tet file as if it were binary, thats different again - and slightly more doable. Could you explain what exacvtly you are trying to do - and why? Maybe we can help? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] update html pages using python
"pedro" wrote Hi, I was wondering if anyone could point me in the right direction as far as the best way to use python to update html. There are a number of modules in the standard library that can help but the best known module for this is BeautifulSoup which you have to download - try Google. There are a couple of others and all of them are better than trying to do it using normal text manipulation or regex... kind of thing well. Ultimately I want to set up a page with a table of thumbnail images corresponding to sequences each with their own colour coding indicating status. That should be fairly straightforward with any of the html parser modules available HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Initialize Class Variables by Dictionary ...
On Sat, Aug 29, 2009 at 6:30 PM, Damon Timm wrote: > Hey! I am a newbie too but it works for me: > class Test(object): > ... def __init__(self,dict): > ... for key in dict: > ... self.__setattr__(key,dict[key]) Use the setattr() builtin: setattr(self, key, dict[key]} or just def __init__(self, d): self.__dict__.update(d) BTW don't use dict as the name of a variable, it shadows the built-in of the same name. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] update html pages using python
On 2009-08-29 19:34:15 -0400, "Alan Gauld" said: "pedro" wrote Hi, I was wondering if anyone could point me in the right direction as far as the best way to use python to update html. There are a number of modules in the standard library that can help but the best known module for this is BeautifulSoup which you have to download - try Google. There are a couple of others and all of them are better than trying to do it using normal text manipulation or regex... kind of thing well. Ultimately I want to set up a page with a table of thumbnail images corresponding to sequences each with their own colour coding indicating status. That should be fairly straightforward with any of the html parser modules available HTH, Hi Alan, yes it looks like BeautifulSoup should do the trick. Thanks Pete ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor