Re: [Tutor] feedback on simple python code

2017-02-28 Thread Peter Otten
Ryan Smith wrote:

> Hi all,
> 
> New python student here. I have been using O¹reilly¹s "Python Beyond the
> Basics: Object Oriented Programming video series". In one of the
> assignments we are to write a simple inheritance hierarchy of three
> classes that write to text files. I have actually written the code for the
> assignment and it runs as well as meets the requirements of the
> assignment. I am posting to get feedback on how I can improve this and
> making it more pythonic and concise.
> 
> Please keep in mind that I am simply ³simulating" writing to a log file
> and a tabbed delimited file, so I¹m not necessarily looking for which
> modules I could have to create actual log files or writing to actual csv
> files. The output of the code should be two text files with text written
> to them that have been passed to the instance of each respective object.
> 
> #!/usr/bin/env python
> 
> import abc
> import datetime
> 
> class WriteFile(object):
> __metaclass__ = abc.ABCMeta
> 
> 
> @abc.abstractmethod
> def write(self,text):

You might run a tool like https://pypi.python.org/pypi/pycodestyle over your 
code to ensure it follows common standards.

> """Write to file"""
> return
> 
> 
> class LogFile(WriteFile):
> def __init__(self,fh):
> self.fh = fh
> 
> 
> def write(self, text):
> date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
> entry = "{0} {1}{2}".format(date, text, '\n')
> with open(self.fh, 'a') as f:
> f.write(entry)
> 
> class DelimWrite(WriteFile):
> def __init__(self, fh, delim):
> self.fh = fh
> self.delim = delim
> 
> 
> def write(self, text):
> with open(self.fh, 'a') as f:
> entry = ""
> for item in text:
> if self.delim in item:
> entry += ' "{0}"{1} '.format(item,self.delim)

What will happen if text contains double quotes?

> else:
> entry += item+self.delim

Have a look at the str.join() method. Example:

>>> ",".join(["foo", "bar", "baz"])
'foo,bar,baz'

> f.write(entry.strip(self.delim) + '\n')

I will mention another "principle", DRY (don't repeat yourself), i. e. do 
not write the same code twice.

When I look at your code I see that both DelimWrite and LogFile open a file. 
If you want modify your code to accept file objects like sys.stdout you have 
to make changes in both subclasses. To avoid that you might put the file-
writing part into a separate method:

class WriteFile(object):
def __init__(self, file):
self.file = file

def write_record(self, record):
with open(self.file, "a") as f:
f.write(self.format_record(record))

def format_record(self, record):
return record


class LogFile(WriteFile):
def format_record(self, record):
date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return "{0} {1}\n".format(date, record)


class DelimWrite(WriteFile):
quote = '"'
def __init__(self, file, delimiter):
super(DelimWrite, self).__init__(file)
self.delimiter = delimiter

def escaped(self, value):
value = str(value)
if self.delimiter in value:
quote = self.quote
value = '"{}"'.format(value.replace(quote, quote + quote))
return value

def format_record(self, record):
escaped_rows = (self.escaped(value) for value in record)
return self.delimiter.join(escaped_rows) + "\n"


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


Re: [Tutor] Learning Objectives?

2017-02-28 Thread Aaron Myatt via Tutor
Just my humble contribution: I rather appreciated this fellows intermediate
python tutorial series:
https://youtu.be/YSe9Tu_iNQQ?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_

Though I would argue some other topics, like context managers, would also
be worth including in his list.

On 28 Feb 2017 9:15 a.m., "Alan Gauld via Tutor"  wrote:

> On 27/02/17 14:57, leam hall wrote:
>
> >> I'm not aware of such a list, and I'm not sure it's of much value.
> >> Better to just learn what you need and use it. ...
>
> > When I was coming up as a Linux guy I took the old SAGE guidelines and
> > studied each "level" in turn. It was useful for making me a well-rounded
> > admin and helped me put off some higher end stuff I wasn't really ready
> > for.
>
> Its an individual choice, so if it works for you don't let
> me stop you :-) But I still don't know of any such list.
>
> > documentation. It's sort of the "if we hired a junior or senior coder,
> what
> > basics would we want them to know?"
>
> That's the thing. I've never, in 40 years in IT, seen
> anyone advertise for a junior programmer. Just doesn't seem to
> happen. It's a bit like having a headache and asking for a
> weak pain killer...
>
> There are places offered for programming apprenticeships,
> but they assume you are starting from scratch.
>
> --
> 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


