The Pythonic Way

Software development is a very fast-paced domain; new ideas & technologies come and go really quickly. Developers usually need to go to the extra mile to be able to keep up with all these changes. Personally, I try to learn a new language every 2-3 years to keep myself in shape and this time it was Python that I chose to add to my arsenal.

There are various reasons for picking Python; the rise of Machine Learning and AI is probably the most dominant one. Being able to work outside of any confined programming environment was also a plus. I have spent the last 6 years in iOS development and writing code that only works on a mobile device did bring some limitations to the table. Finally, Python's dynamically typed structure seemed like a good challenge since I had always worked with statically typed languages such as Java, Objective-C, AspectJ, ABAP and Swift. Types are checked at compile-time; so a developer feels safe knowing that not much can go wrong at run-time with regards to variable types. Objective-C provides a little bit of flexibility with its dynamic message passing architecture but not enough to make it a fully dynamically typed language.

Here are my top 5 Python features/syntax that I have enjoyed over the last year (in no specific order);

1) List Comprehension
Very useful syntactic sugar making "for loops" more concise. Very similar to the map(), reduce() and filter() methods borrowed from the functional world.

# Go through the array of forecast objects and create an array of temperature values
temperatureValues = [forecast.temperature for forecast in forecasts]

# Go through the array of forecast objects and create a dictionary of {location:temperature}
locationTemperatureDictionary = {forecast.location: forecast.temperature for forecast in forecasts}

# Go through the array of forecast objects and create an array of locations where the temperature is scorching hot (above 35 celsius)
reallyHotLocations = [forecast.location for forecast in forecasts if forecast.temperature > 35]

2) Object-Oriented and Procedural Mix
I have noticed that OO and procedural mix in rather nicely in Python. The modules act as clean interfaces to the outside world, while OO does what it does best: encapsulation.

from library.cloud.CloudDataTransformer import CloudDataTransformer
from library.cloud.CloudStorageHandler import CloudStorageHandler as Handler

storageHandler = Handler()

def uploadBuluttanReadingListToCloud(forRun):

    print("Will now upload data to Buluttan-runs.")

    historicalRunData = CloudDataTransformer().historicalRunFromReadingList(forRun.buluttanReadingList)
    __uploadBuluttanRun(historicalRunData, forRun)

def uploadRawData(rawData, forRun):

    storageHandler.uploadRunFile(rawData, forRun.targetedBaseDateDayID)

3) Iterator
It is very simple to create an iterator in Python, almost zero boiler-plate code!

class ValidHours:

    def __init__(self):
        self.currentIndex = -1
        self.dataToServe = ['18', '12', '06', '00']

    def __iter__(self):
        return self

    def __next__(self):
        self.currentIndex += 1

        if self.currentIndex < len(self.dataToServe):
            return self.dataToServe[self.currentIndex]
        else:
            raise StopIteration()

4) Array Slicing
Playing with arrays & strings is really a breeze.

# File name of absolute path via the -1 indexing
justFilename = fileAbsolutePath.split("/")[-1]

# Print out the names list skipping the first two names
for name in names[2:]:
    print(name)

5) Indentation over curly braces
It is usually hard for developers to agree upon coding conventions in a project. By making indentation part of the syntax, Python at least makes sure that indentation is common among all the developers in the world! Also, if you try to have your methods less than 20 lines, then you see that you really don't need the curly braces.

All the examples are taken from the weather forecast engine that I have created last year. The engine is named 'Buluttan' and there is also a mobile app consuming the data provided by this engine. The app can be downloaded from the App Store and Play Store.

Overall, I did enjoy Python a lot and I am hoping I will get better at it! Some closing remarks: It doesn't make sense to become a fan of any language since languages are just tools that enable you to do what you have in mind. Learning new languages do open up some new pathways!

Guven








Comments

Popular Posts