Pythonic Parsing Programs
The Cover Your Bases Answer
The simplest solution to parsing is to parse a file-like object. Again for the newbies, I say file-like because Python has duck typing. According to Wikipedia this term, duck typing, comes from the saying of an old poet—James Whitcomb Riley:
When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.
But I prefer the scene in Monty Python and the Holy Grail, when wise Bedemir uses his powers of logic to determine whether witches are made of wood and therefore flammable—fit to be burned:
BEDEMIR: So, how do we tell whether she is made of wood? VILLAGER #1: Build a bridge out of her. ... BEDEMIR: Aah, but can you not also build bridges out of stone? VILLAGER #2: Oh, yeah. BEDEMIR: Does wood sink in water? VILLAGER #1: No, no. VILLAGER #2: It floats! It floats! BEDEMIR: What also floats in water? VILLAGER #1: Bread! VILLAGER #2: Apples! VILLAGER #3: Very small rocks! VILLAGER #1: Cider! VILLAGER #2: Great gravy! VILLAGER #1: Cherries! VILLAGER #2: Mud! VILLAGER #3: Churches -- churches! VILLAGER #2: Lead -- lead! ARTHUR: A duck. CROWD: Oooh. BEDEMIR: Exactly! So, logically..., VILLAGER #1: If... she.. weighs the same as a duck, she's made of wood. BEDEMIR: And therefore--? VILLAGER #1: A witch!
(Courtesy of sacred-texts.com/neu/mphg/mphg.htm)
We can apply the same
principle—duck typing—to file objects. If an object behaves like
a file—has a
method—then it is a file. By having this interface we can easily
deal with file-like objects, but also string data, and filenames as
will be illustrated.
Implementing the Interface
Another interesting note from
the table above is that most of the parsing mechanisms are not tied
to a class. Most are functions that create an object, populate it
from data within the file and return the object (
being the exception as it has no function, though the
module has both a
function and a
method on the
class). In addition isolating parsing from the data adheres to the
Single Responsibility Principle.
The author’s opinion is that
an overloaded function or method (such as
which accepts both files and filenames, or
which accepts both strings or files) is a violation of “Explicit
is better than implicit” and “In the face of ambiguity, refuse
the temptation to guess”. These methods are not taking advantage
of duck typing, but magic typing, going beyond Postel’s
Law. The Python language makes a hard distinction about the
difference between an Iterable and an Iterator. A
similar comparison could be made between a filename, and a file
object. One is a duck and the other is a duck factory.
A Simple Example
The example below parses the
contents of the Unix
file and stores the result in a list within the
from collections import namedtuple User = namedtuple('User', 'name, pw, id, gid, groups, home, shell') class Passwd(object): def __init__(self): self.users =  def parse(fp): pw = Passwd() for line in fp: data = line.strip().split(':') pw.users.append(User(*data)) return pw
A couple of notes regarding the implementation:
parsefunction populates a
Passwdobject has one responsibility, knowing about the users. It is not responsible for parsing
If a user wanted to create a
object from a filename—
# from filename with open('/etc/passwd') as fin: pw = parse(fin)
function nor the
object needs to worry about opening or closing the file.
If the data from the file was
already in memory, utilizing the built-in module
enables parsing from that end:
# from string from StringIO import StringIO as sio fin = sio('''pulse:x:113:121:PulseAudio daemon,,,:/var/run/pulse:/bin/false\nsaned:x:114:123::/home/saned:/bin/false''') pw = parse(fin)
Advantages of File-interfaces
Hopefully this long-winded post has provided you some insight into parsing files in Python. Prior art is found in the standard library and 3rd party modules. If you want to be fancy and all accommodating, you can, but in reality you are probably just adding unnecessary complexity.
To review a parsing method that relies only on a file interface is:
- accepts generators, iterators that are potentially very long, in
addition to files, sockets, and
- Easier to manage - you don’t want to be in the business of handling and closing people’s files
- Usable for users with a filename
- Usable for users with data from a file
Go forth and parse!
Matt Harrison (@__mharrison__) is a Python developer at Fusion-io where he helps build data analysis tools.
Fast/Flexible Linux OS Recovery
On Demand Now
In this live one-hour webinar, learn how to enhance your existing backup strategies for complete disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible full-system recovery solution for UNIX and Linux systems.
Join Linux Journal's Shawn Powers and David Huffman, President/CEO, Storix, Inc.
Free to Linux Journal readers.Register Now!
|CentOS 6.8 Released||May 27, 2016|
|Secure Desktops with Qubes: Introduction||May 27, 2016|
|Chris Birchall's Re-Engineering Legacy Software (Manning Publications)||May 26, 2016|
|ServersCheck's Thermal Imaging Camera Sensor||May 25, 2016|
|Petros Koutoupis' RapidDisk||May 24, 2016|
|The Italian Army Switches to LibreOffice||May 23, 2016|
- Download "Linux Management with Red Hat Satellite: Measuring Business Impact and ROI"
- Secure Desktops with Qubes: Introduction
- Chris Birchall's Re-Engineering Legacy Software (Manning Publications)
- The Italian Army Switches to LibreOffice
- Linux Mint 18
- Petros Koutoupis' RapidDisk
- ServersCheck's Thermal Imaging Camera Sensor
- CentOS 6.8 Released
- Oracle vs. Google: Round 2
- The FBI and the Mozilla Foundation Lock Horns over Known Security Hole
Until recently, IBM’s Power Platform was looked upon as being the system that hosted IBM’s flavor of UNIX and proprietary operating system called IBM i. These servers often are found in medium-size businesses running ERP, CRM and financials for on-premise customers. By enabling the Power platform to run the Linux OS, IBM now has positioned Power to be the platform of choice for those already running Linux that are facing scalability issues, especially customers looking at analytics, big data or cloud computing.
￼Running Linux on IBM’s Power hardware offers some obvious benefits, including improved processing speed and memory bandwidth, inherent security, and simpler deployment and management. But if you look beyond the impressive architecture, you’ll also find an open ecosystem that has given rise to a strong, innovative community, as well as an inventory of system and network management applications that really help leverage the benefits offered by running Linux on Power.Get the Guide