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] Pulling items from a dict in a print command

2014-06-18 Thread Danny Yoo
Hi Ben,

There's a bit of duplication in the keys being looked up, making it a
bit fragile if you need to correct the spelling of a key or need to
add additional keys, since there are two places that need to be
changed.


One way to make this a little cleaner might be to have a helper
function that does the work you're doing now in constructing the
formatting string.  Something like this might be worth it:


def makeStatusLine(keyValues, firstKey, restKeys):
buffer = []
for key in restKeys:
buffer.append("%s=%s" % (key, keyValues[key]))
firstColumn = "%s=%s|" % (firstKey, keyValues[firstKey])
return firstColumn + ",".join(buffer)



For example:


>>> makeStatusLine({'name': 'Ben', 'forum': 'tutor@python.org'}, 'name', 
>>> ['forum'])
'name=Ben|forum=tutor@python.org'



That way, you can write the sequence of columns just once, and be a
lot more sure that the output is formatted consistently.  Here, we'll
know the first column is treated specially with the "|" pipe symbol,
and the rest will be comma-delimited.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File reading

2014-06-18 Thread Danny Yoo
Hi Uma,


In your case, I'd look at the file as a sequence of "tokens" and look
at this as a tokenization problem

I think we'll see some kind of _identifier_, followed by _whitespace_,
followed by a _string_.  All these three tokens will repeat, until we
hit the end of the the file.

More formally, I'd try to describe the file's structure in a grammar:


## This is not Python, but just a way for me to formally express
what I think your file format is:

file := (IDENTIFIER WHITESPACE STRING)* END_OF_FILE


The star there is meant to symbolize the "repeatedly" part.  Note that
we haven't yet said what IDENTIFIER, WHITESPACE, or STRING means at
all yet: I'm just making sure we've got the toplevel understanding of
the file.


If this is true, then we might imagine a function tokenize() that
takes the file and breaks it down into a sequence of these tokens, and
then the job of pulling out the content you care about should be
easier.  We can loop over the token sequence, watch for an identifier
"x-1", skip over the whitespace token, and then take the string we
care about, till we hit the "x-2" identifier and stop.


tokenize() should not be too bad to write: we walk the file, and
recognize certain patterns as either IDENTIFIER, WHITESPACE, or
STRING.

IDENTIFIER looks like a bunch of non-whitespace characters.
WHITESPACE looks like a bunch of whitespace characters.
STRING looks like a quote, followed by a bunch of non-quote
characters, followed by a quote.

The description above is very handwavy.  You can more formally write
those descriptions out by hand with the use of regular expressions.
Regular expressions are a mini-language for writing out string
patterns and extracting content from strings.

See:  https://docs.python.org/2/howto/regex.html


Once we can formally describe the patterns above, then we can walk the
characters in the file.  We pick out which of the three patterns will
match what we're currently seeing, and then add to the list of tokens.
Eventually, we hit end of file, and tokenize() can return all the
tokens that it has accumulated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File reading

2014-06-18 Thread Umamaheshwar Rao
i agree.
i expect the output be

"all the best"
"all the best 2 next line\n check this"



On Wed, Jun 18, 2014 at 6:24 PM, Danny Yoo  wrote:

> On Wed, Jun 18, 2014 at 6:08 PM, Umamaheshwar Rao
>  wrote:
> > Hi Experts,
> >
> > I have a file with below format
> >
>
>
> Can you describe the format a little more precisely?   You're giving
> examples, which is wonderful.  But the examples are missing something.
>
> What's the output you want to get here?  Imagine that you magically
> have the program you want.  What would be the ideal structure of the
> output you're extracting from this file?
>
>
> I am guessing that if you have content of the form:
>
> ##
> ## Some test data, which we'll treat as a file-like object by
> ## using StringIO:
> from StringIO import StringIO
>
> somefile = StringIO("""this is first file operation
> x-1  "all the best"
> x-2  "all the best 2 next line
>  check this"
> x-3  "last line"
> """)
> ##
>
>
> then I think you're expecting this to be parsed as a key-value store,
> something like this, maybe?
>
> ##
> { "x-1" : "all the best",
>   "x-2" : "all the best 2 next line\n check this",
>   "x-3" : "last line" }
> ##
>
> Can you confirm if this is the structure of the output you'd like to
> see?  Please clarify.
>
>
> You need to make your expectations a bit explicit.  By saying that you
> want to extract everything between x-1 and x-2, there's a bit of
> ambiguity there that I'd like to avoid   By just giving us the input
> as an example, there are several kinds of output you might expect to
> see.  We don't want to guess.
>
___
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] File reading

2014-06-18 Thread Danny Yoo
On Wed, Jun 18, 2014 at 6:08 PM, Umamaheshwar Rao
 wrote:
> Hi Experts,
>
> I have a file with below format
>


Can you describe the format a little more precisely?   You're giving
examples, which is wonderful.  But the examples are missing something.

What's the output you want to get here?  Imagine that you magically
have the program you want.  What would be the ideal structure of the
output you're extracting from this file?


I am guessing that if you have content of the form:

##
## Some test data, which we'll treat as a file-like object by
## using StringIO:
from StringIO import StringIO

