Re: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
Peter, Spir - thanks for your time and effort! I am posting this query to few more Python mailers. Thank you, Sangeeth On Tue, Feb 25, 2014 at 5:22 AM, spir wrote: > On 02/24/2014 08:19 PM, Sangeeth Saravanaraj wrote: > >> Sorry, I should have described what I was trying! >> >> I want to create a decorator which should do the following things: >> >> - When an object of the decorated class is created, the objects name >> >> (say the value of the incoming "id" argument) should be stored as a >> record >> in a table in a database. >> - When an object of the decorated class is deleted, the record with >> this >> >> deleted objects name (i.e. object.id) should be removed from the >> table. >> >> You can safely assume that all the database operations are working fine! >> >> Now, for example - consider the following snippet: >> >> @saveme >> class A(object): >> def __init__(self, id): >> self.id = id >> >> @saveme >> class B(object): >> def __init__(self, id): >> self.id = id >> >> "saveme" should do what I have explained earlier. >> >> a1 = A("A1") >> a2 = A("A2") >> a3 = A("A3") >> b1 = B("B1") >> b2 = B("B2") >> >> At this point if I query and print all the records in a table, I should >> get >> the following: >> output: ["A1", "A2", "A3", "B1", "B2"] >> >> del a1 >> del a2 >> del a3 >> del b1 >> del b2 >> >> At this point, all entries in the table should be deleted; query should >> return an empty list! >> >> And, I want to highlight that the classes that are being decorated with >> "saveme" can de derived classes too! >> >> What is the best way to do this?! >> >> Thank you, >> >> Sangeeth >> > > Your problem looks like a typical "crosscutting" (transversal) concern > addressed by AOP (Aspect Oriented Programming). Their usual example is in > fact logging. Look at the wikipedia page: > https://en.wikipedia.org/wiki/Aspect-oriented_programming > > Not that it would help you solve it _in python_, but this may serve at > least to better understand what kind of problem you are actually facing; > and why it is annoying in programming (with common languages); what may be > your options. > > [I have no better approach than yours, using magic metamethods, and a > decorator to wrap it all.] > > > d > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
On 02/24/2014 08:19 PM, Sangeeth Saravanaraj wrote: Sorry, I should have described what I was trying! I want to create a decorator which should do the following things: - When an object of the decorated class is created, the objects name (say the value of the incoming "id" argument) should be stored as a record in a table in a database. - When an object of the decorated class is deleted, the record with this deleted objects name (i.e. object.id) should be removed from the table. You can safely assume that all the database operations are working fine! Now, for example - consider the following snippet: @saveme class A(object): def __init__(self, id): self.id = id @saveme class B(object): def __init__(self, id): self.id = id "saveme" should do what I have explained earlier. a1 = A("A1") a2 = A("A2") a3 = A("A3") b1 = B("B1") b2 = B("B2") At this point if I query and print all the records in a table, I should get the following: output: ["A1", "A2", "A3", "B1", "B2"] del a1 del a2 del a3 del b1 del b2 At this point, all entries in the table should be deleted; query should return an empty list! And, I want to highlight that the classes that are being decorated with "saveme" can de derived classes too! What is the best way to do this?! Thank you, Sangeeth Your problem looks like a typical "crosscutting" (transversal) concern addressed by AOP (Aspect Oriented Programming). Their usual example is in fact logging. Look at the wikipedia page: https://en.wikipedia.org/wiki/Aspect-oriented_programming Not that it would help you solve it _in python_, but this may serve at least to better understand what kind of problem you are actually facing; and why it is annoying in programming (with common languages); what may be your options. [I have no better approach than yours, using magic metamethods, and a decorator to wrap it all.] d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.call list vs. str argument
Last comment (apologies for being so fragmented!). I don't know why the literal strings there are raw there. Altogether, I'd expect: # cmd1 = ['sphinx-apidoc', '-f', '-F', '-H', title, '-A', author, '-V', version, '-o', output_dir, input_dir] retcode = subprocess.call(cmd1, shell=False) # ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.call list vs. str argument
There are a few issues there. I'd also recommend not trying to shell-quote these manually, # in the argument list of os.subprocess: r'-H', '"%s"' % title, r'-A', '"%s"' % author, r'-V', '"%s"' % version, Rather, just do the simpler thing: r'-H', title, r'-A', author, r'-V', version, in conjunction with passing the "shell=False" keyword argument. Don't escape. Just pass the arguments as is. As far as I can tell, trying to do shell escaping is not only unnecessary here, but doing without it makes the code cleaner safer. Maybe there's another reason why Albert-Jan's situation is different enough that "shell=True" is necessary, but the default situation should be to avoid it. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.call list vs. str argument
Peter Otten wrote: >> r'-f -F', >> r'-H', '"%s"' % title, > > "title" becomes \"title\", i. e. Python puts in an extra effort to have > the quotes survive the subsequent parsing process of the shell: > print subprocess.list2cmdline(['"title"']) > \"title\" Forget that :( Danny spotted the real problem. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.call list vs. str argument
Albert-Jan Roskam wrote: > Hi, > > In the code below, cmd1 and cmd2 are equivalent, as in: " ".join(cmd1) == > cmd2. But the first example returns a code 2, whereas the second runs > successfully. What is the difference? I prefer using a list as it looks a > little cleaner. Btw, shell=True is needed here. > > > # Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 > > import subprocess > > #1# returns retcode 2 (whatever error that maybe) > title, author, version = "title", "author", "1.0.0" > output_dir, input_dir = '/tmp/input', '/tmp/output' > cmd1 = [r'sphinx-apidoc', > r'-f -F', > r'-H', '"%s"' % title, "title" becomes \"title\", i. e. Python puts in an extra effort to have the quotes survive the subsequent parsing process of the shell: >>> print subprocess.list2cmdline(['"title"']) \"title\" > r'-A', '"%s"' % author, > r'-V', '"%s"' % version, > r'-o', output_dir, input_dir] > retcode = subprocess.call(cmd1, shell=True) > assert not retcode, retcode > > #2# returns retcode 0 (succes) > cmd2 = (r'sphinx-apidoc ' > r'-f -F ' > r'-H "%(title)s" ' > r'-A "%(author)s" ' > r'-V "%(version)s" ' > r'-o %(output_dir)s %(input_dir)s') % locals() > > retcode = subprocess.call(cmd2, shell=True) > assert not retcode, retcode > > # no AssertionError > assert " ".join(cmd1) == cmd2 > > > > Thanks in advance! > > Regards, > > Albert-Jan > > > > > ~~ > > All right, but apart from the sanitation, the medicine, education, wine, > public order, irrigation, roads, a > > fresh water system, and public health, what have the Romans ever done for > us? > > ~~ > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess.call list vs. str argument
> cmd1 = [r'sphinx-apidoc', >r'-f -F', This part looks suspicious. Are you sure you don't mean: '-f', '-F' here? They need to be separate arguments. Also, you mention: > Btw, shell=True is needed here. Why do you need shell expansion on the arguments? This can be dangerous unless you know what you're doing. See all the red-backgrounded warnings the subprocess documentation. For example: http://docs.python.org/2/library/subprocess.html#frequently-used-arguments ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess.call list vs. str argument
Hi, In the code below, cmd1 and cmd2 are equivalent, as in: " ".join(cmd1) == cmd2. But the first example returns a code 2, whereas the second runs successfully. What is the difference? I prefer using a list as it looks a little cleaner. Btw, shell=True is needed here. # Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 import subprocess #1# returns retcode 2 (whatever error that maybe) title, author, version = "title", "author", "1.0.0" output_dir, input_dir = '/tmp/input', '/tmp/output' cmd1 = [r'sphinx-apidoc', r'-f -F', r'-H', '"%s"' % title, r'-A', '"%s"' % author, r'-V', '"%s"' % version, r'-o', output_dir, input_dir] retcode = subprocess.call(cmd1, shell=True) assert not retcode, retcode #2# returns retcode 0 (succes) cmd2 = (r'sphinx-apidoc ' r'-f -F ' r'-H "%(title)s" ' r'-A "%(author)s" ' r'-V "%(version)s" ' r'-o %(output_dir)s %(input_dir)s') % locals() retcode = subprocess.call(cmd2, shell=True) assert not retcode, retcode # no AssertionError assert " ".join(cmd1) == cmd2 Thanks in advance! Regards, Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
Sangeeth Saravanaraj wrote: > On Mon, Feb 24, 2014 at 10:53 PM, Peter Otten <__pete...@web.de> wrote: > >> Sangeeth Saravanaraj wrote: >> >> > I am trying to capture an object initiation and deletion events using >> > the __call__() and __del__() methods with the following approach. >> >> Note that there is no guarantee that __dell__ will ever be called. >> Usually it is better to introduce a weakref with callback. >> >> > class A(object): >> > def __init__(self, klass): >> > print "A::__init__()" >> > self._klass = klass >> > >> > def __call__(self): >> > print "A::__call__()" >> > return self._klass() >> > >> > def __del__(self): >> > print "A::__del__()" >> > >> > class Parent1(object): >> > def __init__(self): >> > print "Parent1:: __init__()" >> > super(Parent1, self).__init__() >> > >> > class Parent2(object): >> > def __init__(self): >> > print "Parent2:: __init__()" >> > super(Parent2, self).__init__() >> > >> > @A >> > class B(Parent1, Parent2): >> > def __init__(self): >> > print "B::__init__()" >> > super(B, self).__init__() >> > >> > def main(): >> > b = B() >> > >> > if __name__ == "__main__": >> > main() >> > >> > >> > I decorate a class, say class B (whose object initiation and deletion I >> > wanted to capture) with a decorator class A. Please note that the class >> > B is derived from two classes - Parent1 & Parent2 and I want to use >> > super() method to initialise the parent classes. >> > >> > When I executed the above code snippet, I ran into the following issue: >> > >> > >> > A::__init__() >> > A::__call__() >> > B::__init__() >> > Traceback (most recent call last): >> > File "so.py", line 40, in >> > main() >> > File "so.py", line 36, in main >> > b = B() >> > File "so.py", line 10, in __call__ >> > return self._klass() >> > File "so.py", line 32, in __init__ >> > super(B, self).__init__() >> > TypeError: must be type, not A >> > A::__del__() >> > >> > >> > When I commented "super(B, self).__init__()" in the class B :: >> > __init__() method, it returned an object of type B and I was able to >> > see the prints in the __call__ and __del__ methods but the __init__() >> > methods of the >> base >> > classes (Parent1 & Parent2) are not called! >> > >> > From the error message, what I could understand is - the object >> > returned by A::__call__() is not of type B but of type A. But when I >> > put a print >> in >> > the A::__call__() I could see it returns an object of type B and not A. >> > >> > Now the question is - With this approach to capture the initiation and >> > deletion events of an object, how do I initialise the base classes >> > using super()? >> >> You'd have to introduce a naming convention or rewrite your class to be >> aware of the wrapping in some way: >> >> @A >> class B(Parent1, Parent2): >> def __init__(self): >> print "B::__init__()" >> super(B._klass, self).__init__() >> >> Not pretty. >> >> > Or, is there any other better way to capture the __call__ and __del__ >> > events for an object of a certain class - if so, how?! >> >> Most certainly, but you have to give some details about what you are up >> to first. >> > > Sorry, I should have described what I was trying! > > I want to create a decorator which should do the following things: > >- When an object of the decorated class is created, the objects name >(say the value of the incoming "id" argument) should be stored as a >record in a table in a database. >- When an object of the decorated class is deleted, the record with >this deleted objects name (i.e. object.id) should be removed from the >table. > > You can safely assume that all the database operations are working fine! > > Now, for example - consider the following snippet: > > @saveme > class A(object): > def __init__(self, id): > self.id = id > > @saveme > class B(object): > def __init__(self, id): > self.id = id > > "saveme" should do what I have explained earlier. > > a1 = A("A1") > a2 = A("A2") > a3 = A("A3") > b1 = B("B1") > b2 = B("B2") > > At this point if I query and print all the records in a table, I should > get the following: > output: ["A1", "A2", "A3", "B1", "B2"] > > del a1 > del a2 > del a3 > del b1 > del b2 > > At this point, all entries in the table should be deleted; query should > return an empty list! > > And, I want to highlight that the classes that are being decorated with > "saveme" can de derived classes too! > > What is the best way to do this?! I'm sorry, after a bit of try-and-error I could not come up with a good way to write such a decorator. My best effort so far uses inheritance: import itertools import weakref _registry = weakref.WeakValueDictionary() _next_id = lambda count=itertools.count(): next(count) def show(): print(list(_registry.values())) class Registered(object): def __i
Re: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
On Mon, Feb 24, 2014 at 10:53 PM, Peter Otten <__pete...@web.de> wrote: > Sangeeth Saravanaraj wrote: > > > I am trying to capture an object initiation and deletion events using the > > __call__() and __del__() methods with the following approach. > > Note that there is no guarantee that __dell__ will ever be called. Usually > it is better to introduce a weakref with callback. > > > class A(object): > > def __init__(self, klass): > > print "A::__init__()" > > self._klass = klass > > > > def __call__(self): > > print "A::__call__()" > > return self._klass() > > > > def __del__(self): > > print "A::__del__()" > > > > class Parent1(object): > > def __init__(self): > > print "Parent1:: __init__()" > > super(Parent1, self).__init__() > > > > class Parent2(object): > > def __init__(self): > > print "Parent2:: __init__()" > > super(Parent2, self).__init__() > > > > @A > > class B(Parent1, Parent2): > > def __init__(self): > > print "B::__init__()" > > super(B, self).__init__() > > > > def main(): > > b = B() > > > > if __name__ == "__main__": > > main() > > > > > > I decorate a class, say class B (whose object initiation and deletion I > > wanted to capture) with a decorator class A. Please note that the class B > > is derived from two classes - Parent1 & Parent2 and I want to use super() > > method to initialise the parent classes. > > > > When I executed the above code snippet, I ran into the following issue: > > > > > > A::__init__() > > A::__call__() > > B::__init__() > > Traceback (most recent call last): > > File "so.py", line 40, in > > main() > > File "so.py", line 36, in main > > b = B() > > File "so.py", line 10, in __call__ > > return self._klass() > > File "so.py", line 32, in __init__ > > super(B, self).__init__() > > TypeError: must be type, not A > > A::__del__() > > > > > > When I commented "super(B, self).__init__()" in the class B :: __init__() > > method, it returned an object of type B and I was able to see the prints > > in the __call__ and __del__ methods but the __init__() methods of the > base > > classes (Parent1 & Parent2) are not called! > > > > From the error message, what I could understand is - the object returned > > by A::__call__() is not of type B but of type A. But when I put a print > in > > the A::__call__() I could see it returns an object of type B and not A. > > > > Now the question is - With this approach to capture the initiation and > > deletion events of an object, how do I initialise the base classes using > > super()? > > You'd have to introduce a naming convention or rewrite your class to be > aware of the wrapping in some way: > > @A > class B(Parent1, Parent2): > def __init__(self): > print "B::__init__()" > super(B._klass, self).__init__() > > Not pretty. > > > Or, is there any other better way to capture the __call__ and __del__ > > events for an object of a certain class - if so, how?! > > Most certainly, but you have to give some details about what you are up to > first. > Sorry, I should have described what I was trying! I want to create a decorator which should do the following things: - When an object of the decorated class is created, the objects name (say the value of the incoming "id" argument) should be stored as a record in a table in a database. - When an object of the decorated class is deleted, the record with this deleted objects name (i.e. object.id) should be removed from the table. You can safely assume that all the database operations are working fine! Now, for example - consider the following snippet: @saveme class A(object): def __init__(self, id): self.id = id @saveme class B(object): def __init__(self, id): self.id = id "saveme" should do what I have explained earlier. a1 = A("A1") a2 = A("A2") a3 = A("A3") b1 = B("B1") b2 = B("B2") At this point if I query and print all the records in a table, I should get the following: output: ["A1", "A2", "A3", "B1", "B2"] del a1 del a2 del a3 del b1 del b2 At this point, all entries in the table should be deleted; query should return an empty list! And, I want to highlight that the classes that are being decorated with "saveme" can de derived classes too! What is the best way to do this?! Thank you, Sangeeth > > > PS: > > http://stackoverflow.com/questions/21826854/typeerror-when-using-super- > method-with-class-decorator-for-a-derived-class > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i dont understand this code
It's also a bit unreasonable to ask us to reverse-engineer code that is orginally CRC-16 code. Whoever you got this code from is violating the GPL by stripping out the comments or the COPYRIGHT license from the original sources. This is perhaps unintentional. Please ask them to correct the problem. The original sources appear to have come from: http://dogber1.blogspot.com/2009/05/table-of-reverse-engineered-bios.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to perform a google advanced search using python
> Ah yes, here you go: > > https://developers.google.com/custom-search/?csw=1 Also see the "Indexable file types" help topic: https://support.google.com/webmasters/answer/35287?hl=en ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
Sangeeth Saravanaraj wrote: > I am trying to capture an object initiation and deletion events using the > __call__() and __del__() methods with the following approach. Note that there is no guarantee that __dell__ will ever be called. Usually it is better to introduce a weakref with callback. > class A(object): > def __init__(self, klass): > print "A::__init__()" > self._klass = klass > > def __call__(self): > print "A::__call__()" > return self._klass() > > def __del__(self): > print "A::__del__()" > > class Parent1(object): > def __init__(self): > print "Parent1:: __init__()" > super(Parent1, self).__init__() > > class Parent2(object): > def __init__(self): > print "Parent2:: __init__()" > super(Parent2, self).__init__() > > @A > class B(Parent1, Parent2): > def __init__(self): > print "B::__init__()" > super(B, self).__init__() > > def main(): > b = B() > > if __name__ == "__main__": > main() > > > I decorate a class, say class B (whose object initiation and deletion I > wanted to capture) with a decorator class A. Please note that the class B > is derived from two classes - Parent1 & Parent2 and I want to use super() > method to initialise the parent classes. > > When I executed the above code snippet, I ran into the following issue: > > > A::__init__() > A::__call__() > B::__init__() > Traceback (most recent call last): > File "so.py", line 40, in > main() > File "so.py", line 36, in main > b = B() > File "so.py", line 10, in __call__ > return self._klass() > File "so.py", line 32, in __init__ > super(B, self).__init__() > TypeError: must be type, not A > A::__del__() > > > When I commented "super(B, self).__init__()" in the class B :: __init__() > method, it returned an object of type B and I was able to see the prints > in the __call__ and __del__ methods but the __init__() methods of the base > classes (Parent1 & Parent2) are not called! > > From the error message, what I could understand is - the object returned > by A::__call__() is not of type B but of type A. But when I put a print in > the A::__call__() I could see it returns an object of type B and not A. > > Now the question is - With this approach to capture the initiation and > deletion events of an object, how do I initialise the base classes using > super()? You'd have to introduce a naming convention or rewrite your class to be aware of the wrapping in some way: @A class B(Parent1, Parent2): def __init__(self): print "B::__init__()" super(B._klass, self).__init__() Not pretty. > Or, is there any other better way to capture the __call__ and __del__ > events for an object of a certain class - if so, how?! Most certainly, but you have to give some details about what you are up to first. > PS: > http://stackoverflow.com/questions/21826854/typeerror-when-using-super- method-with-class-decorator-for-a-derived-class ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.symlink can't find target
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 24/02/14 16:56, Mark Lawrence wrote: > On 24/02/2014 16:36, Peter Otten wrote: >> Bob Williams wrote: >> [...] >>> Thanks, >> >> os.symlink(existing_file, symlink_to_create) >> >> fails with that error if the directory that shall contain the new >> symlink does not exist. You can create it before making the >> symlink with >> >> try: os.makedirs(os.path.dirname(symlink_to_create)) except >> OSError as err: # Assume the directory exists. # A thorough coder >> would check the errno here pass >> > > Python 3.3+ allows finer grained error handling than that shown > above, so you could catch FileExistsError, see > http://legacy.python.org/dev/peps/pep-3151/ for the details. > I'm using a module (mutagen) elsewhere in this script, which only works in Python 2 (so far). Also, I'm fairly new to this, so getting things working takes precedence over 'good practice' like error trapping. But I'm also aware that it's best to establish good habits early on. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLfOMACgkQ0Sr7eZJrmU4IgQCgn5MeqNsCOgiS3QY8g2jjMooR 65oAnjcWZaHrfe78C2WvHjMNlqZqjgo1 =CnnC -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.symlink can't find target
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 24/02/14 16:36, Peter Otten wrote: > os.symlink(existing_file, symlink_to_create) > > fails with that error if the directory that shall contain the new > symlink does not exist. You can create it before making the symlink > with > Peter, Many thanks. I was fixating on the existing_file, not realising I had to create a home for the symlink first. > try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError > as err: # Assume the directory exists. # A thorough coder would > check the errno here pass Regards Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLe3QACgkQ0Sr7eZJrmU6QmQCeLUSIh0l97T017KrIHXT92Xhd YuQAn2To2AOXNpbA4fZ+4i6Swt4RdsMg =NgLw -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.symlink can't find target
On 24/02/2014 16:36, Peter Otten wrote: Bob Williams wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 My operating system is Linux (openSUSE 13.1). I'm trying to create symlinks. The following code: if pathList[j][-3:] == "mp3": linkName1 = pathList[j][0:-3] + "mp3" linkName2 = destPath + linkName1[len(sourcePath):] print 'Creating link %s -> %s' % (linkName2, pathList[j]) os.symlink(pathList[j], linkName2) fails with this error: Creating link /pollux/music/portable/testing/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 Traceback (most recent call last): File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in os.symlink(pathList[j], linkName2) OSError: [Errno 2] No such file or directory The same thing happens in ipython, when I type the paths in manually. I have tried escaping the spaces with '\', but the same error is generated. The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3" definitely exists. Thanks, os.symlink(existing_file, symlink_to_create) fails with that error if the directory that shall contain the new symlink does not exist. You can create it before making the symlink with try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError as err: # Assume the directory exists. # A thorough coder would check the errno here pass Python 3.3+ allows finer grained error handling than that shown above, so you could catch FileExistsError, see http://legacy.python.org/dev/peps/pep-3151/ for the details. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I can't understand where python class methods come from
Thank you all for your responses. My first post on the list an I already got more than I asked for. :) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError
I am trying to capture an object initiation and deletion events using the __call__() and __del__() methods with the following approach. class A(object): def __init__(self, klass): print "A::__init__()" self._klass = klass def __call__(self): print "A::__call__()" return self._klass() def __del__(self): print "A::__del__()" class Parent1(object): def __init__(self): print "Parent1:: __init__()" super(Parent1, self).__init__() class Parent2(object): def __init__(self): print "Parent2:: __init__()" super(Parent2, self).__init__() @A class B(Parent1, Parent2): def __init__(self): print "B::__init__()" super(B, self).__init__() def main(): b = B() if __name__ == "__main__": main() I decorate a class, say class B (whose object initiation and deletion I wanted to capture) with a decorator class A. Please note that the class B is derived from two classes - Parent1 & Parent2 and I want to use super() method to initialise the parent classes. When I executed the above code snippet, I ran into the following issue: A::__init__() A::__call__() B::__init__() Traceback (most recent call last): File "so.py", line 40, in main() File "so.py", line 36, in main b = B() File "so.py", line 10, in __call__ return self._klass() File "so.py", line 32, in __init__ super(B, self).__init__() TypeError: must be type, not A A::__del__() When I commented "super(B, self).__init__()" in the class B :: __init__() method, it returned an object of type B and I was able to see the prints in the __call__ and __del__ methods but the __init__() methods of the base classes (Parent1 & Parent2) are not called! >From the error message, what I could understand is - the object returned by A::__call__() is not of type B but of type A. But when I put a print in the A::__call__() I could see it returns an object of type B and not A. Now the question is - With this approach to capture the initiation and deletion events of an object, how do I initialise the base classes using super()? Or, is there any other better way to capture the __call__ and __del__ events for an object of a certain class - if so, how?! Thank you, Sangeeth PS: http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.symlink can't find target
Bob Williams wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > My operating system is Linux (openSUSE 13.1). > > I'm trying to create symlinks. The following code: > > if pathList[j][-3:] == "mp3": > linkName1 = pathList[j][0:-3] + "mp3" > linkName2 = destPath + linkName1[len(sourcePath):] > print 'Creating link %s -> %s' % (linkName2, pathList[j]) > os.symlink(pathList[j], linkName2) > > fails with this error: > > > Creating link /pollux/music/portable/testing/artists/Death in > June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> > /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 > Lifebooks.mp3 > Traceback (most recent call last): > File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in > > os.symlink(pathList[j], linkName2) > OSError: [Errno 2] No such file or directory > > The same thing happens in ipython, when I type the paths in manually. > I have tried escaping the spaces with '\', but the same error is > generated. > > The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of > Holocaust/10 Lifebooks.mp3" definitely exists. > > Thanks, os.symlink(existing_file, symlink_to_create) fails with that error if the directory that shall contain the new symlink does not exist. You can create it before making the symlink with try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError as err: # Assume the directory exists. # A thorough coder would check the errno here pass ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] os.symlink can't find target
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 My operating system is Linux (openSUSE 13.1). I'm trying to create symlinks. The following code: if pathList[j][-3:] == "mp3": linkName1 = pathList[j][0:-3] + "mp3" linkName2 = destPath + linkName1[len(sourcePath):] print 'Creating link %s -> %s' % (linkName2, pathList[j]) os.symlink(pathList[j], linkName2) fails with this error: Creating link /pollux/music/portable/testing/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 Traceback (most recent call last): File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in os.symlink(pathList[j], linkName2) OSError: [Errno 2] No such file or directory The same thing happens in ipython, when I type the paths in manually. I have tried escaping the spaces with '\', but the same error is generated. The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3" definitely exists. Thanks, Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -BEGIN PGP SIGNATURE- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLblkACgkQ0Sr7eZJrmU4qfACdGc7/U8dN6I/NcyJsHA7ILzcV Ea4AoIHSbWLkg5eQ1Lo5rN7z0FTse+YM =+wrZ -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to perform a google advanced search using python
On Mon, Feb 24, 2014 at 04:37:36PM +0800, Xenai Hatsotep wrote: > I have a python program which performs a simple google search. What i > really want to do is perform an advanced search such that i can search > for pdf files and ppt files in google. Any help on this subject would > be very helpful. Sorry, I don't have an answer for you, but I have a warning. I am pretty sure that what you are doing is against Google's terms of service, and if they spot what you are doing they might ban you. I believe that they have an official API for doing searches programmatically. Ah yes, here you go: https://developers.google.com/custom-search/?csw=1 You might also consider Duck Duck Go: https://duckduckgo.com/api -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to perform a google advanced search using python
I have a python program which performs a simple google search. What i really want to do is perform an advanced search such that i can search for pdf files and ppt files in google. Any help on this subject would be very helpful. I have attached the search.py program i'm using with this mail. import urllib2 def getgoogleurl(search,siteurl=False): if siteurl==False: return 'http://www.google.com/search?q='+urllib2.quote(search)+'&oq='+urllib2.quote(search) else: return 'http://www.google.com/search?q=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)+'&oq=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search) def getgooglelinks(search,siteurl=False): #google returns 403 without user agent headers = {'User-agent':'Mozilla/11.0'} req = urllib2.Request(getgoogleurl(search,siteurl),None,headers) site = urllib2.urlopen(req) data = site.read() site.close() #no beatifulsoup because google html is generated with javascript start = data.find('') end = data.find('') if data[start:end]=='': #error, no links to find return False else: links =[] data = data[start:end] start = 0 end = 0 while start>-1 and end>-1: #get only results of the provided site if siteurl==False: start = data.find('http://www.google.com/') for link in links: print link___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 120, Issue 20
hey guys your tutorials really have me a lot and i managed to pass python and i would like you to continue sending me those tutorials so i can do more practice as far as the future is concerned.. I would also like to enroll on the java tutorials that's if you provide them... THANKS IN ADVANCE Regards Daisy Kebadiretse Magunga___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I can't understand where python class methods come from
On 02/23/2014 10:59 PM, voger wrote: I have a really hard time understanding where methods are defined in python classes. My first contact with programming was with C++ and Java and even if I was messing with them in a very amateurish level, I could find where each class was defined and what methods were defined inside them. Everything was clear and comprehensive. With python everything looks like magic. Methods and properties appearing out of nowhere and somehow easing the task at hand. I am not complaining for their existence but I really can't understand how and what is defined so I can use it. In general, python classes look like: class Point: def __init__ (self, x, y): self.x = x self.y = y self.d = x + y # square distance def move (self, dx, dy): self.x += dx self.y == dy def __str__ (self): return "{%s %s}" % (self.x, self.y) (Try using it if needed.) A valid complaint --which I share-- is that python classes do not obviously show data attributes. Maybe from other languages you'd rather expect something like: class Point: data = x , y, d # data attr (no static typing) def __init__ (self, x, y): self.d = x + y # square distance def move (self, dx, dy): self.x += dx self.y == dy def __str__ (self): return "{%s %s}" % (self.x, self.y) In python, you have to look inside __init__ (and sometimes also other methods just to know what are the actual data defining a given class's instances. Enough ranting and let me give an example of what I mean. Let's have a look at the pygeocoder library located here: http://code.xster.net/pygeocoder/src/c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default This code is very unusual and indeed pretty magic. The big schema is that instead of computing and setting all data attributes at init time, it only does it *on demand*. To do so, it intercepts your requests (eg "x = addr.attr") in the "magic metamethod" called __getattr__. This method is called, as name suggests, when you request to read one of an object's attributes. You can even to similar magic with methods (since they are looked up as well), but it even more rare. Anyway, such metamagic is indeed advanced python programing and maybe you shouldn't bother with it now. d ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
Scott W Dunning wrote: > > On Feb 23, 2014, at 2:26 AM, Peter Otten <__pete...@web.de> wrote: >> If you want to make rows with more or less stars, or stars in other >> colors you could add parameters: >> >> def star_row(numstars, starcolor): >>for i in range(numstars): >>fillstar(starcolor) >>space(25) >> >> Your code will then become >> >> star_row(6, red) >> row(25) >> star_row(5, red) >> row(25) >> > I have a question with the above loop function. Why couldn’t row(25) be > added into the function so that wouldn’t have to placed in between every > star_row()? That's of course possible. >> which still shows a repetetive pattern and thus you can simplify it with >> another loop. You should be able to find a way to write that loop with >> two star_row() calls on a single iteration, but can you do it with a >> single call too? > Not sure I understand what you mean in the above paragraph? What you found out later and put in you next post: This repetetive pattern > star_row(5) # oops, typo > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) can be turned into this for loop: > This is what I’m thinking… > > for I in range(4) > star_row(5) > row(25) > star_row(6) > row(25) > > Am I at all close? You hit the jackpot :) Now on to the next challenge: for row_index in range(9): row_width = ... star_row(row_width) row(25) Can you replace the ... with a calculation to get row_width=6 for even and row_width=5 for odd rows? Hint: look at the % ("modulo") operator. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
On 24/02/14 02:04, Scott W Dunning wrote: *Also, does anyone know anything about turtle where I can try and move the starting point to the upper left hand corner? * dir() and help() are your friends. After doing dir(turtle) I spooted this likely looking candidate and ran help on it: -- setposition(x, y=None) Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. etc -- Similarly, I found the window_width() and window_height() methods. So, to get to the top left corner you'd goto( -window_width/2, window_height/2 ) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
On Feb 23, 2014, at 2:26 AM, Peter Otten <__pete...@web.de> wrote: > which still shows a repetetive pattern and thus you can simplify it with > another loop. You should be able to find a way to write that loop with two > star_row() calls on a single iteration, but can you do it with a single call > too? So, I was able to cut it down a bit but I’m having a hard time trying to cut it down with another loop and a single call. Wouldn’t what you’re saying in the above paragraph have to be another function with a loop inside? Or are you saying just another loop will suffice? Any hints? Here is what I got so far, I’ll put the loop in question in bold. from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() def star_row(numberstars): for i in range (numberstars): fillstar(red) space(25) star_row(5) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) This is what I’m thinking… for I in range(4) star_row(5) row(25) star_row(6) row(25) Am I at all close? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
On Feb 23, 2014, at 2:26 AM, Peter Otten <__pete...@web.de> wrote: > If you want to make rows with more or less stars, or stars in other colors > you could add parameters: > > def star_row(numstars, starcolor): >for i in range(numstars): >fillstar(starcolor) >space(25) > > Your code will then become > > star_row(6, red) > row(25) > star_row(5, red) > row(25) > I have a question with the above loop function. Why couldn’t row(25) be added into the function so that wouldn’t have to placed in between every star_row()? > > which still shows a repetetive pattern and thus you can simplify it with > another loop. You should be able to find a way to write that loop with two > star_row() calls on a single iteration, but can you do it with a single call > too? Not sure I understand what you mean in the above paragraph? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
On Feb 23, 2014, at 2:26 AM, Peter Otten <__pete...@web.de> wrote > a programmer would think "for loop” immediately That’s what I thought. It just seemed like way to much to keep repeating everything over and over. I knew there had to be a better way we just haven’t learned loops in school yet. > > for i in range(5): >fillstar(red) >space(25) Awesome, I was able to cut everything down quite a bit but, now like you say below I’m still repeating the loop. I’m gonna see if I can make a function with the loop to cut it down even further. Here is what I was able to cut it down to so far with your help. I’ll paste the new code when I make a function with the loop and maybe you guys can help me see if it look any better/easier. Also, does anyone know anything about turtle where I can try and move the starting point to the upper left hand corner? Thanks again! Scott from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) for i in range (5): fillstar(red) space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() row(25) for i in range (5): fillstar(red) space(25) row(25) for i in range (6): fillstar(red) space(25) row(25) for i in range (5): fillstar(red) space(25) row(25) for i in range (6): fillstar(red) space(25) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function help
On Feb 23, 2014, at 5:31 AM, Dave Angel wrote: > > Welcome to the tutor forum also, Scott. You'll find it works very > similarly to python-list, and has many of the same people on it. > I'm not sure how you tried to attach source, but please be aware > that this is a text list - anything other than plain text will > probably be invisible or inconvenient to someone. Just paste > snippets inline when needed. I actually forgot to paste the code before I sent the email. > > What you're looking for is a loop. for and while are the two > keywords for looping. In this case, since you know how many > times you want to go round, loop is appropriate. Build a > collection or iterator of length 5, and loop over it. range is > designed for the purpose: > > for index in range (5): > dosomething > moresomething (index) Thank you for this help. I believe I understand. At least enough to do a simple loop for what I need. I’ll check back and paste my code after and maybe you can tell me if there is anything I could be doing better/easier. Thanks again!! Scott ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor