3
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

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)]
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.