[Tutor] The benefits of a junior programmer (was: Learning Objectives?)

2017-02-28 Thread Ben Finney
Alan Gauld via Tutor  writes:

> That's the thing. I've never, in 40 years in IT, seen anyone advertise
> for a junior programmer. Just doesn't seem to happen.

Several employers in my career, including my current employer, actively
seek to fill some positions with junior programmers.

> It's a bit like having a headache and asking for a weak pain killer...

Not at all. Apart from the obvious (a junior position commands a smaller
payroll, so is easier to fit into a departmental budget), junior
programmers can only gain proper experience if someone employs them and
many employers recognise that.

There is a world of difference between lack of specific experience with
a tool, and lack of ability to learn in the right environment. A good
junior programmer will be in the former category only.

> There are places offered for programming apprenticeships, but they
> assume you are starting from scratch.

In my experience, many employers will seek programmers who have some
amount of experience but not enough to demand a senior salary. Most
projects are complex and specific enough that every new hire, regardless
of seniority, will spend a lot of time initially coming up to speed on
that project.

Junior programmers paired with senior programmers can be a powerful
force in an organisation. I encourage junior programmers to see their
fresh perspective and lower salary demand as an attractive and saleable
feature when seeking employment.

-- 
 \   “Firmness in decision is often merely a form of stupidity. It |
  `\indicates an inability to think the same thing out twice.” |
_o__)—Henry L. Mencken |
Ben Finney

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


Re: [Tutor] Learning Objectives?

2017-02-28 Thread Leam Hall

On 02/27/17 20:12, Alan Gauld via Tutor wrote:

On 27/02/17 14:57, leam hall wrote:


I'm not aware of such a list, and I'm not sure it's of much value.
Better to just learn what you need and use it. ...



When I was coming up as a Linux guy I took the old SAGE guidelines and
studied each "level" in turn. It was useful for making me a well-rounded
admin and helped me put off some higher end stuff I wasn't really ready
for.


Its an individual choice, so if it works for you don't let
me stop you :-) But I still don't know of any such list.


Understood. However, think about the issue from a newbie perspective.

1. The Python Tutor e-mail list helps with questions when someone can 
frame a question.


2. Books or videos like "Learning Python", "Learn Python the Hard Way", 
or the Coursera/EdX classes cover what the publisher felt could be 
covered in a profitable way.


3. Books like "Python Projects" can help someone go from absolute newbie 
to being able to do useful stuff. 


When I was learning Ruby I put section dividers in a 3 ring binder and 
had one section for each of the topics in the Pickaxe book. That way as 
I learned and relearned things could gel a little better. I have an old 
copy of "Learning Python" and will break out the section dividers today.


I don't know about anyone else, but I have a bad habit of jumping in way 
over my head and getting frustrated when I can't make things work. By 
setting a sequential list it helps prevent that; learning Objects is 
much easier when one understands functions.



documentation. It's sort of the "if we hired a junior or senior coder, what
basics would we want them to know?"


That's the thing. I've never, in 40 years in IT, seen
anyone advertise for a junior programmer. Just doesn't seem to
happen. It's a bit like having a headache and asking for a
weak pain killer...

There are places offered for programming apprenticeships,
but they assume you are starting from scratch.



The PHP community has a Mentoring thing (https://php-mentoring.org/), 
and I would assume there are many open source Python projects that would 
be willing to bring a junior in and help them grow. Growth and 
contributing seem to go hand in hand. It's easy to read a book and think 
you "know" a language. It's more challenging when you're in the lab with 
seasoned programmers and you're pushed to produce better and better code.


It's a lot nicer for the seasoned programmers if you don't have to be 
convinced to write tests or taught what an object is.  :)


The "junior" level is more a gift to the seasoned programmers; someone 
who can do those basics has proven a willingness to learn coding past 
the "type what's in the book" phase. Of course, one must go through 
junior to get to senior.


For those interested, GIAC has a Certified Python Programmer. It focuses 
on using security tools, which is GIAC's forte.


http://www.giac.org/certification/python-coder-gpyc

Does a certification make you a better coder? Not really, there are lots 
of uncertified (but probably certifiable!) expert coders out there. 
However, certifications can help in the job search and it's nice to get 
paid for what you enjoy.


Leam




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


Re: [Tutor] Learning Objectives?

2017-02-28 Thread M Hashmi
Coding is an artthat helps you craft beautiful things in digital world.
As beginner it's pretty natural to confuse about which learning curve can
benefit you most in future.

If I were you I would go with simple approach. I would choose best of the
best software available and start building its source by looking at it. Bit
by bit piece by piece it would help you to understand a pre-built
application.

Lets assume as you've posted in Django group so you might be interested in
web development. Pick a best project and start writing your own guide for
yourself. The best one I came across is django-oscar. Start building it's
replica and document each step in the process for yourself. You can consult
the django's own docs as well as django-oscar's documentation for
understanding what the function/class is about.

I bet that in a single month you will be able to build a semi-dynamic site
yourself. In maximum 3 to 4 months you can really do wonders.

Hope it helps.

Regards,
M

On Tue, Feb 28, 2017 at 1:39 AM, Aaron Myatt via Tutor 
wrote:

> Just my humble contribution: I rather appreciated this fellows intermediate
> python tutorial series:
> https://youtu.be/YSe9Tu_iNQQ?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_
>
> Though I would argue some other topics, like context managers, would also
> be worth including in his list.
>
> On 28 Feb 2017 9:15 a.m., "Alan Gauld via Tutor"  wrote:
>
> > On 27/02/17 14:57, leam hall wrote:
> >
> > >> I'm not aware of such a list, and I'm not sure it's of much value.
> > >> Better to just learn what you need and use it. ...
> >
> > > When I was coming up as a Linux guy I took the old SAGE guidelines and
> > > studied each "level" in turn. It was useful for making me a
> well-rounded
> > > admin and helped me put off some higher end stuff I wasn't really ready
> > > for.
> >
> > Its an individual choice, so if it works for you don't let
> > me stop you :-) But I still don't know of any such list.
> >
> > > documentation. It's sort of the "if we hired a junior or senior coder,
> > what
> > > basics would we want them to know?"
> >
> > That's the thing. I've never, in 40 years in IT, seen
> > anyone advertise for a junior programmer. Just doesn't seem to
> > happen. It's a bit like having a headache and asking for a
> > weak pain killer...
> >
> > There are places offered for programming apprenticeships,
> > but they assume you are starting from scratch.
> >
> > --
> > 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
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Learning Objectives?

2017-02-28 Thread Fred Stluka
   On 2/27/17 9:57 AM, leam hall wrote:

 On Mon, Feb 27, 2017 at 9:28 AM, Alan Gauld via Tutor [1]
 wrote:


 On 27/02/17 10:44, Leam Hall wrote:

 Is there a list of Python skill progression, like "Intermediates should
 know  and Advanced should know ?" Trying to map out
 a well rounded study list.

 I'm not aware of such a list, and I'm not sure it's of much value.
 Better to just learn what you need and use it. When you need
 to learn more, learn it. The worst thing you can do is study an
 arbitrary list of topics that don't have any relevance to
 the problems you need to solve!

 ...

 When I was coming up as a Linux guy I took the old SAGE guidelines and
 studied each "level" in turn. It was useful for making me a well-rounded
 admin and helped me put off some higher end stuff I wasn't really ready
 for.

 ...



   I agree with Leam.  If anyone has such a list, I think many of us
   would be interested to see it.

   Personally, I'd already been a programmer for 30 years when I
   first started using Python and Django.  I learned them in bits and
   pieces, as needed for a 4 year project.  I never took time to read
   a comprehensive book on either topic.  Also, they both evolved
   quite a bit during those 4 years, with many new and changed
   features.  So it's possible that I've completely overlooked some
   relatively basic features.

   If there were such a list, I'd quickly scan the "basic" section to
   what I may have missed.  Then, I'd scan the more advanced
   sections to what else exists.

   It would also be useful when teaching Python to someone else,
   to have some guidance about which language constructs are
   used most often.

   As a quick straw man, here's a syllabus I started whipping up
   recently for a Python and Django class I was asked to teach.
   - [2]http://bristle.com/Courses/PythonDjangoIntro/syllabus.html

   It has 5 main sections:
   - Python
   - Django
   - Possible Advanced Python Topics
   - Possible Advanced Django Topics
   - Possible Related Topics

   The class would be ten weeks, with 6 hours of lecture and 4
   hours of lab per week, so I'd hope to cover all of the 1st 2
   sections, and perhaps some/all of the last 3 sections.

   Feel free to comment on errors, omissions, misplaced items, etc.

   Enjoy!
   --Fred

   --

   Fred Stluka -- [3]mailto:f...@bristle.com -- [4]http://bristle.com/~fred/
   Bristle Software, Inc -- [5]http://bristle.com -- Glad to be of service!
   Open Source: Without walls and fences, we need no Windows or Gates.

   --

References

   Visible links
   1. mailto:tutor@python.org
   2. http://bristle.com/Courses/PythonDjangoIntro/syllabus.html
   3. mailto:f...@bristle.com
   4. http://bristle.com/~fred/
   5. http://bristle.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] pygrib issues involving wind

2017-02-28 Thread Jason Snyder
I have a grib2 file.  You can see the components of this grib2 file below:

wgrib2 -v chart_2017022812_0057.grb2

1:0:d=2017022812:RH Relative Humidity [%]:2 m above ground:57 hour fcst:
2:227081:d=2017022812:TMAX Maximum Temperature [K]:2 m above ground:54-57
hour max fcst:
3:486870:d=2017022812:UGRD U-Component of Wind [m/s]:10 m above ground:57
hour fcst:
4:751610:d=2017022812:VGRD V-Component of Wind [m/s]:10 m above ground:57
hour fcst:
5:1009523:d=2017022812:PRATE Precipitation Rate [kg/m^2/s]:surface:54-57
hour ave fcst:


Now I am trying to use pygrib to extract the U and V wind components of
this grib2 file with the below python script:

grib = 'chart_2017022812_0057.grb2'

grbs=pygrib.open(grib)
uwind = grbs.select(name='U-component of wind')[0]
rh = grbs.select(name='Relative humidity')[0]
temp = grbs.select(name='Maximum temperature')[0]
prate = grbs.select(name='Precipitation rate')[0]

while with this script, I am able to successfully extract relative
humidity, temperature, and precipitation rate, I am having a problem
extracting the u component of wind.  I get the error:

Traceback (most recent call last):
  File "testgrib.py", line 16, in 
uwind = grbs.select(name='U-Component of wind')[0]
  File "pygrib.pyx", line 609, in pygrib.open.select (pygrib.c:6175)
ValueError: no matches found


How can I resolve this issue?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pygrib issues involving wind

2017-02-28 Thread Ben Iannitelli
Hi Jason,


I know nothing about pygrib, but usually Python is case-sensitive.


Look again at the upper-case and lower-case letters in the original file:

1:0:d=2017022812:RH Relative Humidity [%]:2 m above ground:57 hour fcst:
2:227081:d=2017022812:TMAX Maximum Temperature [K]:2 m above ground:54-57
hour max fcst:
3:486870:d=2017022812:UGRD U-Component of Wind [m/s]:10 m above ground:57
hour fcst:
4:751610:d=2017022812:VGRD V-Component of Wind [m/s]:10 m above ground:57
hour fcst:
5:1009523:d=2017022812:PRATE Precipitation Rate [kg/m^2/s]:surface:54-57
hour ave fcst:

Now look again at your code:

grbs=pygrib.open(grib)
uwind = grbs.select(name='U-component of wind')[0] #<"component" with small 
"c" and #"wind" with small "w"
rh = grbs.select(name='Relative humidity')[0] #<"humidity" with a small "h"
temp = grbs.select(name='Maximum temperature')[0] #<"temperature" with a 
small "t"
prate = grbs.select(name='Precipitation rate')[0] #< "rate" with a small "r"

while with this script, I am able to successfully extract relative
humidity, temperature, and precipitation rate, I am having a problem
extracting the u component of wind.

I don't know why letter case wouldn't matter for the other fields (did you cut 
and paste, or type from memory?), but if you alter your code to match the 
capitalization exactly, you might rule case sensitivity out.

Traceback (most recent call last):
  File "testgrib.py", line 16, in 
uwind = grbs.select(name='U-Component of wind')[0]
  File "pygrib.pyx", line 609, in pygrib.open.select (pygrib.c:6175)
ValueError: no matches found

HTH,

-Ben I.

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