jmcfarland

Author. Coder. Geek. Reader. Baker of bread. Brewer and drinker of beer. Writer of code. Destroyer of developer egos. Also, I make really, really good pancakes.

Creating a successful project – Part 3: Development Tools/Equipment

Every single year that I’ve been doing this, I hear about the next “totally awesome” way to write code.  And more often than not, the new thing is certainly very shiny.

When it comes to projects, with the exception of coding standards (which will be part 4 of this series) I am not a fan of telling developers how to write code.  If you’ve got someone who likes to write code using Notepad on a Microsoft Windows machine, more power to them.  Oh, you like coding in SublimeText3 on Mac – go for it.

If you work on one of my projects there are only a few rules I have about how you write your code:

  1. It must maintain the agreed-upon standard (such as PEP8)
  2. Your code – under penalty of my ire – must work on the designated system.  If it WFM, “Works for Me” then you must get it working on the chosen system. (More on this topic in the test and build posts) And trust me, there’s plenty of people out there – including other contributors to this site – who would shudder to think of my ire directed singly upon them.
  3. Use whatever the agreed upon (preferably Git) source code control system.
  4. Use whatever build system is in play.  Usually, this is done via a Jenkins server, but I’m not picky.  I want consistency, and I want to make sure that the output of the project is reliable.  More on build systems in the CI/CD section.

Notice something odd in there: nowhere did I say you had to use this particular editor or debugger.  I honestly couldn’t care less if you like to write your code using Comic Sans or SourceCodePro.  I really don’t care if you like to code using EMACS or Sublime.  The tools one uses to write code should be selected through a similar vetting process to purchasing a good chef’s knife: use what you feel most comfortable using.

But, in the interest of showing what a rather more seasoned coder uses, here’s my setup:

Keyboard – Microsoft Natural Ergonomic Keyboard – I spend 8-16 hours a day on a keyboard, so I want my keyboard to be comfortable and able to handle heavy use.  The good thing (besides that this is a great keyboard) they’re nice and cheap.  So when one dies, I just buy another.

Mouse – ROCCAT Kone Pure Color – This is just a really great mouse.

Editor- Vim or, as of recent Neovim – I’ve used Vi/Vim for decades so I’m a bit of an old hat at using them.

Operating System – Debian Linux – When you want the best and you don’t want extra crap getting in your way; accept only the best.

I use that same setup at work as well as home.  I am not endorsed by any of the product manufacturers; I just know what works for me.  If I find a keyboard in the same form-factor as the one I’m using with Cherry MX Browns, I’ll buy two of them in a heartbeat.

I have also made use of PyCharm and Atom.  Both of which I still use with Vim Keybindings.

 

Creating a successful project – Part 2: Project Organization

Ok, so you’ve familiarized yourself with the rules.  Good.  This isn’t Fight Club, but they are important rules. You want to be a professional in all the projects on which you want to participate.  If properly managed, your GitHub account should be a functional part of your ever-evolving resume.

Code organization:

So, code itself really isn’t hard to organize.  But you’d be surprised how many people just don’t get it.  Since I usually develop in python, here is my standard project directory structure:

./new_project.
 ├── CONTRIBUTING.md
 ├── doc
 ├── LICENSE.md
 ├── README.md
 ├── scripts
 ├── setup.py
 ├── src
 └── tests

If you code in a different language which has different structural requirements, make changes.  This is how I do it.

First, the markdown files:

I’m not going to worry over the preference for ReStructuredText, Markdown, LaTeX, or basic text for these files.  Feel free to do your own research and come to your own conclusions.

CONTRIBUTING.md

This document is optional for simple projects.  It is possible to have this as part of the README.  In this document, you should spell out how people can contribute to your project.  Should they fork and submit pull requests?  How should they report issues and/or request new features?  These are important questions.  Not just for potential compatriots, but for you.

LICENSE.md

This should have the text of the license under which you are placing the project.  You can cut and paste this from any number of reputable licensing sources.  I recommend reading about the different licenses here. I will also be going over the primary players in a future post.

README.md

I feel that the project README is non-optional.  This single document should have key information about the project.  It should (ideally) address the following:

  1. What is the purpose of this project?  Think of it as the two-to-three sentence description of the project.  What problem were you trying to solve?
  2. Where to find more documentation.
  3. Installation instructions
  4. Simple configuration settings – if appropriate.
  5. Possibly simple use-cases and examples.

Optional Docs:

