Coding Snippets in Sublime Text 3


This is my coup de grĂ¢ce into coding snippets, which completes this mini-series (for now, at least). I wanted to do a tiny bit more Python, so began investigating which IDE to look into next:

Stackoverflow – Which Python IDE
Best Python IDE

The Eric IDE project caught my eye initially, and definitely looks like an incredibly interesting prospect. However, I find myself inexorably drawn to try out Sublime Text 3, only because I seem to have crossed paths with a fair few people using it. If anyone is interested in checking out the Eric IDE I’ve included a set of links below for further investigation:


Eric IDE Prerequisites Listed


Eric IDE Sourceforge Download

For now, let’s focus our efforts on Sublime Text 3…

Sublime Text 3

To get started, you can navigate to the Sublime Text 3 downloads page and grab the appropriate package for your OS. After reading up, there appears to be a project accessible on GitHub called Anaconda which ‘turns Sublime Text 3 into a full featured Python development IDE’. In order to utilise this functionality, you’ll first need (well, this is the easiest way from the options listed) Package Control, which is essentially a Package Manager for Sublime.

Here are a few basic notes for getting Anaconda setup with Sublime Text 3:

Image showing setup notes on installing Anaconda for Sublime Text 3.

Notes on setting up Anaconda.

In addition, this blog post looks like a strong starting point for investigation into setting up Sublime Text 3 for Python development:

Sublime Text as Python IDE

Just to prove the point, here is Anaconda showing its presence via a context menu in the IDE:

Image showing Anaconda in use within Sublime Text 3.

Anaconda in use.

I’ve taken a few additional steps here. For starters, I wanted to run my code directly within Sublime, which requires configuring the correct Build System, as follows:

Image showing how to setup the Python Build System in Sublime Text 3.

Setting Python Build System.

After performing the Build System configuration you can decide on whether you want to use syntax-only style checks or physically run your code on build (‘Tools > Build With‘):

Image showing the Sublime Build With options.

Sublime Build With.

So, as far as setup goes, that covers it. On to snippets…

Snippets in Sublime

To the main event, how do you create snippets in Sublime Text 3?

Creating the snippet itself couldn’t be simpler, just navigate to ‘Tools > Developer > New Snippet…’ and you’ll be presented with the following:

Image showing the default setup for a snippet in Sublime Text 3.

Snippet Default Setup.

The idea behind creating a snippet is conceptually similar to how you would create them for use within Visual Studio. With the content element (again, we are dealing with an XML format) you’ll find a CDATA definition; snippet code goes between the square brackets. Placeholders can be defined within the code snippet using the $ symbol followed by an incremental number, starting at one (depending on how many placeholders you have of course). The tabTrigger element defines the shortcut that needs to be typed into the IDE code window to bring the snippet into scope. Additional metadata can also be provided to specify the scope of a certain code snippet (e.g. just Python) and a friendly, textual description (stored in the aptly named description element). It sticks pretty close to other snippet creation conventions I’ve seen elsewhere, it’s certainly a cinch to pick up. Here is my first stab at a completed snippet, with comments left in line for reference:

def saySomething(name):
	print("$1", name)
	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
	<!-- Optional: Set a scope to limit where the snippet will trigger -->
    <description>Say Something Snippet</description>

Snippet files are saved using the .sublime-snippet extension and for the purposes of a quick demonstration I’ve saved mine in the default location of ‘C drive > Users > MY_USER > AppData > Roaming > Sublime Text 3 > Packages > User’, this would require a bit more thought if you were creating more snippets (if you have organisational OCD such as I do). Initial reading does suggest that they should be saved under the ‘User’ directory regardless.

Within Sublime you will then need to save a file with a .py extension, ready to actually construct some Python code! The next two images show the newly created ‘say-something.sublime-snippet’ being brought into scope by keying in ‘ss’ and then hitting tab. As before, placeholders can be tabbed through for fast snippet completion:

Image showing the snippet before use.

Snippet before use.

Image showing the snippet after use.

Snippet after use.

Placeholder values, within snippets, can accept defaults by using the following convention:

def saySomething(name):
	print("${1:Hello}", name)
	print (${2:5} + ${3:5})
	<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
	<!-- Optional: Set a scope to limit where the snippet will trigger -->
    <description>Say Something Snippet</description>

That’s it, mini-series completed! As mentioned before I have a gargantuan mound of topics to cover, some just bubbling over in my mind and others sitting as draft posts ready for completion, so there is plenty of content on its way. Until the next time, have a great weekend!

Fighting The Python

A random spin-off for today, but thankfully a much, much shorter post for anyone who bled from their eyeballs when reading my last post! The focus for today is Python; what you’ll read about here is my initial insights. Looking at the clock, this equates to about just under an hour of reading and learning; so don’t expect to see anything too advanced or perhaps even technically perfect (sound the ‘possibly wrong on the internet alarms now please, if you will’).

What is Python?

Everyone, I’m sure, just wants to say it’s a big-ass snake; and of course it is! Programming language wise however, Python is designed to be a very easy to read, terse, dynamically typed language which allows for rapid development. I’m familiar with it from a procedural/scripting sense but Python does support an object-orientated paradigm (something I haven’t looked into as of the time of writing).

