Re: [Tutor] Tips
On Thu, Jun 19, 2014 at 11:10:26AM -0700, Alex Kleider wrote: > The idea of a singleton class is new to me as is this comparison of > class vs module. > Can anyone suggest a place to turn for more discussion of the topic? > thks, alexK "Singleton" is one of the classic "design patterns", although these days people are equally divided on whether it's a design pattern or anti-pattern. The idea of design patterns is that they are a standard way of solving a certain type of problem. For example, in the real world, there are various problems which have a certain factor in common: Example problems: - Painting a mural on the ceiling. Building a house. Replacing a broken window on the 2nd story. Making a tree house. Class of problem: - There is work needed at a height well above what you can reach from the ground. General solution: - Use scaffolding to raise the height at which you can comfortably work. So "scaffolding" is the design pattern. Actual scaffolds may be made from many different materials (steel, timber, bamboo) and in many different shapes and sizes, but they're all scaffolds. Rather than there being a "one size fits all" solution for all problems, instead there is a general solution that you customize for the specific problem. The size and shape of the scaffolding needed to replace a broken window will be different than that needed to build a house. Design patterns for software are like scaffolds: a design pattern is not a language feature or function you can call, but a general technique to be used to solve a class of problems. https://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29 Explicit use of design patterns is very, very big in the Java and Dot Net worlds, less so in other programming languages. To learn more, Duck Duck Go is your friend: https://duckduckgo.com/html/?q=singleton+design+pattern https://duckduckgo.com/html/?q=singleton+anti-pattern If you still prefer Google: https://www.google.com/search?q=singleton+design+pattern or feel free to ask questions here. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
- Original Message - > From: Alex Kleider > To: tutor@python.org > Cc: > Sent: Thursday, June 19, 2014 8:10 PM > Subject: Re: [Tutor] Tips > > On 2014-06-18 18:37, Steven D'Aprano wrote: >> Python tries very hard to ensure that every module is loaded only once. >> (There are circumstances where you can fool it, but they're rare.) >> Since >> the module holds state (variables) and behaviour (functions), modules >> perform the same sort of role as classes, so a module which is loaded >> once is very similar to a singleton instance. In other words, if you >> want a class to implement singleton behaviour, you have to work at it. >> But if you shift the functionality from the class into a module, Python >> gives you singleton behaviour for free. >> >> But if you're not sure why anyone would want a singleton instance, I >> agree with you: most (but not all) uses of singletons are unnecessary. > > The idea of a singleton class is new to me as is this comparison of > class vs module. > Can anyone suggest a place to turn for more discussion of the topic? > thks, alexK Maybe this (it's about Singleton and Borg): http://stackoverflow.com/questions/1318406/why-is-the-borg-pattern-better-than-the-singleton-pattern-in-python ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On 19/06/14 15:35, Ian D wrote: Ok and do I leave all this rubbish at the bottom? or edit it. Delete as much as possible that is not needed to understand the reply. But only as much as necessary, err on the generous side if in doubt. But definitely things like the Python mailing list comments etc can be deleted - we've all seen them multiple times! :-) -- 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] Tips
On 2014-06-18 18:37, Steven D'Aprano wrote: Python tries very hard to ensure that every module is loaded only once. (There are circumstances where you can fool it, but they're rare.) Since the module holds state (variables) and behaviour (functions), modules perform the same sort of role as classes, so a module which is loaded once is very similar to a singleton instance. In other words, if you want a class to implement singleton behaviour, you have to work at it. But if you shift the functionality from the class into a module, Python gives you singleton behaviour for free. But if you're not sure why anyone would want a singleton instance, I agree with you: most (but not all) uses of singletons are unnecessary. The idea of a singleton class is new to me as is this comparison of class vs module. Can anyone suggest a place to turn for more discussion of the topic? thks, alexK ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] write dictionary to file
On Thu, Jun 19, 2014 at 8:13 AM, Ian D wrote: > When trying to write my dictionary to a file I get: > > > f.write(output) > TypeError: 'tuple' does not support the buffer interface When writing structured data to disk files, you need to do something extra, because what disk files support are the reading and writing of raw bytes. That is, there are multiple ways to get that structured data to disk, so you've got to choose! :P Typically, you'll use some function to "encode" your structured data into a linear byte string, and write the byte string to disk. Later, to recover that structure, you use another function to "decode" the linear byte string back into structured data. There are several encoder/decoder libraries in Python that you can use. A popular one is the JSON library: it's popular because JSON is well-supported by other programming languages. https://docs.python.org/2/library/json.html But in your case, you probably want to stick with CSV, since that's what your input is in. > So is it the csv.DictWriter that is needed here? That's probably most appropriate in your situation, yes. Since you're using csv.DictReader, it does make sense to use csv.DictWriter when you're storing the data if you want to use the same encoding format. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] write dictionary to file
When trying to write my dictionary to a file I get: f.write(output) TypeError: 'tuple' does not support the buffer interface using this example: #so far this should read a file #using dictreader and take a column and join some text onto it import csv csvfile= open('StudentListToSort.csv', newline='') spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|') #open a file to write to later f = open('output.csv', 'wb+') #iterate through dictreader object for row in spamreader: if row['year'] == '40': username = row['user'] #I put stuff in variables for ease of viewing/debugging email = "".join([username,'@email.com]) # join text #put output for file in variable first output = email, row['first'],row['last'],row['password'] #change tuple to list #outputlist= list(output) #write results to file f.write(output) print(output) I then tried to cast the tuple to a list thinking that would help like this: #change tuple to list #outputlist= list(output) #write results to file f.write(outputlist) print(outputlist) same problem: f.write(outputlist) TypeError: 'list' does not support the buffer interface So is it the csv.DictWriter that is needed here? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On 19/06/2014 15:35, Ian D wrote: Ok and do I leave all this rubbish at the bottom? or edit it. Or is it bad practice to edit someone's text ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor If you're referring to the stuff above I usually delete it. It is bad practice to edit the text if it changes the context. It is good practice if (say) you're replying to only one paragraph out of ten. -- 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] python libraries online
> Date: Fri, 20 Jun 2014 00:30:49 +1000 > From: st...@pearwood.info > To: tutor@python.org > Subject: Re: [Tutor] python libraries online > > On Thu, Jun 19, 2014 at 12:59:58PM +, Ian D wrote: >> What does top post mean? > > It means posting at the top of the reply, just as you have done here. > > When you reply to an email, the comments you are replying to are quoted > with greater-than signs> at the start of each line. There are three > basic places to insert your replies to the comments being quoted: at the > top, at the bottom, and interleaved through the middle. > > Here is an example. Suppose I write an email asking two questions: > > Hello, how long should I boil a soft-boiled egg? > And how many eggs in a dozen? > > > (I didn't say they were *good* questions.) You reply, and my comments are > quoted: > > === This is top-posting === > > Oh, about 3 minutes, depending on the size of the egg. > Twelve eggs. > > Steven asked: >> Hello, how long should I boil a soft-boiled egg? >> And how many eggs in a dozen? > > > === This is bottom-posting === > > Steven asked: >> Hello, how long should I boil a soft-boiled egg? >> And how many eggs in a dozen? > > Oh, about 3 minutes, depending on the size of the egg. > Twelve eggs. > > > === This is interleaved posting === > > Steven asked: >> Hello, how long should I boil a soft-boiled egg? > > Oh, about 3 minutes, depending on the size of the egg. > >> And how many eggs in a dozen? > > Twelve eggs. > > === > > > For detailed, complicated discussions where people are replying to > multiple points, interleaved posting is by far the best. It is like > carrying on a conversation: > >> Question > Answer >> Question > Answer >> Point > Counter-point >> Question > Answer > > > The context for each answer is right there, next to the answer. It makes > the email *much* easier to follow when things get technical and > complicated. > > Top-posting and bottom-posting are okay for short, trivial responses > where the context is not very important, but sadly they also get used by > lazy writers who don't care about the people reading the email. > > (I hope I do not offend, but I've been dealing with email for close to > 20 years and in my experience there are a lot of lazy writers. If you've > ever asked somebody four questions in an email, and they've fired off a > reply answering one of them and ignoring the other three, you will know > what I mean.) > > Top-posting encourages short, snappy responses, where the context can > be inferred from the subject line or the first few sentences of the > quoted comments: > > > Okay see you there. >> Hey Bill, meet us at the pub tonight? > > > 2pm >> Sue, what time is the meeting today? > > > Yes. >> Do you want the 2TB hard drive or a 1TB hard drive? > > > But for technical discussions, short, snappy responses are often not > very good. A *discussion* may go back and forth over many different > points, not just one or two sentence replies. For this reason, in > technical forums like this one, interleaved posting is MUCH preferred. > > > > -- > Steven > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Ok and do I leave all this rubbish at the bottom? or edit it. Or is it bad practice to edit someone's text ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On Thu, Jun 19, 2014 at 12:59:58PM +, Ian D wrote: > What does top post mean? It means posting at the top of the reply, just as you have done here. When you reply to an email, the comments you are replying to are quoted with greater-than signs > at the start of each line. There are three basic places to insert your replies to the comments being quoted: at the top, at the bottom, and interleaved through the middle. Here is an example. Suppose I write an email asking two questions: Hello, how long should I boil a soft-boiled egg? And how many eggs in a dozen? (I didn't say they were *good* questions.) You reply, and my comments are quoted: === This is top-posting === Oh, about 3 minutes, depending on the size of the egg. Twelve eggs. Steven asked: > Hello, how long should I boil a soft-boiled egg? > And how many eggs in a dozen? === This is bottom-posting === Steven asked: > Hello, how long should I boil a soft-boiled egg? > And how many eggs in a dozen? Oh, about 3 minutes, depending on the size of the egg. Twelve eggs. === This is interleaved posting === Steven asked: > Hello, how long should I boil a soft-boiled egg? Oh, about 3 minutes, depending on the size of the egg. > And how many eggs in a dozen? Twelve eggs. === For detailed, complicated discussions where people are replying to multiple points, interleaved posting is by far the best. It is like carrying on a conversation: > Question Answer > Question Answer > Point Counter-point > Question Answer The context for each answer is right there, next to the answer. It makes the email *much* easier to follow when things get technical and complicated. Top-posting and bottom-posting are okay for short, trivial responses where the context is not very important, but sadly they also get used by lazy writers who don't care about the people reading the email. (I hope I do not offend, but I've been dealing with email for close to 20 years and in my experience there are a lot of lazy writers. If you've ever asked somebody four questions in an email, and they've fired off a reply answering one of them and ignoring the other three, you will know what I mean.) Top-posting encourages short, snappy responses, where the context can be inferred from the subject line or the first few sentences of the quoted comments: Okay see you there. > Hey Bill, meet us at the pub tonight? 2pm > Sue, what time is the meeting today? Yes. > Do you want the 2TB hard drive or a 1TB hard drive? But for technical discussions, short, snappy responses are often not very good. A *discussion* may go back and forth over many different points, not just one or two sentence replies. For this reason, in technical forums like this one, interleaved posting is MUCH preferred. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On Thu, Jun 19, 2014 at 12:37:17PM +, Ian D wrote: > And I wondered what 'cpython' was when I came across it. I thought > they might have called it python Python is the name of the programming languages. There are many different implementations of that programming language: - Jython is Python written in Java - IronPython is Python written for Dot-Net - PyPy is a high-performance optimizing Just-In-Time compiler for Python - Stackless is a version of Python that doesn't use the C calling stack - Nuitka is a static compiler for Python written in C++ - and of course, there is the plain old ordinary "python" you are used to, the reference implementation, also called "CPython" because the compiler is written in C. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
What does top post mean? > To: tutor@python.org > From: breamore...@yahoo.co.uk > Date: Thu, 19 Jun 2014 13:46:03 +0100 > Subject: Re: [Tutor] python libraries online > > On 19/06/2014 13:37, Ian D wrote: >> And I wondered what 'cpython' was when I came across it. I thought they >> might have called it python >> > > Cpython because it's written in C. Look closely at the repository > you'll find Jython there as well, it's written in Java. There are > umpteen other Python versions, IronPython for .Net amongst others. > > Please don't top post on this list, it's extremely irritating following > long threads when this is done. > > -- > 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 > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On Thu, Jun 19, 2014 at 5:18 AM, Ian D wrote: > A while back some one linked to the python source and I was able to view the > whole of its libraries and class files something like this java api site > http://docs.oracle.com/javase/7/docs/api/ > > > But I cant seem to find what I want now. > > > I wanted to be able to look at the classes etc Hi Ian, Are you looking for the Library Reference? You can find it here: https://docs.python.org/2/library/index.html It should describe the functionality of the standard library. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
- Original Message - > From: Mark Lawrence > To: tutor@python.org > Cc: > Sent: Thursday, June 19, 2014 2:40 PM > Subject: Re: [Tutor] Tips > > On 19/06/2014 10:09, Albert-Jan Roskam wrote: >>> From: Mark Lawrence >>> To: tutor@python.org >>> Cc: >>> Sent: Thursday, June 19, 2014 8:41 AM >>> Subject: Re: [Tutor] Tips >>> >>> On 19/06/2014 02:36, Danny Yoo wrote: [content about __add__ dispatch resolution cut] We should remember the target audience, lest this thread > doesn't spiral away so that only the tutors are talking to each other. > I'm guilty of this as anyone, mind you. Pot. Kettle. :P > I didn't write any of the above. Did you mean to reply to me, but > inadvertantly snipped too much, or did you mean to reply to Danny, or what? Sorry, yes I intended to reply to Danny's Pot/Kettle remark. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On 19/06/2014 13:37, Ian D wrote: And I wondered what 'cpython' was when I came across it. I thought they might have called it python Cpython because it's written in C. Look closely at the repository you'll find Jython there as well, it's written in Java. There are umpteen other Python versions, IronPython for .Net amongst others. Please don't top post on this list, it's extremely irritating following long threads when this is done. -- 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] Tips
On Tue, Jun 17, 2014 at 02:52:33PM -0400, keith papa wrote: > > Hi, I want to no what some tips or information you can give me to > remember some of the rules of python, when you first start learning > programming? Questions about memory (that is, *human* memory, in the brain) are not really on-topic for this list. We're not likely to be experts on how memory works. (I'm a little dubious that *anyone* is an expert on how memory works, but that's another story.) But having said that, what worked for me was, practice practice and even more practice. I have spent *years* writing little bits of Python code. 99.9% of that code was junk, and either never finished, or thrown away but it's still good practice. If you want to be a master carpenter, you have to expect to spend a lot of time making rubbish before you make your masterpiece. Same applies to programming. Get used to *reading* Python code. (It's easier to read something than to write it.) You will find huge amounts of Python code on the Internet, on Wikipedia, on the Activestate cookbook, on the tutor archives, in the Python standard library, and more: https://en.wikipedia.org/wiki/Python_%28programming_language%29 http://code.activestate.com/recipes/langs/python/ https://mail.python.org/pipermail/tutor/ http://hg.python.org/cpython/file/cf70f030a744/Lib/ https://wiki.python.org/moin/SimplePrograms http://rosettacode.org/wiki/Category:Python To learn to program in Python, you need to spend time writing Python code as well as reading it. You'll make mistakes. That's *good*. Every time you make a mistake: py> for i = 1 to 20: File "", line 1 for i = 1 to 20: ^ SyntaxError: invalid syntax that's an opportunity for learning something. The great thing about making mistakes is that you never run out of opportunities to learn! When you make a mistake, try to match what you've written to something you've read. In the above, I've tried to write a for-loop, but I've written it almost the way I'd write it in Pascal, not Python. Naturally it doesn't work. Where have I seen something with a for loop in Python? http://rosettacode.org/wiki/Flow-control_structures#Loops https://wiki.python.org/moin/ForLoop The more code you have read, the more likely you will have seen something similar to what you are trying to do. And the more you write it, the more it will sink in to your memory and become second nature. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
On 19/06/2014 10:09, Albert-Jan Roskam wrote: - Original Message - From: Mark Lawrence To: tutor@python.org Cc: Sent: Thursday, June 19, 2014 8:41 AM Subject: Re: [Tutor] Tips On 19/06/2014 02:36, Danny Yoo wrote: [content about __add__ dispatch resolution cut] We should remember the target audience, lest this thread doesn't spiral away so that only the tutors are talking to each other. I'm guilty of this as anyone, mind you. Pot. Kettle. :P The original question that the OP posed was: I want to know what some tips or information you can give me to remember some of the rules of Python, when you first start learning programming? and if the discussion is going to be on how __add__, __ladd__, and __radd__ all work in concert, then that might a hard right turn for beginners. I understand. Sometimes threads go like this, from one topic to another, and then an even more exotic topic, and then, well I didn't even know he played the violin?! http://www.youtube.com/watch?v=Hh_shsRfXqk :-) I didn't write any of the above. Did you mean to reply to me, but inadvertantly snipped too much, or did you mean to reply to Danny, or what? -- 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] python libraries online
And I wondered what 'cpython' was when I came across it. I thought they might have called it python > Date: Thu, 19 Jun 2014 22:23:01 +1000 > From: st...@pearwood.info > To: tutor@python.org > Subject: Re: [Tutor] python libraries online > > On Thu, Jun 19, 2014 at 12:18:35PM +, Ian D wrote: > >> A while back some one linked to the python source and I was able to >> view the whole of its libraries and class files something like this >> java api site http://docs.oracle.com/javase/7/docs/api/ > > http://hg.python.org/cpython/file/cf70f030a744/Lib/ > > > Don't forget that if you have Python installed on your computer, the > standard library (at least the parts written in Python) will be > installed on your computer too, and readable. > > > > -- > Steven > ___ > 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] python libraries online
Ok Thanks. I will look on the computer, it seems that the online repository is not so easy to search. i.e If I search csv I get all the changes all the merges... but I just want the class file > Date: Thu, 19 Jun 2014 22:23:01 +1000 > From: st...@pearwood.info > To: tutor@python.org > Subject: Re: [Tutor] python libraries online > > On Thu, Jun 19, 2014 at 12:18:35PM +, Ian D wrote: > >> A while back some one linked to the python source and I was able to >> view the whole of its libraries and class files something like this >> java api site http://docs.oracle.com/javase/7/docs/api/ > > http://hg.python.org/cpython/file/cf70f030a744/Lib/ > > > Don't forget that if you have Python installed on your computer, the > standard library (at least the parts written in Python) will be > installed on your computer too, and readable. > > > > -- > Steven > ___ > 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] Tips
On Wed, Jun 18, 2014 at 06:36:12PM -0700, Danny Yoo wrote: > [content about __add__ dispatch resolution cut] > > > We should remember the target audience, lest this thread doesn't > spiral away so that only the tutors are talking to each other. I'm > guilty of this as anyone, mind you. Pot. Kettle. :P Perhaps so, but I wasn't answering the OP, I was answering Albert, who asked a perfectly reasonable follow-up question about + and the __add__ method. Discussion threads often go in strange and interesting directions. [...] > and if the discussion is going to be on how __add__, __ladd__, and > __radd__ all work in concert, then that might a hard right turn for > beginners. __ L add__ ??? :-) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python libraries online
On Thu, Jun 19, 2014 at 12:18:35PM +, Ian D wrote: > A while back some one linked to the python source and I was able to > view the whole of its libraries and class files something like this > java api site http://docs.oracle.com/javase/7/docs/api/ http://hg.python.org/cpython/file/cf70f030a744/Lib/ Don't forget that if you have Python installed on your computer, the standard library (at least the parts written in Python) will be installed on your computer too, and readable. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] python libraries online
A while back some one linked to the python source and I was able to view the whole of its libraries and class files something like this java api site http://docs.oracle.com/javase/7/docs/api/ But I cant seem to find what I want now. I wanted to be able to look at the classes etc Anyone help plz ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
On 19/06/2014 03:37, Steven D'Aprano wrote: On Wed, Jun 18, 2014 at 12:35:20PM +0200, Sydney Shall wrote: On 17/06/2014 22:35, Alan Gauld wrote: Use modules instead of singleton classes As a new beginner with Python, I am having problem understanding the difference here. I think I understand classes, but still have problems with inheritance, but I do not understand what defines a module. I assume you know how to make a class: class Spam: def method(self, arg): ... And then you make instances: x = Spam() y = Spam() A singleton class is one which only allows there to be a single instance (or occasionally, two instances, a "doubleton" class). For example, None is a singleton. Like all instances, None has a class, but see what happens if you try to create a second instance in Python 2.7 (Python 3.3 is slightly different): py> from types import NoneType py> x = NoneType() # create a new instance Traceback (most recent call last): File "", line 1, in TypeError: cannot create 'NoneType' instances The error is slightly inaccurate, it's not that no instances can be created at all, but that only *one* instance can be created, and it's already created and named None. Inheritence is a separate issue, big enough that it deserves a new thread. As for modules, you already use modules, I'm sure, you just don't realise it. Every time you create a python file ending in .py, that's a module. Scripts are modules. Every time you use the import command, you're loading a module: py> import math py> print math Python tries very hard to ensure that every module is loaded only once. (There are circumstances where you can fool it, but they're rare.) Since the module holds state (variables) and behaviour (functions), modules perform the same sort of role as classes, so a module which is loaded once is very similar to a singleton instance. In other words, if you want a class to implement singleton behaviour, you have to work at it. But if you shift the functionality from the class into a module, Python gives you singleton behaviour for free. But if you're not sure why anyone would want a singleton instance, I agree with you: most (but not all) uses of singletons are unnecessary. Thanks a lot. This was very useful and clear. -- Sydney Shall ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
- Original Message - > From: Mark Lawrence > To: tutor@python.org > Cc: > Sent: Thursday, June 19, 2014 8:41 AM > Subject: Re: [Tutor] Tips > > On 19/06/2014 02:36, Danny Yoo wrote: >> [content about __add__ dispatch resolution cut] >> >> >> We should remember the target audience, lest this thread doesn't >> spiral away so that only the tutors are talking to each other. I'm >> guilty of this as anyone, mind you. Pot. Kettle. :P >> >> >> The original question that the OP posed was: >> >> I want to know what some tips or information you can give me to >> remember some of the rules of Python, when you first start learning >> programming? >> >> >> and if the discussion is going to be on how __add__, __ladd__, and >> __radd__ all work in concert, then that might a hard right turn for >> beginners. I understand. Sometimes threads go like this, from one topic to another, and then an even more exotic topic, and then, well I didn't even know he played the violin?! http://www.youtube.com/watch?v=Hh_shsRfXqk :-) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tips
- Original Message - > From: Steven D'Aprano > To: tutor@python.org > Cc: > Sent: Thursday, June 19, 2014 3:17 AM > Subject: Re: [Tutor] Tips > > On Wed, Jun 18, 2014 at 07:25:41AM -0700, Albert-Jan Roskam wrote: > >> Given that the concept of Ducktyping has already been mentioned, is >> there a reason why you did not mention try-except? >> >> def add(a, b): >> try: >> return a + b >> except TypeError: >> raise > > As others have mentioned, this is pointless -- there is no good reason > to catch an exception, only to *unconditionally* re-raise it. > > Sometimes it is useful to conditionally re-raise: > > try: > something() > except SomeFailure as e: > if e.condition == foo: > raise > else: > do_something_else() > > but even that is pretty rare. In general, the rule is to never catch any > exception you aren't prepared to deal with in some way. > > >> Btw, given that: >> >>> {}.__add__ >> Traceback (most recent call last): >> File "", line 1, in AttributeError: >> 'dict' object has no attribute '__add__' >> >> Why does one only need to use 'except TypeError', not 'except >> (TypeError, AttributeError)' in the try-except above? > > You answer your own question by trying it: > >> >>> {} + 1 >> Traceback (most recent call last): >> File "", line 1, in TypeError: >> unsupported operand type(s) for +: 'dict' and 'int' > > > You don't need to worry about AttributeError for __add__ because you > aren't calling __add__ directly, you're using the + operator. Aha!!! I always thought that "+" was perfectly equivalent to "__add__", just a more readable way of writing this (I would almost use the term "syntactical sugar" but for some reason that only seems to be used in the context of decorators, so I don't. Oops, I still did use that term. Oh well :-) > x + y is not the same as calling x.__add__(y). It's actually quite > clever, it gives *both* x and y a chance to decide what to do: > > (1) if y is a subclass of x, then try calling y.__radd__(x) > otherwise try calling x.__add__(y) > (2) if the method doesn't exist (raises AttributeError), > or it returns the special value NotImplemented, > try the other way around, x.__add__(y) or y.__radd__(x) > (3) if that method also doesn't exist, or returns > NotImplemented, then raise TypeError > > So you can see, the + operator catches the AttributeError raised if the > object doesn't have __add__ or __radd__ methods, either to try a > different method, or to turn it into a TypeError. Now I understand it. Very interesting. Thanks, that was exactly what I meant! "+" != "__add__". ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor