Re: [Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?

2016-01-24 Thread Alan Gauld
On 24/01/16 03:07, boB Stepp wrote:

>> In pure OO objects should only expose methods and the data
>> attributes should only be there to support the methods.
> 
> Apparently what OOP knowledge I started out with agrees strongly with
> what you say here.  But this level of *purity* appears to be
> non-Pythonic in actual practice.  

Python allows you to be as pure as you want to be.
The choice is mainly in the hands of the consumer of
the class. They get to decide whether they want/need
to poke about with the internals. If a class is well
designed it should be possible to use its operations
without directly modifying its data. Reading data
directly in Python is usually considered ok.

But laziness or the need for speed (of development)
often corrupts purity.

> So, in your opinion, how far should
> I go towards emulating pure OO objects?

As above, I try to ensure that the class operations
do not require the user to poke values in (possibly
by providing parameters). I "allow/encourage" direct
access to read.

As an example

class Point:
  def __init__(self,x,y):
 self.x = x
 self.y = y
  def distance(self):
 return (self.x**2+self.y**2)**0.5
  def moveTo(self,new_x,new_y):
 self.x = x
 self.y = y

By providing the moveTo() method there should be
no reason for users to set x or y individually.
But I encourage direct reading by not providing
get() methods. In pure OOP I should provide a Coords()
method too.

>> monolithic algorithms/functions often get split into small
>> chunks distributed over several classes.
> 
> With functions, the ideal is that each function executes a single,
> specific purpose.  

Still true in OOP

> With large classes, what should I use as a guide as
> to when to split them into smaller ones?  

Is it a single thing? Or is it really trying to be multiple things?
Of course a large object may be composed of many smaller objects.
A model of a car may have wheels, engines, brakes etc.
And the code for the accelerate() method may delegate to
engine and wheel methods rather than directly reading the
engine data.

> class, perhaps one that looks to be useful on its own in other
> programming scenarios.  Am I close to hitting the nail on the head
> here?

Yes, re-use is also a good reason to ask should this be a
separate object? But reuse alone is not strong enough to
break up what is a single entity, although if its a
function you want you might find that you can extract it
into a mixin class (ie one that reflects a behaviour rather
than a noun and is usually inherited as part of a
multi-inheritance lattice) - such as loggable, or colored.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Value of tracebacks to malicious attackers?

2016-01-24 Thread Alan Gauld
On 24/01/16 04:52, boB Stepp wrote:

> How much concern do you give this in designing and implementing your
> production code?  How far do you go in handling exceptions to ensure
> that tracebacks cannot arise for a malicious user?

When I was writing commercial code that went into "the wild" we
had a policy to wrap the entire main program in a try/except
that logged all error output in a file (on the server). If it
was a PC desktop app you could email it to a support site
 - although I've never personally written commercial apps
other than server side.

Our main concern was to prevent spooking the user, but nowadays
the security risk is definitely valid too.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Change datatype for specific columns in an 2D array & computing the mean

2016-01-24 Thread Peter Otten
Ek Esawi wrote:

> Hi All---
> 
> 
> 
> Sorry for posting again, but I have a problem that I tried several
> different ways to solve w/o success. I approached the problem from one
> angle and asked about it here; I got some good input using pandas, and
> structured array, but I am new to python and not very familiar with either
> to use at this moment.  I decided to go about in a different direction. I
> am hoping for a simpler solution using Numpy.
> 
> 
> I have a csv file with 4 columns and 2000 rows. There are 10 variables in
> column 1 and 4 variables on each column, 2 and 3. I read the csv file and
> converted it to arrays. The problem I ran into and could not resolve is
> 2-fold: (1) change the datatype for columns 1 and 4 to float and (2) then,
> I want to use Numpy-or simpler method- to calculate the mean of the data
> points on column 4 based on each variable on column 1 and column 2. Below
> is my code and sample data file.
> 
> 
> 
> Here is part of my code:
> 
> 
> 
> import numpy as np
> 
> import csv
> 
> 
> 
> TMatrix=[]
> 
> np.set_printoptions(precision=2)
> 
> 
> 
> " Converting csv to lists "
> 
> 
> 
> with open('c:/Users/My Documents/AAA/temp1.csv') as temp:
> 
> reader = csv.reader(temp, delimiter=',', quoting=csv.QUOTE_NONE)
> 
> for row in reader:
> 
> TMatrix.append(row)
> 
> 
> 
> " converting lists to arrays "
> 
> TMatrix=np.array(TMatrix)
> 
> TMatrix=np.array(4,TMatrix[1:,::],dtype='float,int,int,float')#
> this statement is not working
> 
> 
> 
> +++ This is a sample of my file +
> 
> 
> 
> ['19' 'A4' 'B2' '2']
> 
>  ['19' 'A5' 'B1' '12']
> 
>  ['18' 'A5' 'B2' '121']]

