Re: [Tutor] Tips

2014-06-19 Thread Steven D'Aprano
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

2014-06-19 Thread Albert-Jan Roskam


- 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] Tips

2014-06-19 Thread Alex Kleider

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] Tips

2014-06-19 Thread Albert-Jan Roskam
- 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] Tips

2014-06-19 Thread Steven D'Aprano
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

2014-06-19 Thread Mark Lawrence

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] Tips

2014-06-19 Thread Steven D'Aprano
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] Tips

2014-06-19 Thread Sydney Shall

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

2014-06-19 Thread Albert-Jan Roskam


- 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

2014-06-19 Thread Albert-Jan Roskam


- 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


Re: [Tutor] Tips

2014-06-18 Thread Mark Lawrence

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 wrote something similar months if not years ago and was shot down in 
flames.  Fortunately for me but unfortunately for you (plural), my 
parachute opened :)


--
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

2014-06-18 Thread Steven D'Aprano
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. 


-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Danny Yoo
[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.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Steven D'Aprano
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.

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.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Dave Angel
Sydney Shall  Wrote in message:

> 
 but I do not understand what defines a module

Please post in plain text,  not html.

A module is a source file (eg. .py) or a compiled source file (eg 
 .pyc) that's generally intended to be used via an import.
 


-- 
DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Mark Lawrence

On 18/06/2014 20:17, Albert-Jan Roskam wrote:



- Original Message -


From: Mark Lawrence 
To: tutor@python.org
Cc:
Sent: Wednesday, June 18, 2014 9:03 PM
Subject: Re: [Tutor] Tips

On 18/06/2014 15:25, Albert-Jan Roskam wrote:

  - Original Message -

  From: Alan Gauld 
  To: tutor@python.org
  Cc:
  Sent: Wednesday, June 18, 2014 11:47 AM
  Subject: Re: [Tutor] Tips

  On 18/06/14 01:15, Nanohard wrote:

On 2014-06-17 13:35, Alan Gauld wrote:


Don't test types, use the interface


Can you please explain what you mean by this?


He means use the Python interpreter, by going to your console and

typing

  "python", or in Windows

it's called 'IDLE'.



  Nope, I meant what Mark and Danny said.

  For example don't do this:

  def add(a,b):
if type(a) == int and type(b) == int:
   return a+b
else:
   raise TypeError

  Just do this:

  def add(a,b):
return a+b


  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

  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?

  {} + 1

  Traceback (most recent call last): File "", line 1, in TypeError:

unsupported operand type(s) for +: 'dict' and 'int'




What makes you think that you're calling your add function in either
example above?  In the first you're not calling anything as you've
missed the brackets.  Even if you add (groan :) them, you'll be trying
to call an add method for a dict, not your add function.  In the second
example, you're trying to add 1 to an empty dict, again your function
doesn't enter into the equation (double groan :)


If I call my add function, then then the return statement would be equivalent 
to:
-... if a={] and b=[1]: a.__add__(b)
-... if a={} and b=1: AttributeError, because the class dict does not have an 
__add__ method.
That's why I thought an AttributeError would also have to be caught, just in 
case the caller is stupid enough to give a dict as the first argument. But 
indeed (Alan) it was silly of me to just 'raise' and not doing anything else 
with it.



Now you've completely lost me.  Please explain precisely what you think 
your function does, and how it relates to the two examples that you 
tried that gave exceptions.


--
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

2014-06-18 Thread Albert-Jan Roskam


- Original Message -

> From: Mark Lawrence 
> To: tutor@python.org
> Cc: 
> Sent: Wednesday, June 18, 2014 9:03 PM
> Subject: Re: [Tutor] Tips
> 
> On 18/06/2014 15:25, Albert-Jan Roskam wrote:
>>  - Original Message -
>>>  From: Alan Gauld 
>>>  To: tutor@python.org
>>>  Cc:
>>>  Sent: Wednesday, June 18, 2014 11:47 AM
>>>  Subject: Re: [Tutor] Tips
>>> 
>>>  On 18/06/14 01:15, Nanohard wrote:
>>>>>    On 2014-06-17 13:35, Alan Gauld wrote:
>>>>> 
>>>>>>    Don't test types, use the interface
>>>>> 
>>>>>    Can you please explain what you mean by this?
>>>> 
>>>>    He means use the Python interpreter, by going to your console and 
> typing
>>>  "python", or in Windows
>>>>    it's called 'IDLE'.
>>> 
>>> 
>>>  Nope, I meant what Mark and Danny said.
>>> 
>>>  For example don't do this:
>>> 
>>>  def add(a,b):
>>>        if type(a) == int and type(b) == int:
>>>           return a+b
>>>        else:
>>>           raise TypeError
>>> 
>>>  Just do this:
>>> 
>>>  def add(a,b):
>>>        return a+b
>> 
>>  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
>> 
>>  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?
>>>>>  {} + 1
>>  Traceback (most recent call last): File "", line 1, in TypeError: 
> unsupported operand type(s) for +: 'dict' and 'int'
>> 
> 
> What makes you think that you're calling your add function in either 
> example above?  In the first you're not calling anything as you've 
> missed the brackets.  Even if you add (groan :) them, you'll be trying 
> to call an add method for a dict, not your add function.  In the second 
> example, you're trying to add 1 to an empty dict, again your function 
> doesn't enter into the equation (double groan :)

If I call my add function, then then the return statement would be equivalent 
to:
-... if a={] and b=[1]: a.__add__(b)
-... if a={} and b=1: AttributeError, because the class dict does not have an 
__add__ method.
That's why I thought an AttributeError would also have to be caught, just in 
case the caller is stupid enough to give a dict as the first argument. But 
indeed (Alan) it was silly of me to just 'raise' and not doing anything else 
with it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Mark Lawrence

On 18/06/2014 15:25, Albert-Jan Roskam wrote:

- Original Message -

From: Alan Gauld 
To: tutor@python.org
Cc:
Sent: Wednesday, June 18, 2014 11:47 AM
Subject: Re: [Tutor] Tips

On 18/06/14 01:15, Nanohard wrote:

  On 2014-06-17 13:35, Alan Gauld wrote:


  Don't test types, use the interface


  Can you please explain what you mean by this?


  He means use the Python interpreter, by going to your console and typing

"python", or in Windows

  it's called 'IDLE'.



Nope, I meant what Mark and Danny said.

For example don't do this:

def add(a,b):
  if type(a) == int and type(b) == int:
 return a+b
  else:
 raise TypeError

Just do this:

def add(a,b):
  return a+b


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

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?

{} + 1

Traceback (most recent call last): File "", line 1, in TypeError: unsupported 
operand type(s) for +: 'dict' and 'int'



What makes you think that you're calling your add function in either 
example above?  In the first you're not calling anything as you've 
missed the brackets.  Even if you add (groan :) them, you'll be trying 
to call an add method for a dict, not your add function.  In the second 
example, you're trying to add 1 to an empty dict, again your function 
doesn't enter into the equation (double groan :)


--
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

2014-06-18 Thread Alan Gauld

On 18/06/14 15:25, Albert-Jan Roskam wrote:


Just do this:

def add(a,b):
  return a+b


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


Because that's a lot of work for no value.
Catching an exception simply to raise it again is
a pointless exercise. Only catch stuff you intend
to process.

Of course an add function is a waste of space too
since one already exists in the operators module
and the + sign is usually all thats needed.
But the function was only an example...

but try/except is completely orthogonal to the
original 'tip' of not checking types.


Why does one only need to use 'except TypeError',

> not 'except (TypeError, AttributeError)' in the try-except above?

I'm not sure I understand? You created the try/except.
You can catch as much or as little as you wish.
Leaving it to Python catches both.


--
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

2014-06-18 Thread Albert-Jan Roskam
- Original Message -
> From: Alan Gauld 
> To: tutor@python.org
> Cc: 
> Sent: Wednesday, June 18, 2014 11:47 AM
> Subject: Re: [Tutor] Tips
> 
> On 18/06/14 01:15, Nanohard wrote:
>>>  On 2014-06-17 13:35, Alan Gauld wrote:
>>> 
>>>>  Don't test types, use the interface
>>> 
>>>  Can you please explain what you mean by this?
>> 
>>  He means use the Python interpreter, by going to your console and typing 
> "python", or in Windows
>>  it's called 'IDLE'.
> 
> 
> Nope, I meant what Mark and Danny said.
> 
> For example don't do this:
> 
> def add(a,b):
>      if type(a) == int and type(b) == int:
>         return a+b
>      else:
>         raise TypeError
> 
> Just do this:
> 
> def add(a,b):
>      return a+b

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 
 
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?
>>> {} + 1 
Traceback (most recent call last): File "", line 1, in TypeError: unsupported 
operand type(s) for +: 'dict' and 'int'
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Sydney Shall

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.

With many thanks.

--
Sydney Shall
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Alan Gauld

On 18/06/14 01:15, Nanohard wrote:

On 2014-06-17 13:35, Alan Gauld wrote:


Don't test types, use the interface


Can you please explain what you mean by this?


He means use the Python interpreter, by going to your console and typing 
"python", or in Windows
it's called 'IDLE'.



Nope, I meant what Mark and Danny said.

For example don't do this:

def add(a,b):
if type(a) == int and type(b) == int:
   return a+b
else:
   raise TypeError

Just do this:

def add(a,b):
return a+b

And rely on the interpreter to check that a and b can be added.
It makes the function much more flexible and reusable.
You can now add strings, lists, floats etc, as well as ints


--
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

2014-06-18 Thread Nanohard
> On 2014-06-17 13:35, Alan Gauld wrote:
> 
>> Don't test types, use the interface
> 
> Can you please explain what you mean by this?
> alex

He means use the Python interpreter, by going to your console and typing 
"python", or in Windows
it's called 'IDLE'.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-18 Thread Mark Lawrence

On 18/06/2014 01:02, Alex Kleider wrote:

On 2014-06-17 13:35, Alan Gauld wrote:


Don't test types, use the interface


Can you please explain what you mean by this?
alex



Further to Danny Yoo's response have a read of this 
http://en.wikipedia.org/wiki/Duck_typing


--
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

2014-06-17 Thread Danny Yoo
On Tue, Jun 17, 2014 at 5:02 PM, Alex Kleider  wrote:
> On 2014-06-17 13:35, Alan Gauld wrote:
>
>> Don't test types, use the interface
>
>
> Can you please explain what you mean by this?


If you are writing type tests on a function's inputs, you might better
off by having the inputs implement an interface: the design of the
program will often be more maintainable.


As a toy example, consider the following:

###
class Football(object):
pass

class Baseball(object):
pass

def printBallSize(game):
if isinstance(game, Football):
print "The ball is 68-70cm"
if isinstance(game, Baseball):
print "The ball is 229-235mm"
raise ValueError
###

The problem with getBallSize() is that it hardcoded a decision based
on what the type of the input is.  It's a bit fragile.


A more flexible design allows the game itself to provide that
information for itself:

###
class Football(object):
def size(self):
return "68-70cm"

class Baseball(object):
def size(self):
return "229-235mm"

def printBallSize(game):
return "The ball is", game.size()
###


The reason the latter is usually preferable is because additional
games can be supported without having to revise printBallSize().  For
example, we can write:

###
class AmericanFootball(object):
def size(self):
return "68-70cm"
###

and printBallSize() will work on American footballs as well.
printBallSize() works on anything that implements a size() method.


The example above is very toy.  A more realistic example might be
writing a function whose inputs might be assumed to be a sequence.
Rather than hardcode a test that explicitly checks whether the input
is a list, just use it.  Then anything that satisfies the
"interface"---the way you're using the input---will often Just Work.
Tuples, for example, will do many of the things that lists will do.
And in some cases, even a file might look like a list, for all
practical purposes, if all we care about is iterating though it once.


Hope that makes some sense!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-17 Thread Alex Kleider

On 2014-06-17 13:35, Alan Gauld wrote:


Don't test types, use the interface


Can you please explain what you mean by this?
alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2014-06-17 Thread Alan Gauld

On 17/06/14 19:52, 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?


Most of my tips/rules are about programming rather than python...
-
Use for loops when you know (or can predict) the number of iterations.
Use while loops when you don't know in advance

Put repeating code in a function

Use meaningful variable names.

Use dictionaries more often.

Let the data define the structure.
And structure your data so that it can.

And more Python specific:
---
Use modules instead of singleton classes

Use "if/elif" instead of "if/else if" trees

Variables are just names bound to objects

Don't test types, use the interface


Is that the kind of thing?

--
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


[Tutor] Tips

2014-06-17 Thread keith papa


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?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tips

2010-01-11 Thread Kent Johnson
On Mon, Jan 11, 2010 at 12:33 AM, VacStudent  wrote:
> I would like to get a python book, how and where to get one?

Amazon.com? Or lots of free resources online.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tips

2010-01-11 Thread VacStudent
I would like to get a python book, how and where to get one?

 

Jappie Monele

Mechanical Engineer Student

Koffiefontein Blue Diamond Mine JV 

 

Petra Diamonds

Group Management Office: Elizabeth House, 9 Castle Street, St. Helier,
Jersey, JE4 2QP

South African Office: Block 3, Silver Point Office Park, 22 Ealing
Crescent, Bryanston, Johannesburg, 2052. 

Postal Address: PO Box  71007, Bryanston, 2021, South Africa.

Koffiefontein Office: 1 Du Preezstreet, Koffiefontein, Free State
Province, S.A, 9986.

Postal Address: PostOfficeBox 80, Koffiefontein, 9986, South Africa.

Office: +27 (53)205 5

Cell: +27 (0) 844428008

e mail: v...@petradiamonds.com  

Web Address:  www.petradiamonds.com   

This email is intended for the sole use of the addressee and may contain
information that is confidential and privileged. Access to this email by
anyone else is unauthorised. If you are not the intended recipient any
disclosure, copying, distribution or any action taken or omitted to be
taken in reliance on it is strictly prohibited and may be unlawful. If
you have received this email in error, please notify us immediately by
return of the email or telephone +27 11 467 6710 and destroy the
original message. Thank you.

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tips for writing a program

2007-06-20 Thread Alan Gauld
"Mat Newport" <[EMAIL PROTECTED]> wrote

> Basically the program would scan a specified folder, 
> build a list of specific files (.txt in the example below), 

Look at the glob module and its glob function.

Or if you want to include subdirectories lkook at the 
os.walk function. There are examples of using both 
in my Using the OS topic in my tutorial.

> ... to move and rename certain one's 

And the os and shutil modules contain functions to do 
this - again see my OS topic for examples.

> based on a separate list. 

Which could be stored in a file and read into a 
normal python list at startup.

> it would then test its list of found files against 
> a large database for a match, and upon finding 
> the match copy move and rename them 

All fairly simple using the modules mentioned above.

> Et cetera. I know basic python but don't know how to make 
> it generate the list, 

glob will give you a list, os.walk needs more work 
but the normal Python list processing methods will 
work just fine. Do you have any more specific 
questions/problems?

> store them, 

You probably only need to store them in memory so 
once you put them in a list you should be fine.

> analyze it against another list, 

That can be done by looping over one list while comparing 
the items in the other. Luke has shown one way to do that 
using a list comprehension.

> then copy and rename based on the matches it finds. 

See the shutil functions mentioned above.

> Is this a task for a different program?

No, Python is perfectly suited to this kind of task. 
I did something very similar a few weeks ago

Have a go, if you get stuck come back and ask us more 
specific questions and show us the code and error messages.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tips for writing a program

2007-06-19 Thread Luke Paireepinart
Mat Newport wrote:
> I have taken a fundamentals of programming course at a local college, but 
> that class does not provide the level of expertise to write a program I have 
> in mind. So I do have basic skills, I just need to be shown the tools to 
> write this thing and I think I could put it all together. 
>   
You sound confident in your ability to reason the problem out.  That's 
very good.
> Basically the program would scan a specified folder, build a list of specific 
> files (.txt in the example below), and then have the ability to move and 
> rename certain one's based on a separate list. For example, it would scan 
> c:\test\  for .txt files
> and find:
>
> "Koontz lighning.txt"
> "davinci_code.txt" 
>
> it would then test its list of found files against a large database for a 
> match, and upon finding the match copy move and rename them to
>
> "Dean Koontz - Lightning.txt"
> "Dan Brown - The Davinci Code.txt"
>
> Et cetera. I know basic python but don't know how to make it generate the 
> list, store them, analyze it against another list, then copy and rename based 
> on the matches it finds. Is this a task for a different program?
>   
There are certainly automated file renamer programs out there, but none 
can provide the flexibility of being able to code your own.
Also, if you're really interested in programming, you should take any 
opportunity you can to work on your skills, provided the required level 
of skill
is not vastly out of reach of your own level at the time, and from what 
you have said, I believe you could do this program.

I'm not exactly sure what all your questions are... if you explain in 
more detail, we should be able to assist you with everything.
Here's some hints for what I think you're asking.

"how to generate the list" of files in a directory.
import os #we need this for the path and directory listing functions
directory = 'c:\\test' #define the target directory
extensions = ['txt']
#a list comprehension would be a succinct way to filter the directory 
listing.
listing = [filename for filename in os.listdir(directory) if 
os.path.splitext(filename)[-1].lower() in extensions]

listing now contains all the filenames in the target directory that 
contain the file extension you're looking for.
If the above line doesn't make sense, you can try reading about "list 
comprehensions."  feel free to ask any questions you might have.


"how to store them"
I'm assuming you mean the directory listing?
I'm not sure what you mean by 'store'
You mean permanently store?

"analyze it against another list"
I'm not sure where these lists are coming from.
If you have a basic, direct mapping from incorrect to correct filenames,
like  you know
Koontz lighning.txt  should always be renamed to Dean Koontz - Lightning.txt
the problem is fairly simple.
If you're trying to match based on keywords, etc. it gets more complex.

"copy and rename based on the matches it finds"
if you want to rename a file, you can use the os.rename function.
If you ever find you need help on a certain function,
just use the builtin method "help"
 >>> help(os.rename)
Help on built-in function rename in module nt:

rename(...)
rename(old, new)
   
Rename a file or directory.

so this tells us we can do, for example,

os.rename("C:\\test.txt","C:\\foobar.txt")


So try to be more specific where I got confused (I get confused easily)
and I'll try to give you more specific help.
-Luke

>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tips for writing a program

2007-06-19 Thread Mat Newport
I have taken a fundamentals of programming course at a local college, but that 
class does not provide the level of expertise to write a program I have in 
mind. So I do have basic skills, I just need to be shown the tools to write 
this thing and I think I could put it all together. 
Basically the program would scan a specified folder, build a list of specific 
files (.txt in the example below), and then have the ability to move and rename 
certain one's based on a separate list. For example, it would scan c:\test\  
for .txt files
and find:

"Koontz lighning.txt"
"davinci_code.txt" 

it would then test its list of found files against a large database for a 
match, and upon finding the match copy move and rename them to

"Dean Koontz - Lightning.txt"
"Dan Brown - The Davinci Code.txt"

Et cetera. I know basic python but don't know how to make it generate the list, 
store them, analyze it against another list, then copy and rename based on the 
matches it finds. Is this a task for a different program?




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor