TweetFollow Us on Twitter

Mac in the Shell: Learning Python on the Mac: Functions

Volume Number: 25 (2009)
Issue Number: 02
Column Tag: Mac in the Shell

Mac in the Shell: Learning Python on the Mac: Functions

Modularizing and simplifying your code

by Edward Marczak

Introduction

We've been learning Python on the Mac and have so far covered the basics. We need to introduce a little more foundation this month. Functions-in any language-allow the author to create reusable blocks of code. This is important from a few perspectives: code reuse, the ability to refactor easily and debugging. Functions lead to building libraries, both of which are critical concepts to becoming an effective Python programmer and part of an essential foundation for creating an OS X utility or application.

Jumping In

Let's get started. Like variables, functions don't need to be defined before use. Need a function? Just define it. Similarly, functions may be defined anywhere in the source file, and in any order. Since a function defines a code block, the rules of indentation apply: choose spaces or tabs (trying to be consistent with the style you use in the rest of your code) and indent the entire function. Here's an example:

#!/usr/bin/env python
def SayHello():
  print "Hello"
SayHello()

This short program simply prints "Hello." Not too exciting, and it really could have been accomplished in one line. But it does help illustrate the basics: A function is created by using the def keyword, supplying a function name-unique to this source file-followed by parenthesis and terminated with a colon character. The lines following need to be consistently indented; the first line that lowers the indentation level ends the code block that comprises the function. The previous example is really as simple as it can get. Let's look at something a little more useful: a function definition that prints the square of a number passed into it.

def Square(number):
  print number,"squared is",number ** 2

Once defined, this function can be called as many times as you have need, individually, or in a loop:

for i in range(1,6):
  Square(i)

This will produce:

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

However, there's a problem with this function. What if we only want to compute the value of a square and keep it for later, rather than print it out? That's where the return keyword comes in. return sends a value back to the caller. So, our Square() function could be rewritten like this:

def Square(number):
  return number ** 2

and would need to be called like this:

x = Square(44)

or, used in-line like this:

print "The square of 78 is %d." % (Square(78))

How, you may ask, is this any better than the first version? The answer is two-fold: first, you'll typically use functions to build up more complex sections of code. The times that you have a one-line or very simple function usually involve creating a function for readability purposes. Second, by returning a value, you can store it for later, rather than display it or otherwise use it immediately.

Libraries

Let's build up a small set of useful functions, and learn some new Python skills along the way. We'll improve and expand on these functions as time goes on. Also, for now, some of this is a little more advanced than we've covered, so, just trust me for now, and this will all be covered in future columns. Here's the beginning of the code, along with the first function, and yes, it's one that you just need to trust me on for now:

Listing 1a - Wrapper for subprocess

#!/usr/bin/env python
import subprocess
def RunProc(command,env_vars=None):
  """Wrap subprocess into something reasonable.
  Args:
    command: List containing command and arguments
    env_vars: Shell environment variables that should be present for execution
  Returns:
    stdout: output of the command
  """
  proc = subprocess.Popen(command, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          env=env_vars)
  (stdout, stderr) = proc.communicate()
  return stdout

Note that I'm also shooting for good habits, here: commented code, readable variable names and consistent, clean code style (space after comma, spaces around equal signs, and so on). The above code wraps the subprocess library calls to make it easier to run a child process. It's less than perfect right now, but we'll correct that in due time (not this column, however). Let's get on to a useful OS X-related function.

Listing 1b - GetLocalUsers function.

def GetLocalUsers():
  """Fills a dictionary with all system users
     Args:
       None
     Returns:
       Dictionary, filled with uid/username pairs       
  """
  command = ['/usr/bin/dscl','.','list','/Users']
  output = RunProc(command)
  userList = output.split('\n')
  userDict = {}
  for userName in userList:
    if userName is not '':
      command = ['dscl','.','read','/Users/'+userName,'uid']
      output = RunProc(command)
      uidLocation = output.split(':')
      uid = uidLocation[2].strip()
      userDict[uid] = userName
  return userDict

The GetSystemUsers() function will fill a dictionary with uid (the key) and the short name that it is assigned to. It takes no parameters, and can be called like this:

userDict = GetLocalUsers()

To extract information, simply request the value using the uid as the key:

print "User ID 74 is %s." % (userDict[74])

(It's _mysql, if you're curious and not typing in code while reading this).

There are some new concepts in Listing 1b. The split string function (line 10 of listing 1b), creates a list, each element created by the boundary of the character argument. For example, the string 'This is a string' when split using a space (string.split(' ')) becomes the following list:

['This', 'is', 'a', 'string']

Any character can be used to provide the boundary marker.

This function is nice, but could certainly be improved. What if we only wanted standard users, and not all of the system users? That's where function arguments come in. Like passing arguments into a command line application, functions can accept arguments, too. Alter our function to do so:

def GetLocalUsers(incSystemUsers):