somefile = StringIO("""this is first file operation
x-1  "all the best"
x-2  "all the best 2 next line
 check this"
x-3  "last line"
""")
##


then I think you're expecting this to be parsed as a key-value store,
something like this, maybe?

##
{ "x-1" : "all the best",
  "x-2" : "all the best 2 next line\n check this",
  "x-3" : "last line" }
##

Can you confirm if this is the structure of the output you'd like to
see?  Please clarify.


You need to make your expectations a bit explicit.  By saying that you
want to extract everything between x-1 and x-2, there's a bit of
ambiguity there that I'd like to avoid   By just giving us the input
as an example, there are several kinds of output you might expect to
see.  We don't want to guess.
___
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


[Tutor] File reading

2014-06-18 Thread Umamaheshwar Rao
Hi Experts,

I have a file with below format

this is first file operation
x-1  "all the best"
x-2  "all the best 2 next line
 check this"
x-3  "last line"


i need extract the lines starting with x-1 and x-2, can some throw some
light on how to do?

Thanks,
Uma
___
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] Pulling items from a dict in a print command

2014-06-18 Thread Peter Otten
Ben Sherman wrote:

> Whats a more pythony way to do this?  I have a dict with a few dozen
> elements, and I want to pull a few out.  I've already shortened it with
> itemgetter, but it still seems redundant.  I feel like I can do something
> like I've seen with *kwargs, but I'm not sure.
> 
> I'm using old style sprintf formatting, so feel free to show me a better
> way to do this with the new way.
> 
> Thanks for the help!
> 
> Code:
> 
> print(("overall_status=%s|" +
> "mon_count=%s," +
> "healthy_mons=%s," +
> "pg_count=%s," +
> "pg_clean_count=%s," +
> "osd_count=%s," +
> "osd_up=%s," +
> "osd_in=%s," +
> "bytes_avail=%s," +
> "bytes_used=%s," +
> "bytes_total=%s") %
> itemgetter("overall_status",
> "mon_count",
> "healthy_mons",
> "pg_count",
> "pg_clean_count",
> "osd_count",
> "osd_up",
> "osd_in",
> "bytes_avail",
> "bytes_used",
> "bytes_total")(parsed_json))

names = ["overall_status", "mon_count", "pg_count", ...]
print(", ".join("{}={}".format(name, parsed_json[name]) for name in names))


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


[Tutor] Pulling items from a dict in a print command

2014-06-18 Thread Ben Sherman
Whats a more pythony way to do this?  I have a dict with a few dozen
elements, and I want to pull a few out.  I've already shortened it with
itemgetter, but it still seems redundant.  I feel like I can do something
like I've seen with *kwargs, but I'm not sure.

I'm using old style sprintf formatting, so feel free to show me a better
way to do this with the new way.

Thanks for the help!

Code:

print(("overall_status=%s|" +
"mon_count=%s," +
"healthy_mons=%s," +
"pg_count=%s," +
"pg_clean_count=%s," +
"osd_count=%s," +
"osd_up=%s," +
"osd_in=%s," +
"bytes_avail=%s," +
"bytes_used=%s," +
"bytes_total=%s") %
itemgetter("overall_status",
"mon_count",
"healthy_mons",
"pg_count",
"pg_clean_count",
"osd_count",
"osd_up",
"osd_in",
"bytes_avail",
"bytes_used",
"bytes_total")(parsed_json))
___
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] Are These Resources Good Enough To Learn Python 3?

2014-06-18 Thread Alan Gauld

On 18/06/14 06:27, Brandon Price wrote:

Hi,
I'm new to programming and I've tried to learn in the past but I gave up
easily.



Learn Python within 1 month


That's achievable, at least to a working level.
Expert takes a tad longer.


Questions:
1. Which one of these resources would you recommend I use:
http://www.alan-g.me.uk/l2p/index.htm or
http://www.python-course.eu/python3_course.php


OK, I'm biased...
But tutorials are very personal. Some people like a lot of explanation 
about the background and theory. Others like a lot of hands on and don't 
care about the 'why'.


My tutorial focuses on teaching programming in general while using 
Python as  the example language. The other tutorial you cite focuses
on teaching Python and as such gives a deeper study of the language at 
the expense of missing some of the wider issues. both will teach you 
enough to stat writing your own programs and be able to read and 
understand the documentation.


But the most important thing for you is which one matches your preferred 
learning style.



2. Once I learn Python, what next?


Use it! Find a project and write some code.
If you can't think of one find someone else's project and
lend a hand.

That will probably require you to learn other new technologies
such as HTML, network programming, databases and SQL, graphics, 
statistics, and so on... Once you start programming the learning

never stops.

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


[Tutor] Are These Resources Good Enough To Learn Python 3?

2014-06-18 Thread Brandon Price
Hi,
I'm new to programming and I've tried to learn in the past but I gave up
easily. I tried learning Java but I feel that Python would be the best
route to take since it's easier to learn and then I'll move on to learning
Java. I want to learn Python 3.x not Python 2.

My goal(s) are:
Learn Python within 1 month

Questions:
1. Which one of these resources would you recommend I use:
http://www.alan-g.me.uk/l2p/index.htm or
http://www.python-course.eu/python3_course.php

2. Once I learn Python, what next?
___
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