So, some re-iteration here but bear with me; the key takeaway points are:

  • Dynamically typed.
  • Standard files use the .py extension.
  • Whitespace sensitive (uses indentation, like F#, to control flow).
  • Similar ethos to F#, easy to read and terse.
  • Allows for rapid development cycles.
  • Information that I’ve gathered so far touts this as a great starter programming language.


You’ve got a few options for getting started. There appears to be multiple online interpreters where you can go and code in Python without downloading any resources:

Python Online Interpreters (Google)

Codecademy also has a course on offer which you can review, which I used as a primer for writing this post (the first few sections at least). The site also has, based on an initial nosey around, some solid looking documentation along with downloads for the latest versions of Python:

Codecademy Python Course (Downloads/Documentation)

As I’m a Windows/Visual Studio kind of guy (something I should probably step away from occasionally to properly fly the ‘Random Coding Journeys’ banner in future!) the examples you’ll see next are formed using the Python Visual Studio templates (for creating a Python Command Line Application).

On debugging the application for the first time you will be prompted to download an interpreter; CPython is the option I selected, but there were various options to peruse so if you try this yourself have a good root around. After one, simple, installation I was away and debugging.

Python VS Interpreter.

Python VS Interpreter.

Python Command Line.

Python Command Line.

So, without further ado, let’s get to some coding!

The Basics

As Python is dynamically typed, as stated before, to get up and running you simply declare a variable name, followed by the equals (‘=’) operator, then a value to start working with data as follows:

language = "Python"

Python then uses a type inference system (much akin to F# again) as you would expect.

Single-line comments are defined using #, with multi-line comments requiring content to be wrapped inside triple double quotes:

#A single-line comment
language = "Python"

A multi-line comment
intNumber = 10

A super-fast blast through the documentation on the site and codecademy illustrates that the +, -, *, / and % operators all function as you would expect. The ** syntactic rule is used for exponential operations. The input/print functions can be used read in/output information to the console respectively. The def keyword is used to define functions (parameters can be supplied using parentheses). In a slight syntactic twist to what I’m used to, colons are used at the end of if, elif, else, try and except statements before any newlines/indentation:

#Classic Hello World - Just in case you really, really wanted to see it!
print ("Hello World")

print (5 + 5)       #Addition (10)
print (10 - 5)      #Subtraction (5)
print (5 * 5)       #Multiplication (25)
print (10 / 5)      #Division (2.0)
print (10 % 4)      #Modulo/Modulus (2)
print (10 ** 2)     #Exponential (100) 

#Get a number input from the user
intValue = input("Enter any number: ")

#No checking on ints here - Completely unsafe cast (gulp!)

#Notice the use of colons here. Stardard ==, <, >, etc operators are fine. Can also define an 'in' statement (if, elif and else supported)
if int(intValue) <= 8:
    print("intValue less than or equal to 9")
elif int(intValue) in (9, 10, 11):
    print("intValue in 9, 10, 11")
    print("intValue is greater than or equal to 12")

#Retrieve another input from the user
intValueTwo = input("Enter another number: ")

#Illustrate some other decision making constructs. 'or' and 'and' are substituted (when compared to C#) for && and ||
if int(intValueTwo) == 0 or int(intValueTwo) == 1:
    print("intValueTwo is 0 or 1")
elif int(intValue) > 10 and int(intValueTwo) == 2:
    print("intValue is greater than 10 and intValueTwo is equal to 2")
    print("Some other condition")

Sample Application

To finish this post off here’s an incredibly rudimentary code sample that’s designed to calculate the hypotenuse of a right-angled triangle (with the lengths of the two shorter sides of the triangle provided):

A basic example of using python: Pythagoras' Theorem (and a multi-line comment!)
#Import math helpers as required
from math import sqrt, floor

#Create a function up front to parse the input to an integer (that's all I'm allowing for now). Basically to demonstrate very simple error handling
def intTryParse(value):
        return True
    except ValueError:
        print("Could not convert input value to an integer.")
        print("Unknown error occurred whilst processing the input.")
    return False

#Create a function to calculate the third side (assuming we have a right angled triangle!) of a triangle based on the two side lengths provided
def calculateTrianglesThirdSide(firstSideLen, secondSideLen):
    return floor(sqrt((firstSideLen ** 2) + (secondSideLen ** 2))) #Use floor to round, ok with the slight inaccuracy (I just wanted to use more helper functions)

#print to the console - We're here and we are alive!
print ("Pythagoras Example (calculate Hypotenuse)\r\n=========================\r\n")

#Get string based input from the user for the first two sides of the triangle
sideOne = input("How long is the first shortest side of the triangle: ")
SideTwo = input("How long is the second shortest side of the triangle: ")

#Only proceed if both values provided are integers
if intTryParse(sideOne) and intTryParse(SideTwo):
    #Both values provided for the first two sides parse correctly (strip space from the values)
    sideOneInt = int(sideOne.strip())
    sideTwoInt = int(SideTwo.strip())

    #Calculate the remaining side using the values provided (output to the console)
    print (calculateTrianglesThirdSide(sideOneInt, sideTwoInt))
    #Invalid input - Cease processing
    print ("Processing halted due to invalid input.")

Thanks for reading, until the next time…