PEP on path module for standard library

Andrew Dalke dalke at dalkescientific.com
Fri Jul 22 06:42:50 CEST 2005


Michael Hoffman wrote:
> Having path descend from str/unicode is extremely useful since I can 
> then pass a path object to any function someone else wrote without 
> having to worry about whether they were checking for basestring. I think 
> there is a widely used pattern of accepting either a basestring[1] or a 
> file-like object as a function argument, and using isinstance() to 
> figure out which it is.

Reinhold Birkenfeld wrote:
> Where do you see that pattern? IIRC it's not in the stdlib.

Here's the first place that comes to mind for me

xml.sax.saxutils

def prepare_input_source(source, base = ""):
    """This function takes an InputSource and an optional base URL and
    returns a fully resolved InputSource object ready for reading."""

    if type(source) in _StringTypes:
        source = xmlreader.InputSource(source)
    elif hasattr(source, "read"):
        f = source
        source = xmlreader.InputSource()
        source.setByteStream(f)
        if hasattr(f, "name"):
            source.setSystemId(f.name)


and xml.dom.pulldom

def parse(stream_or_string, parser=None, bufsize=None):
    if bufsize is None:
        bufsize = default_bufsize
    if type(stream_or_string) in _StringTypes:
        stream = open(stream_or_string)
    else:
        stream = stream_or_string
    if not parser:
        parser = xml.sax.make_parser()
    return DOMEventStream(stream, parser, bufsize)

Using the power of grep

aifc.py
    def __init__(self, f):
        if type(f) == type(''):
            f = __builtin__.open(f, 'rb')
        # else, assume it is an open file object already
        self.initfp(f)

binhex.py
class HexBin:
    def __init__(self, ifp):
        if type(ifp) == type(''):
            ifp = open(ifp)

imghdr.py
        if type(file) == type(''):
            f = open(file, 'rb')
            h = f.read(32)
        else:
            location = file.tell()
            h = file.read(32)
            file.seek(location)
            f = None

mimify.py
    if type(infile) == type(''):
        ifile = open(infile)
        if type(outfile) == type('') and infile == outfile:
            import os
            d, f = os.path.split(infile)
            os.rename(infile, os.path.join(d, ',' + f))
    else:
        ifile = infile

wave.py
    def __init__(self, f):
        self._i_opened_the_file = None
        if type(f) == type(''):
            f = __builtin__.open(f, 'rb')
            self._i_opened_the_file = f
        # else, assume it is an open file object already
        self.initfp(f)


compiler/transformer.py:

        if type(file) == type(''):
            file = open(file)
        return self.parsesuite(file.read())

plat-mac/applesingle.py
    if type(input) == type(''):
        input = open(input, 'rb')
    # Should we also test for FSSpecs or FSRefs?
    header = input.read(AS_HEADER_LENGTH)

site-packages/ZODB/ExportImport.py
    if file is None: file=TemporaryFile()
    elif type(file) is StringType: file=open(file,'w+b')


site-packages/numarray/ndarray.py
        if type(file) == type(""):
            name = 1
            file = open(file, 'wb')


site-packages/kiva/imaging/GdImageFile.py
    if type(fp) == type(""):
        import __builtin__
        filename = fp
        fp = __builtin__.open(fp, "rb")
    else:
        filename = ""

site-packages/reportlab/graphics/renderPM.py
   if type(image.path) is type(''):
        im = _getImage().open(image.path).convert('RGB')
   else:
        im = image.path.convert('RGB')


site-packages/twisted/protocols/irc.py
    def __init__(self, file):
        if type(file) is types.StringType:
            self.file = open(file, 'r')

(hmm, that last one looks buggy.  It should
have a "else: self.file = file" afterwards.)


Used in the std. lib and used by many different
people.  (I excluded the Biopython libraries
in this list, btw, because I may have influenced
the use of this sort of type check.)

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list