Hacker Newsnew | comments | show | ask | jobs | submitlogin

You can do type-class tricks with it if you want...

    class Username(unicode): pass
    class Directory(unicode): pass

    def updateUserHomeDir(name, dirname):
        assert isinstance(name, Username)
        assert isinstance(dirname, Directory)

        update_etc_passwd(name=name, dirname=dirname)
or whatever. This only really starts to become useful when you start adding sanity checks into the classes:

    class Directory(unicode):
        def __init__(*vargs, **kwargs):
            super(Directory, self).__init__(*vargs, **kwargs)
            if not os.path.is_dir(self):
                if not os.path.exists(self):
                    make_dirs(self)

just a bit cleverer in reality. You then move all the directory-path sanity checks into there. You can also subclass further for `class ValidHomeDir(Directory)`, etc.

The benefit of this is that you don't have to run your sanity checks more than once, you can pass the values around as much as you need and be sure that they have been initiated correctly. Use of your functions becomes at worst:

    updateUserHomeDir(Username('dan'), Directory('/home/daniel'))
which isn't so bad, really.

And it's fine to be optimised out, as the code paths are what are being checked here, not the user data. :-)

I don't know how "pythonic" the idea is, but it does seem reasonably elegant to me, and solves some of the problems of python's otherwise fun duck-typing.




Applications are open for YC Summer 2015

Guidelines | FAQ | Support | Lists | Bookmarklet | DMCA | Y Combinator | Apply | Contact

Search: