HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Creating objects from parsed file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fileobjectscreatingfromparsed

Problem

I'm newbie in Python but I want to know some tricks to make my code look cute. I know that syntax of Python allows to do this, but I don't know how.
Suppose I have file with lines of format "x y z" and I want to parse it and make some objects. Now code looks like this:

class Point(object):
    def __init__(self, x, y, z):
        self.x = x;
        self.y = y;
        self.z = z;

...

def load_file(file_path):
    points = [];
    with open(file_path, "r") as input_file:
        for line in input_file:
            str_point = line.split();
            x = float(str_point[0]);
            y = float(str_point[1]);
            z = float(str_point[2]);
            points.append(Point(x, y, z));
    return points;


Is there any way to make this code simpler?

Solution

Instead of parsing x, y, z one by one, you can use a list comprehension,
and pass the whole thing directly to the the constructor of Point using * like this:

def load_file(file_path):
    objects = []
    with open(file_path) as input_file:
        for line in input_file:
            obj = Point(*[float(x) for x in line.split()])
            objects.append(obj)
    return objects


I dropped the "r" in open(..., "r"), as that's the default anyway.
Even more importantly,
; are not required to end statements in Python,
and they are just noise in the posted code.

It would be even cuter to use a generator pattern instead:

def load_file(file_path):
    with open(file_path) as input_file:
        for line in input_file:
            yield Point(*[float(x) for x in line.split()])


You could iterate over this to do something with the objects, for example:

for obj in load_file(file_path):
    # do something ...


Or you could load all into a list using a list comprehension:

objects = [x for x in load_file(file_path)]

Code Snippets

def load_file(file_path):
    objects = []
    with open(file_path) as input_file:
        for line in input_file:
            obj = Point(*[float(x) for x in line.split()])
            objects.append(obj)
    return objects
def load_file(file_path):
    with open(file_path) as input_file:
        for line in input_file:
            yield Point(*[float(x) for x in line.split()])
for obj in load_file(file_path):
    # do something ...
objects = [x for x in load_file(file_path)]

Context

StackExchange Code Review Q#67298, answer score: 2

Revisions (0)

No revisions yet.