Permalink
Browse files

Implemented using_module class method to select alternate path module

  • Loading branch information...
1 parent 54769b9 commit d36450e6f88e4e3b8e7ebf3b754b71be4ea5f7e1 Vojislav Stojkovic committed Nov 13, 2012
Showing with 26 additions and 12 deletions.
  1. +17 −6 path.py
  2. +9 −6 test_path.py
View
@@ -77,16 +77,27 @@ class path(unicode):
counterparts in os.path.
"""
- # Constructor allows specifying an alternate path module (e.g. posixpath)
- def __new__(cls, value, module=os.path):
- self = unicode.__new__(cls, value)
- self.module = module
- return self
+ # Use an alternate path module (e.g. posixpath)
+ module = os.path
+ _subclass_for_module = {}
+ @classmethod
+ def using_module(cls, module, value=None):
+ if module in cls._subclass_for_module:
+ subclass = cls._subclass_for_module[module]
+ else:
+ subclass_name = cls.__name__ + '_' + module.__name__
+ bases = (cls,)
+ ns = {'module': module}
+ subclass = type(subclass_name, bases, ns)
+ cls._subclass_for_module[module] = subclass
+ if value is None:
+ return subclass
+ return subclass(value)
# --- Special Python methods.
def __repr__(self):
- return 'path(%s)' % super(path, self).__repr__()
+ return '%s(%s)' % (type(self).__name__, super(path, self).__repr__())
# Adding a path and a string yields a path.
def __add__(self, more):
View
@@ -130,14 +130,17 @@ def testUNC(self):
self.assert_(p.splitunc() == os.path.splitunc(str(p)))
def testExplicitModule(self):
- nt_ok = path('C:\\Program Files\\Python\\Lib\\xyzzy.py', module=ntpath)
- posix_ok = path('/usr/local/python/lib/xyzzy.py', module=posixpath)
- posix_wrong = path('C:\\Program Files\\Python\\Lib\\xyzzy.py',
- module=posixpath)
- self.assertEqual(nt_ok.dirname(), 'C:\\Program Files\\Python\\Lib')
- self.assertEqual(posix_ok.dirname(), '/usr/local/python/lib')
+ nt_ok = path.using_module(ntpath, r'foo\bar\baz')
+ posix_ok = path.using_module(posixpath, r'foo/bar/baz')
+ posix_wrong = path.using_module(posixpath, r'foo\bar\baz')
+
+ self.assertEqual(nt_ok.dirname(), r'foo\bar')
+ self.assertEqual(posix_ok.dirname(), r'foo/bar')
self.assertEqual(posix_wrong.dirname(), '')
+ self.assertEqual(nt_ok / 'quux', r'foo\bar\baz\quux')
+ self.assertEqual(posix_ok / 'quux', r'foo/bar/baz/quux')
+
class TempDirTestCase(unittest.TestCase):
def setUp(self):
# Create a temporary directory.

0 comments on commit d36450e

Please sign in to comment.