DONATIONS.md/SPONSOR.md – Where/how to send any monetary donations.  A good example of what might be found in a donations/sponsorship doc can be found here.

THANKS.md – If you want to thank anyone for help or encouragement, this would be alright to add.  Completely optional.

Now the directories:

doc

This is where your project documentation should reside.  If you do this correctly, you can easily get them posted to readthedocs.org.

scripts

This is optional for projects which have no need for command-line scripts.  But, if your project has a command-line tool associated with it, you should really consider having them in this directory.

src

This is where your code should reside.

tests

This is where the tests for your code should be found.  Having tests is a big indicator of the health and maturity of the project.  The tests here should show that you take the writing and maintaining of the code very seriously.

Optional Directories:

examples – Some people like to house some usage examples here.  If appropriate, feel free.

 

 

 

Creating a successful project – Part 1: The Rules

So, you want to create a project.  That’s great!  Welcome to the party.  I’d like to pass along some general knowledge about how best to approach creating/running a project.  Also, I’m not going to say that I know everything there is to know about running a successful project.  I have run a few projects in my time, some successful, some less so;  I also have some hard-fought lessons learned that I am going to share.  Perhaps you’ll use some of this knowledge to improve your projects.

One side note on what I am teaching/advocating here:  I am not telling you some secret to making your project the next docker or requests.  I’m showing you best practices for success.  These ideas and concepts are good for any size or purpose of a software project.  They have been successfully used on single-person projects all the way up to projects with 70+ contributors.  Good ideas and buy-in from your team are critical to success, but they are never going to be enough to replace plain old elbow grease to write the code, docs, and tests for a project.  That stuff takes discipline and time.

General Project Structure Rules

  1. If you want you (and your project) to be taken seriously?  Be organized.
  2. Tests are non-optional.
  3. Documentation is also non-optional.
  4. Documentation should read like it was written by someone with knowledge who cares about informing a newcomer to the project.
  5. You should understand contributor roles if any.
  6. You MUST understand the licenses that are in regular use and decide which license to use.  This is more about long-term CYA than anything else.

Well, there’s the first entry in this series.  I hope people find it interesting.

 

Indisputably immutable

For many of us, as we develop as coders, we want to continue to grow our knowledge. We pour over the standard library (STL) of this wonderful language, looking for hidden gems. There are many such gems in the Python STL. Such as all the fun things you can do with sets and itertools. But one of the lesser used (which is a real shame) is found in the collections module: namedtuples.

So….what is a named tuple?

from collections import namedtuple

Address = namedtuple("Address", ["number", "street", "city", "state", "zip_code"])

the_prez = Address("1600", "Pennsylvania Avenue", "Washington", "DC", "20500")

print("{the_prez.number} {the_prez.street}".format(**locals()))

 

Pretty boring stuff all around, right? Who cares that you can get dotted notation from this? Why not just write your own class?  You totally can.  There’s nothing to it.

class Address(object):
    def __init__(self, number, street, city, state, zip_code):
        self.number = number
        self.street = street
        self.city = city
        self.state = state
        self.zip_code = zip_code

Yep. Gotta love the classic Python class. Super explicit, which is keeping in one of the core tenants of the Python. But, then, depending on your use-case they may have a weakness.  Let’s say that the type of class you have written is all about data storage and retrieval.  That means you’d really like the data to be reliable and, in a word: immutable.  If you just write the aforementioned class and someone wants to change the street number where the president lives it’s pretty simple stuff:

class Address(object):
    def __init__(self, number, street, city, state, zip_code):
        self.number = number
        self.street = street
        self.city = city
        self.state = state
        self.zip_code = zip_code

the_prez = Address("1600", "Pennsylvania Avenue", "Washington", "DC", "20500")
the_prez.number = "1601"

Boom, now the postman will now deliver your postcard from the grand canyon to the wrong house.

“But,” you say, “I could just override __setitem__ and be done with my class!” You are correct. But, maybe, just maybe you’re a lazy coder (as I believe all coders should be from time to time), and you want to have immutibility without having to rewrite a core behavior of your class?  Why, what you’d be talking about would have the immutability of a tuple, with the flexibility of a class! Sounds crazy?  Sounds impossible?  Well, guess what?  You can have it.

Named tuples, just as the name implies is a tuple (an immutable data type) which uses names instead of numerical indexing. Simple. But, why the devil would you use them if you already control the code? Is it simply the immutability?