How do you want to convert the second and third column to int? Are A4 and B2 
hex numbers? Then try

$ cat esawi.csv 
19,A4,B2,2
19,A5,B1,12
$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> def fromhex(s):
... return int(s, 16)
... 
>>> numpy.genfromtxt("esawi.csv", delimiter=",", converters={1:fromhex, 
2:fromhex})
array([(19.0, 164, 178, 2.0), (19.0, 165, 177, 12.0)], 
  dtype=[('f0', 'https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Value of tracebacks to malicious attackers?

2016-01-24 Thread Devin Jeanpierre
Forgetting to hide tracebacks on a client-side app is not a huge deal
(other than being confusing and looking too serious), and definitely
doesn't matter for security. So I guess we're assuming that the Python
code is not on the user's machine.

On Sat, Jan 23, 2016 at 10:43 PM, Danny Yoo  wrote:
> But if there is malicious intent, yes, a traceback can give a lot of
> information that we're rather not give freely.  Operating system,
> version of the Python runtime, locations of files, etc.  That's all
> valuable knowledge.

Verbose tracebacks (like from cgitb) will also included the values of
variables on the stack, which can include extremely sensitive data
like cryptographic keys.

For letting users report errors without compromising any data at all,
one can give them a hashed stack trace or error ID that a developer
can look up locally from an error DB. If there is no error DB, then an
encrypted stack trace works too.

>> Is it even
>> possible to prevent this from happening?  I am highly doubtful that it
>> is possible to handle all possible exceptions in any reasonably
>> complex application.

You can catch exceptions using a top-level try-except. If an exception
slips through (e.g. a bug in your setup/teardown code etc.), then your
app will crash, but the exception will not be given to the user (just
to stderr, which will get directed to logs), because the only
exceptions users see are exceptions you explicitly give to them.

(This isn't true in some environments. Avoid those.)

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


Re: [Tutor] Change datatype for specific columns in an 2D array & computing the mean

2016-01-24 Thread Ek Esawi
Thanks for the input. Columns 2 and 3 are strings and i assume that they
don't need to be converted. Because all i need is to compute the mean for
data on column 4 based on each variable in column 1 and each in column 2..

BTW, is it possible to send you what i did off list? That way you see what
i am doing.


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


Re: [Tutor] Change datatype for specific columns in an 2D array & computing the mean

2016-01-24 Thread Peter Otten
Ek Esawi wrote:

> Thanks for the input. Columns 2 and 3 are strings and i assume that they
> don't need to be converted. Because all i need is to compute the mean for
> data on column 4 based on each variable in column 1 and each in column 2..

I'm an amateur with numpy, and unfortunately my favourite search engine 
didn't come up with a numpy-specific way to group rows in a 2D array.

> BTW, is it possible to send you what i did off list? That way you see what
> i am doing.

No. I'm posting here to help you overcome problems you run into when 
learning Python (and sometimes the application of Python libraries), not to 
write ready-to-use code for you.


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


Re: [Tutor] Change datatype for specific columns in an 2D array & computing the mean

2016-01-24 Thread Alan Gauld
On 24/01/16 14:09, Ek Esawi wrote:

> BTW, is it possible to send you what i did off list? That way you see what
> i am doing.

The list is here so that everyone can benefit.
Can you post the code publicly? If so, and its not more
than say, 100-200 lines, you can just post it here.

But I will repeat that while Oscar and Peter and a few
others can help you with Numpy/SciPy there is a dedicated
forum where you will find many more experts willing and
eager to help you.

And I get the feeling that even if we resolve this issue
there will only be more to follow...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Why is an OrderedDict not sliceable?

2016-01-24 Thread Albert-Jan Roskam
 
> To: tutor@python.org
> From: breamore...@yahoo.co.uk
> Date: Thu, 21 Jan 2016 21:02:03 +
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> 
> On 20/01/2016 13:33, Albert-Jan Roskam wrote:
> > Hi,
> >
> > Like the subject says: Why is an OrderedDict not sliceable? (From the 
> > collections library). Was that an intentional omission, or a mistake? [1]
> 
> Plenty of answers on this all ready, but...
> 
> >
> > Background: I do not use OrderedDict very often, but I thought I could use 
> > it to look up street and city names using postcodes ([0-9]{4} [a-z]{2} 
> > format). I needed it to be ordered because I also wanted to be able to use 
> > bisect, which is needed when the postcode letters are missing. In short: a 
> > fast dict lookup for complete postcodes and less fast bisect lookup for in 
> > complete postcodes.
> >
> 
> You appear to be confusing ordered and sorted.   You are correct. Is there a 
> difference in the way those terms are used colloquially vs. in the field of 
> Computer Science (Note: English is not my mother tongue)? Anyway, this page 
> seems to suggest that "Ordered" means "gets messed up upon insertion, 
> deletion, update: 
> http://stackoverflow.com/questions/1084146/what-is-the-difference-between-an-ordered-and-a-sorted-collection
>There is no way that you 
> can use bisect on an OrderedDict unless it is sorted in the first place.
 I fetch the data from a MS SQL Server with a query that goes something like 
SELECT DISTINCT pc_digits, pc_letters, house_number_from, house_number_to, 
street, city WHERE ... ORDER BY pc_digits, pc_letters.  
> > [1] http://stackoverflow.com/questions/30975339/slicing-a-python-ordereddict
> >
> > Thanks!
> >
> > Albert-Jan
> > 
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence
> 
> ___
> 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] Why is an OrderedDict not sliceable?

2016-01-24 Thread Albert-Jan Roskam

 
> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Fri, 22 Jan 2016 00:12:18 +
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> 
> On 22/01/16 00:00, Steven D'Aprano wrote:
> 
> > Also, you have a problem -- what happens if the incomplete postcode is 
> > missing the first digit? (I suppose for that case, you just have to do a 
> > slow linear search.) 
If the postcode letters are missing, I look up the insertion point for the 
postcode digits. I then indeed use a linear search to loop through that postal 
code 4-digits area. Then I use the apartment number to filter out impossible 
street(s). Often postcodes for odd and even house numbers differ. So if, for 
instance, I have postcode digits 1234, no postcode letters, and apartment 
number 312, I can ignore all odd number ranges, and all ranges that do not 
include 312 (many streets have just a few dozen numbers). I then end up with a 
bunch of options, which I call candidates. Finally, I use 
difflib.SequenceMatcher to try and select a record of which the "dirty" street 
name, most closely resembles the standard street name in the list of 
candidates. I did not consider what to do when one postcode letter is missing, 
or when letters are transposed. I expect (and hope!) that the street/city 
cannot be derived and that this record needs to be reviewed manually. And in 
case you wondered: yes, it
  sucks that all these corrections need to be done "after the fact". A good 
reason to learn how to use Django or Flask to create a data entry screen and 
start with crisp clean data :-)
> Which is why a different solution may be better suited.
> What about an in-memory SQLite table? Then you can use
> a LIKE based select and let the library do the hard work.
Ouch, I considered marshall and pickle to cache the data, because running the 
query on MS SQL takes more time than I like. But I am embarrassed to say I did 
not even consider SQLite. I will reconsider this. Thank you! 
> Just a thought.
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is an OrderedDict not sliceable?

2016-01-24 Thread Albert-Jan Roskam
> Date: Fri, 22 Jan 2016 11:00:00 +1100
> From: st...@pearwood.info
> To: tutor@python.org
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> 
> Further thoughts on your question...
> 
> 
> On Wed, Jan 20, 2016 at 01:33:17PM +, Albert-Jan Roskam wrote:
> > Hi,
> > 
> > Like the subject says: Why is an OrderedDict not sliceable? (From the 
> > collections library). Was that an intentional omission, or a mistake? 
> > [1]
> > 
> > Background: I do not use OrderedDict very often, but I thought I could 
> > use it to look up street and city names using postcodes ([0-9]{4} 
> > [a-z]{2} format). I needed it to be ordered because I also wanted to 
> > be able to use bisect, which is needed when the postcode letters are 
> > missing. In short: a fast dict lookup for complete postcodes and less 
> > fast bisect lookup for in complete postcodes.
> 
> I'm not sure I understand your use-case here.
> 
> You have postcodes that look like this:
> 
> "1234az"
> 
> Correct? Why do you want them *ordered*? 
> 
> I think you are confusing OrderedDict for a "Sorted Dict". OrderedDict 
> doesn't keep the keys in sorted order, it keeps them in the order that 
> they were inserted. So unless you are super-careful to insert the 
> postcodes in sorted order, the order of them in the dict will be 
> whatever order you insert them:

You are right. See also my reply to Mark Lawrence, who made a similar remark.

> py> from collections import OrderedDict
> py> d = OrderedDict()
> py> d['1234az'] = "1 Smith Street"
> py> d['zz'] = "991203 Short Street"
> py> d['3456mx'] = "24 Hour Lane"
> py> for key in d:
> ... print(key, d[key])
> ...
> 1234az 1 Smith Street
> zz 991203 Short Street
> 3456mx 24 Hour Lane
> 
> 
> So even if OrderedDict supported slicing, that would not do what you 
> think it does.


Oscar Benjamin's link about collections.OrderedDict.__eq__ (or rather, the fact 
that it's not reimplemented) scared the heck outta me :-)
Maybe this class should be avoided altogether?
 
> Also, you have a problem -- what happens if the incomplete postcode is 
> missing the first digit? (I suppose for that case, you just have to do a 
> slow linear search.) What about transposed digits or other errors? I'm 
> glad I don't have to solve that problem!
> 
> 
> Anyway, I suggest doing something like this:
> 
> (1) Keep the known postcodes in a regular dict, not an ordered dict.
> 
> (2) Once you have built the dict, then copy the keys and sort them:
> 
> postcodes = {
> '1234az': "1 Smith Street",
> 'zz': "991203 Short Street",
> '3456mx': "24 Hour Lane",
> }
> 
> array = sorted(postcodes.keys())
> 
> 
> (3) Each time you add a new postcode to the dict, use bisect to add it 
> to the array as well. To ensure you never forget, use a helper function:

But I only *read* from the postcode table. I never insert any postcodes, nor do 
I delete any (ok, a few times a year I load new definitions from the database, 
because new houses, with new postcodes, will have been built).  See also my 
mail to Alan (today).

> def insert(postcode, entry):
> if postcode in postcodes:
> # deal with duplicate/existing key
> ...
> else:
> postcodes[postcode] = entry
> bisect.insort(array, postcode)
> 
> 
> Same for deleting.
> 
> 
> 
> -- 
> Steve
> ___
> 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] Why is an OrderedDict not sliceable?

2016-01-24 Thread Albert-Jan Roskam
> To: tutor@python.org
> From: ben+pyt...@benfinney.id.au
> Date: Fri, 22 Jan 2016 04:12:08 +1100
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> 
> Ben Finney  writes:
> 
> > Oscar Benjamin  writes:
> >
> > > According to a narrow definition of indexed access. I would say that
> > > d[k] is index access even if d is a dict and k a key.
> 
> The sense of “index” implied is used consistently throughout Python
> https://docs.python.org/3/glossary.html> to refer to the integer
> ordinal position in a sequence.

I appear to have confused the terms "sorted" and "ordered" (see the email I 
just sent to Mark Lawrence).  My OrderedDict was sorted on its keys, because I 
defined the dict using the result of an SQL query that ended with ORDER BY 
. So in that case I needed a kind of "chameleon" 
datatype: both a mapping and an indexing type [1]
[1] https://docs.python.org/2/reference/datamodel.html#object.__getitem__ 
 

> It is not compatible with key access into a mapping.
> 
> > An index implies the ordinal position in a sequence. In a mapping, the
> > key is *not* referring to the position in a sequence, so is not a key.
> 
> “the key … is not an index”, I mean.
> 
> > So accessing an item in a mapping by key is not indexed access.
> 
> -- 
>  \ “Facts do not cease to exist because they are ignored.” —Aldous |
>   `\Huxley |
> _o__)  |
> Ben Finney
> 
> ___
> 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] Why is an OrderedDict not sliceable?

2016-01-24 Thread Albert-Jan Roskam
> From: oscar.j.benja...@gmail.com
> Date: Thu, 21 Jan 2016 11:02:40 +
> To: ben+pyt...@benfinney.id.au
> Subject: Re: [Tutor] Why is an OrderedDict not sliceable?
> CC: tutor@python.org
> 
> On 21 January 2016 at 09:19, Ben Finney  wrote:
> > Albert-Jan Roskam  writes:
> >
> >> Why is an OrderedDict not sliceable?
> >
> > Because slicing implies index access. The built-in ‘dict’ and
> > ‘collections.OrderedDict’ both do not support indexed access::
> 
> According to a narrow definition of indexed access. I would say that
> d[k] is index access even if d is a dict and k a key.
> 
> Albert-Jan I guess what you want is this:
> 
> from collections import OrderedDict
> 
> class SliceableOrderedDict(OrderedDict):
> def __getitem__(self, sl):
> if isinstance(sl, slice):
> keys = list(self)
> keyslice = slice(
> None if sl.start is None else keys.index(sl.start),
> None if sl.stop is None else keys.index(sl.stop),
> sl.step
> )
> newitems = ((k, self[k]) for k in keys[keyslice])
> return SliceableOrderedDict(newitems)
> else:
> return super().__getitem__(sl)
 
 
That looks interesting. I will check this out tomorrow at work. If I read it 
correctly this is indeed exactly what I meant. Thank you!!

 
> I guess that the authors of OrderedDict just didn't really consider
> this to be very useful. Apart from having ordered iteration
> OrderedDict is not really that deeply thought out. There's a thread on
> python-ideas about the inconsistent behaviour of the keys and values
> views and equality comparison of OrderedDicts on python-ideas at the
> moment:
> 
> https://mail.python.org/pipermail/python-ideas/2015-December/037472.html

As I said in a prior email: That is SCARY! Should I just avoid OrderedDict like 
the plague?
 

> --
> Oscar
> ___
> 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] Change datatype for specific columns in an 2D array & computing the mean

2016-01-24 Thread Albert-Jan Roskam
> To: tutor@python.org
> From: __pete...@web.de
> Date: Sun, 24 Jan 2016 11:22:19 +0100
> Subject: Re: [Tutor] Change datatype for specific columns in an 2D array & 
> computing the mean

 
> How do you want to convert the second and third column to int? Are A4 and B2 
> hex numbers? Then try
> 
> $ cat esawi.csv 
> 19,A4,B2,2
> 19,A5,B1,12
> $ python3
> Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import numpy
> >>> def fromhex(s):
> ... return int(s, 16)
> ... 
> >>> numpy.genfromtxt("esawi.csv", delimiter=",", converters={1:fromhex, 
> 2:fromhex})
> array([(19.0, 164, 178, 2.0), (19.0, 165, 177, 12.0)], 
>   dtype=[('f0', 'http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
 
 
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Noob: nested if-clauses

2016-01-24 Thread STF
Hi,

I've just started to learn Python thru some online courses and websites.
They just teach very basic things.  I've got some questions about "if" that
I'm unable to find the answers.  So let me ask the newbie questions here.

Let's see the following instructions:

if condition_A:
instruction_1
instruction_2
if condition_B:
  instruction_3
  instruction_4
instruction_5
else:
instruction_6


* How to make Pythom understand that instruction_4 is a part of condition_B
if-clause but not a direct instruction of condition_A if-clause?  And how
to make Python understand that instruction_5 is outside of condition_B
if-clause?  Just by the number of white spaces in front of every
instruction??

* How to make Python understand that "else" belongs to the first
condition_A if-clause, not to the immediate condition_B if-clause?

* Suppose I put four white spaces in front of instruction_1, and then "tab
key" in front of instruction_2, would this break things?  I ask so because
most intelligent text editors would insert automatically a tab in place of
4 white spaces after we press Enter on a line with 4 leading white spaces.

* Do I really need to keep the consistency of 4 white spaces?  Not one more
or one less?

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


Re: [Tutor] Noob: nested if-clauses

2016-01-24 Thread Joel Goldstick
On Sun, Jan 24, 2016 at 2:42 PM, STF  wrote:

> Hi,
>
> I've just started to learn Python thru some online courses and websites.
> They just teach very basic things.  I've got some questions about "if" that
> I'm unable to find the answers.  So let me ask the newbie questions here.
>
> Let's see the following instructions:
> 
> if condition_A:
> instruction_1
> instruction_2
> if condition_B:
>   instruction_3
>   instruction_4
> instruction_5
> else:
> instruction_6
> 
>
> * How to make Pythom understand that instruction_4 is a part of condition_B
> if-clause but not a direct instruction of condition_A if-clause?  And how
> to make Python understand that instruction_5 is outside of condition_B
> if-clause?  Just by the number of white spaces in front of every
> instruction??
>
> * How to make Python understand that "else" belongs to the first
> condition_A if-clause, not to the immediate condition_B if-clause?
>
> * Suppose I put four white spaces in front of instruction_1, and then "tab
> key" in front of instruction_2, would this break things?  I ask so because
> most intelligent text editors would insert automatically a tab in place of
> 4 white spaces after we press Enter on a line with 4 leading white spaces.
>
> * Do I really need to keep the consistency of 4 white spaces?  Not one more
> or one less?
>

yes.  you can use 1 or 2 or any number of spaces, but do spacing
consistently.  4 is recommended. Don't mix tabs and spaces

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



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Noob: nested if-clauses

2016-01-24 Thread Alan Gauld
On 24/01/16 19:42, STF wrote:

> Let's see the following instructions:
> 
> if condition_A:
> instruction_1
> instruction_2
> if condition_B:
>   instruction_3
>   instruction_4
> instruction_5
> else:
> instruction_6
> 
> 
> * How to make Pythom understand that instruction_4 is a part of condition_B
> if-clause but not a direct instruction of condition_A if-clause?  

You've done it above by the indentation.

> to make Python understand that instruction_5 is outside of condition_B
> if-clause?  Just by the number of white spaces in front of every
> instruction??

Yes, the indent level tells Python where the instruction should be.

> * How to make Python understand that "else" belongs to the first
> condition_A if-clause, not to the immediate condition_B if-clause?

Again you've done it already, just use the indent level.

> * Suppose I put four white spaces in front of instruction_1, and then "tab
> key" in front of instruction_2, would this break things?  

In Python 2 things are a wee bit flexible but in Python 3 less so.
But in general avoid mixing them, stick to spaces. Most Python
programmers set their text editor/IDE to convert tabs to
spaces(usually 4)

> most intelligent text editors would insert automatically a tab in place of
> 4 white spaces after we press Enter on a line with 4 leading white spaces.

Most can also be configured not to use tabs at all and
for Python that's better. Tell us your editor and somebody
can probably advise on optimum settings.

> * Do I really need to keep the consistency of 4 white spaces?  Not one more
> or one less?

No you can have as many or as few as you like in your own code,
just be consistent. 4 just happens to be esy to read. And its
the standard for library code so if you want to write some code
for the standard library you will need to use 4 spaces. In
the interpreter (>>>) I often only use 2 just to save typing.
But for production code I stick with 4 - not a problem since
the editor(vim) does most of the work for me.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Why is an OrderedDict not sliceable?

2016-01-24 Thread Mark Lawrence

On 24/01/2016 20:23, Albert-Jan Roskam wrote:


I appear to have confused the terms "sorted" and "ordered" (see the email I just sent to Mark 
Lawrence).  My OrderedDict was sorted on its keys, because I defined the dict using the result of an SQL query that 
ended with ORDER BY . So in that case I needed a kind of "chameleon" 
datatype: both a mapping and an indexing type [1]
[1] https://docs.python.org/2/reference/datamodel.html#object.__getitem__



Can you use one of the containers here 
http://www.grantjenks.com/docs/sortedcontainers/ ?


If yes it's as simple as:-

pip install sortedcontainers

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] Why is the name "self" optional instead of mandatory?

2016-01-24 Thread Steven D'Aprano
On Fri, Jan 22, 2016 at 11:10:39PM -0600, boB Stepp wrote:
> On Thu, Jan 21, 2016 at 5:49 AM, Steven D'Aprano  wrote:

> > class X:
> > pass
> >
> > def func(this):
> > print("instance %r called method" % this)
> >
> > X.method = func
> 
> Am I understanding this correctly?  It appears to me that you have
> successfully added a method to class X from outside of class X!  If
> this is the case, then this clarifies some things I was wondering
> about in my other thread.

Yes, you are reading it correctly.

Of course, in practice you wouldn't do that as shown. Why write the 
method outside the class when you could write it inside the class? There 
are some good reasons for doing something similar though:

(1) Perhaps you have a whole family of classes that share the same 
method. Three traditional solutions to this are to use inheritence, a 
mixin class, or traits. But a fourth is to create your classes without 
the method, then dynamically add the extra, shared, method into each one 
afterwards.

Possibly by using a simple decorator:

def method(self, arg): ...

def decorate(cls):
cls.method = method
return cls

@decorate
class Spam: ...

This technique is even more powerful when the method you are injecting 
is *slightly different* each time. For that, you can use a closure, 
created *inside* the decorator function. Play around with this example 
and see if you can understand what is going on:


# Warning: this may expand your mind.

def decorate(number):
# Create a closure over the number.
def method(self, x):
"""Return x + %d."""
return x + number
method.__doc__ %= number
# Create a decorator.
def decorator(cls):
# Inject the method into the class.
cls.method = method
return cls
# Return the decorator so it can be used.
return decorator

@decorate(5)
class AddFive:
pass

@decorate(9)
class AddNine:
pass



(2) Another reason for doing this may be that you have an existing class 
from some library that you have to use. You can't subclass it, because 
too much of your code already depends on using that specific class. In 
some languages, like Java, perhaps the library authors marked the class 
as unsubclassable. But you want to add a new method for your own use.

Here's an example of this:

http://stackoverflow.com/questions/13730924/java-adding-fields-and-methods-to-existing-class

You'll notice that the answers given don't really solve the problem, 
apart from a vague and scary-sounding suggestion to use "byte-code 
injection". A number of people suggest subclassing, but a comment 
from another person says the the question also applies to him, but in 
his case subclassing isn't practical.

In Python, we have two solutions:

Write a function, and use that. Instead of calling obj.new_method(), 
we simply have new_function(obj). This option is available to Java as 
well, but hardly anyone ever thinks of it because Java is the Kingdom of 
Nouns: 

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html

Or *monkey-patch* the class using a new method we create on the outside.

https://en.wikipedia.org/wiki/Monkey_patch

Monkey-patching is a powerful technique, but should be used with care. 
Overuse is considered harmful:

http://devblog.avdi.org/2008/02/23/why-monkeypatching-is-destroying-ruby/


[...]
> I guess I am trying to wrap my mind around this incredible power and
> flexibility that Python provides.  I thought I had asked a relatively
> harmless question.  But it generated some strong responses!  It seemed
> like "self" had a similar utility of use as "print" to me.  After all,
> we can't redefine "print", can we?  But now I realize that I can do
> exactly that if I so choose.  That is both fascinating and scary!

Indeed. And in Python 3, print is a regular function, which means it 
*can* be redefined by shadowing, or even by monkey-patching the 
built-in module.


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


Re: [Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?

2016-01-24 Thread Steven D'Aprano
On Fri, Jan 22, 2016 at 10:14:57PM -0600, boB Stepp wrote:
> On Thu, Jan 21, 2016 at 4:57 AM, Steven D'Aprano  wrote:

> > def spam(x, y):
> > ...
> >
> > spam.extra_info = "whatever"
> 
> A new thing that I did not suspect I could do.  This bothers me for two 
> reasons:
> 
> 1)  It does not seem right adding attributes to functions outside
> of its definition.

Well, unfortunately there's no syntax for adding attributes to a 
function *inside* its definition. If you put it inside the body of the 
function, it won't get run until you call the function:

def spam(arg):
spam.widget = some_widget

spam.widget  # Fails because the function hasn't been run yet.


If you put it before the function definition, the function doesn't 
exist yet:

spam.widget = some_widget  # Fails because spam doesn't exist.
def spam(arg): 
...

So the only thing left is to put it *after* the definition.

In practice, I would create a decorator that adds the extra attribute, 
so you can write:


def add_widget(the_widget):
def decorator(func):
func.widget = the_widget
return func
return decorator

@add_widget(some_widget)
def spam(arg):
...



 
> 2)  spam.extra_info appears to be global:

`spam` is global, but only because you created it in the global 
namespace. You could have put it in a class, or nested inside another 
function. `extra_info` is not global, it is attached firmly to `spam`, 
no different from the 30 or so existing attributes of functions:

py> dir(lambda:None)
['__annotations__', '__call__', '__class__', '__closure__', '__code__', 
'__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', 
'__eq__', '__format__', '__ge__', '__get__', '__getattribute__', 
'__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', 
'__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', 
'__qualname__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']

or for that matter nearly any object. Even None has 20+ attributes.

You'll notice that *by default* all of the function attributes are 
__dunder__ names, which mean that they are used (somewhere) by the 
Python implementation. E.g. the __code__ object contains the actual 
byte-code of the function. But you can add your own, if you have a 
reason to do so.

It would have been very easy for the core developers to prohibit the 
addition of arbitrary attributes to functions: just don't give functions 
a __dict__ attribute. And indeed, in the earliest versions of Python, 
such as version 1.5, functions didn't have a __dict__ and you couldn't 
add attributes to them. So it is a deliberate choice to allow adding 
attributes to functions, but not strings, ints, floats etc.


[...]
> And I imagine I am being dense about something that is quite obvious
> to you:  How is this a useful feature to have?  What does it give me
> that is more useful than just saying something like:
> 
> just_another_global variable = "whatever"
> 
> ?


It keeps the function's data close to the function. What if you have two 
functions, spam and eggs, that both want to claim the name "widget" for 
their internal data? Do they just stomp all over each other's data? Or 
do you call them "spam_widget" and "eggs_widget"?

If you can write spam_widget, what's wrong with writing spam.widget 
instead?



> And what bothered me about my original example that started this
> thread is that when my typo
> 
> humdrum.sigh_strenght = 'high'
> 
> was accepted and did not generate an error, it seemed to mean to me
> that I was violating my object's data encapsulation.

That's a matter of opinion.

Encapsulation just means that data and code that operates on that 
data are bundled together in some sense. Encapsulation isn't even 
*necessarily* to do with objects. Ancient 1970s BASICs even had a 
primitive form of encapsulation, with the DATA statement. You could 
encapsulate data in the same file as the BASIC code that operated on 
that data.

One question is whether objects are *open* or *closed* to modifications. 
Python defaults to them being open unless there are good reasons for 
them to be closed. Other languages, like Java, default to them being 
closed: you can't easily add new attributes to Java objects after 
creation.


> It just seems to
> me that I should not be able to arbitrarily add new attributes from
> outside the class definition that created my object.  That seems
> similar to having a class Dog, to which from outside the class'
> definition, I decide to add a new Dog attribute that all dogs in this
> class can now have a tail sticking out of their noses.

That would be:

lassie = Dog()
lassie.nose.tail = make_tail()

Yes, that would be a silly thing to do. But how about this?

lassie = Dog()
lassie.collar = Collar()

I don't think that collar should be an attribute of all dogs. I know 
that Gaspode wouldn't be caught dead wearing a collar:

http://wiki.lspace.org/mediawiki/index.php/