This will allow us to pass a value into the function. Great, but we need to do something with it. Let's expect this to be a Boolean True or False: if True, include the system accounts, if False, do not. (I'm classifying accounts based on uid-only system accounts have a uid of less than 500). Update the code portion of the function to utilize this new variable (the first ten lines are the same as before-I just wanted to give some context):

command = ['/usr/bin/dscl','.','list','/Users']
  output = RunProc(command)
  userList = output.split('\n')
  userDict = {}
  for userName in userList:
    if userName is not '':
      command = ['dscl','.','read','/Users/'+userName,'uid']
      output = RunProc(command)
      uidLocation = output.split(':')
      uid = uidLocation[2].strip()
      if incSystemUsers:
        userDict[int(uid)] = userName
      else:
        if int(uid) > 499:
          userDict[int(uid)] = userName
  return userDict

We use a simple if/else statement to determine if the user should be included in the dictionary that is returned. We should update our comments about this in the function, too.

Now, we have to include a value when we call the function. Like this:

userDict = GetLocalUsers(False)

This is an improvement to this function. Frankly, though, more often than not, you probably do only want standard users.

Default Arguments

Python functions understand default arguments. Change the function definition to read:

def GetLocalUsers(incSystemUsers=False):

Now, if we don't tell GetLocalUsers how to behave, by not including an argument, it will assign False and continue on. So now, we can once again call the function with no arguments:

userDict = GetLocalUsers()

This is equivalent to calling GetLocalUsers(False). We really only have to pass in a value of True if we wish to override the default behavior. It is possible to combine default and non-default arguments in a single function definition. For example:

def Mount(path, method="afp", mount_point="/Volumes", shadow=False):

This fictional function, Mount(), has four parameters, only one which you are required to provide when called: path. The remainder use the defaults provided. Therefore, this function can be called in the following ways:

Mount("serv.example.com/share")
Mount("serv.example.com/share", "nfs")
Mount("serv.example.com/share","/tmp/mnt")

These examples use simple positional arguments: you need to know the position of the argument and pass in the values in the correct sequence. When creating a function definition, default arguments should be grouped at the end of the list. This allows them to be omitted.

Python also supports specifying the argument that is being passed in. This allows us to call the function like this:

Mount("serv.example.com/data.dmg","http",shadow=True)

Note that we're passing in the value for shadow in the third position, where we would typically specify mount_point. This is an excellent way to pass parameters into a function, as it makes it exceptionally obvious what is taking place. Which of the following code is easier to read?

ConvertFile('rawdata.txt','sales.csv','csv',True)

or:

ConvertFile(infile='rawdata.txt', outfile='sales.csv',
            format='csv',Totals=True)

Hmmmm? Using named arguments is a good habit to get into.

Variable Length Argument Lists

As a final discourse in functions, what if you don't know how many parameters a function may receive, or, has a number that may change from call to call? Python supports variable length argument lists. Two decorators designate how these values are received. If a single asterisk is used, the values are received into a tuple, receiving any excess positional parameters, defaulting to an empty tuple. If a double asterisk is used, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. Let's see how this works. Here's a short, sample function that accepts any number of arguments:

def SomeFunction(*args):
  print args

It can be called like this

SomeFunction(24, 'blah', 'cold', 88, [22,34,66],'starch')

Note that arguments do not need to be of the same type. Pass in strings, integers, or even lists and dictionaries. The same goes for the double-asterisk decorator, with one exception: since you're creating a dictionary, you need to pass the key and the value.

Changing the function definition to:

def SomeFunction(**args):

allows the function to be called like this:

SomeFunction(number=24, some_string='blah',
             a_list = [22,34,66], string2='starch')

In our case, this will cause the function to output:

{'a_list': [22, 34, 66], 'some_string': 'blah', 'string2': 'starch', 'number': 24}

Finally, realize that you can mix variable arguments along with standard and named arguments. In the examples used above, since we only specified a variable argument, passing in an argument is completely optional.

In Conclusion

I was hoping to rip through functions and talk about modules in this column, but then I started writing, and realized the scope of the topic. I want to do justice to both functions and modules, as they're both critical foundational subjects. Next month, we'll build on the functions introduced this month and dig into modules.

Media of the month: I'm not going to call out any one particular 'thing,' but will give this directive: Find something new. If you've only been exposed to the Mac, go pick up a book (or find a web page) about Windows, FreeBSD or Linux. Compare to OS X. If you're a MySQL person, download and explore PostgreSQL, or learn the command-line interface to SQLite. You get the idea-stretch your boundaries.


Ed Marczak is the Executive Editor of MacTech Magazine. He lives in New York with his wife, two daughters and various pets. He has been involved with technology since Atari sucked him in, and has followed Apple since the Apple I days. He spends his days on the Mac team at Google, and free time with his family and/or playing music. Ed is the author of the Apple Training Series book, "Advanced System Administration v10.5," and has written for MacTech since 2004.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.