class Address(namedtuple("Address", ["number", "street", "city", "state", "zip_code"])):

    def __new__(cls, number=None, street=None, city=None, state=None, zip_code=None):
        return super(Address, cls).__new__(
            cls,
            number=number,
            street=street,
            city=city,
            state=state,
            zip_code=zip_code)

So, what happens if you try to redirect that grand canyon postcard by changing the house number now?

Traceback (most recent call last):
 File "namedtuplecraziness.py", line 74, in
 the_prez.number = "1601"
 AttributeError: can't set attribute

Nope.  Sorry.  Protected by immutability!

Of course, there are always oddities.  If you were to have a mutable variable in the namedtuple, the variable retains its mutability, while the other (non-mutable) variables remain immutable.  Here’s an example where we make the ‘number’ field into a list.  Which means we can now change it through direct index-based assignment or even through append.

Here’s an example where we make the ‘number’ field into a list.  Which means we can now change it through direct index-based assignment or even through append.

from collections import namedtuple

class Address(namedtuple("Address", ["number", "street", "city", "state", "zip_code"])):
    def __new__(cls, number=None, street=None, city=None, state=None, zip_code=None):
        return super(Address, cls).__new__(
            cls,
            number=[number],
            street=street,
            city=city,
            state=state,
            zip_code=zip_code)

a = Address()
print(a)
Address(number=[None], street=None, city=None, state=None, zip_code=None)
a.number[0] = 1600

print(a)
Address(number=[1600], street=None, city=None, state=None, zip_code=None)

a.number.append(1700)

print(a)
Address(number=[1600, 1700], street=None, city=None, state=None, zip_code=None)

Of course, just because it’s a list, and therefore mutable, doesn’t mean you can re-assign it.  That’s when the immutability of the namedtuple asserts itself.

a.number = 1600
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
can't set attribute

 

One of the first things you should know about Python is, EVERYTHING IS AN OBJECT. That means that you can inherit from it. Boom. I just inherited from my named tuple, and now I can add items to the class to define how data is retrieved! Super nifty!

Wow.  Who cares, you say.  Big deal?  What are you, some type of wierdo?   Yes.  Yes, I am.

So, let’s say, that you have a database of addresses. And you want to get a printable mailing address for an entry? Well, you could easily apply the queried records from the database into our Address model (we’ll just use this name as a reference). Now, we have a whole list of these entries. Perhaps we’re having a party, and we want to mail invites to everyone.  This is where the whole nametuple inheritance gives you some pretty cool flexibility.

class Address(namedtuple("Address", ["number", "street", "city", "state", "zip_code"])):

    def __new__(cls, number=None, street=None, city=None, state=None, zip_code=None):
        return super(Address, cls).__new__(
            cls,
            number=number,
            street=street,
            city=city,
            state=state,
            zip_code=zip_code)
   
    def mailing_address(self):
      return ("{self.number} {self.street}\n"
              "{self.city}, {self.state} {self.zip_code}"
             ).format(**locals())

Nice and simple. Or perhaps you’re going to export your entire rolodex to csv (for some reason)?

class Address(namedtuple("Address", ["number", "street", "city", "state", "zip_code"])):

    def __new__(cls, number=None, street=None, city=None, state=None, zip_code=None):
        return super(Address, cls).__new__(
            cls,
            number=number,
            street=street,
            city=city,
            state=state,
            zip_code=zip_code)
   
    def mailing_address(self):
      return ("{self.number} {self.street}\n"
              "{self.city}, {self.state} {self.zip_code}"
             ).format(**locals())

    def to_csv(self):
        return ",".join(self._asdict().values()

 

Now you could just iterate over that list of Address entries and write out the to_csv() call!  It would likely look something like:

addresses = [all your address entries would be here]
with open("rolodex.csv", 'wb') as f:
    [f.write(a.to_csv() for a in addresses]

I’m not advocating for a replacement of traditional classes.

My opinion: Python classes should fall into one of three basic types:

  1. A class could contain data (such as our namedtuple example here)
  2. a class could provide encapsulation of action (like a database library).
  3. Or a class could provide actuation/transformation of data (kind of a mix of #1 and #2)

If you’re dealing with data which is merely going to be acted upon and never changed, then take a swing with these fancy namedtuples.  If you’re doing lots of actuation, write a normal class.   At all times, never should a good coder assume they know the best way to do something.  You’d be surprised how often when I make this assumption, some young, talented coder comes along and corrects my ego.