[Tutor] Question on classes/instances

mailing list ml.cyresse at gmail.com
Wed Aug 10 09:51:08 CEST 2005

Hi Negroup, 

First off, you may want to use os.path.join to create paths - 

path = 'categories/%s' % self.name

could be - 

path = os.path.join(categories, self.name)

This will ensure minimum hassle if you ever want to use this across
multiple OS.
Also, it looks a little tidier, and IMAO, tidier code is easier to maintain.

As for what you're wanting to do with the list comprehension, once
again I'd use os.path.join, but otherwise your comprehension looks

On 8/10/05, Negroup - <negroup at gmail.com> wrote:
> Hi, Sorry for the subject a bit generic. This question comes from a
> simple program I'm doing. I could have a working solution, but
> considering my inexperience, I'm just asking if my approach is
> acceptable.
> This is a simple class to manage (actually to create and save)
> categories of things. Categories are represented as directories, while
> descriptions of categories are stored inside a file called
> .description inside the category directory. Look at the code..
> class Category:
>         def __init__(self, name=None, description=None):
>                 self.description = description
>                 if name:
>                         self.name = name
>                 else:
>                         return 'Value expected'
>         def save(self):
>                 from os import access, F_OK, mkdir
>                 path = 'categories/%s' % self.name
>                 if access(path, F_OK):
>                         return 'Category already present'
>                 else:
>                         mkdir(path)
>                         if self.description:
>                                 f = file('%s/.description' % path, 'w')
>                                 f.write(self.description)
>                                 f.close()
> and this is a simple function to get a list of categories, inside the
> same module of Category:
> def get_categories():
>         from os import listdir
>         return listdir('categories')
> I would instead, that get_categories returns a list of instances of
> Category class instead of a list of strings, so that I can handle
> categories with proper APIs. I found this way:
> def get_categories():
>         from os import listdir
>         # return listdir('categories')
>         path = 'categories'
>         categories = [Category(name, file('%s/%s/.description' %
> (path, name)).read()) for name in listdir('categories')]
>         return categories
> Is it a good way to solve the problem? Otherwise, I would be glad if
> you could propose better solutions.
> Thanks for any clarification.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list