2

I often see Python code that accepts a variety of inputs...

file names

s = Something("/Users/me/my_file.txt")

file paths

s = Something("my_file.txt")

or file objects

f = open("my_file.txt", "r")
s = Something(f)

Is there a convention to this? As a lot of people mentioned, it depends on what something() is. What situations are better suited to file names vs. file objects?

I wonder if this SO post gives the best answer.

2
  • It depends on what something() is doing, whether it is checking the type of argument being passed or not. Commented Aug 29, 2012 at 19:26
  • 1
    Almost everywhere, a bare file name "foo" is treated identically to the more explicit path "./foo", so there's really only two cases: paths and objects. Commented Aug 29, 2012 at 19:47

3 Answers 3

4

The json has two methods for loading data: json.load which takes a file-like object, and json.loads which takes a string:

>>> json.load(open("my_file.json"))
[1, 2]
>>> json.loads("[1, 2]")
[1, 2]

The pickle module has a similar interface (one accepts a file-object, and a second which takes a string)

Essentially, your API primarily uses file-objects, and you provide a convenience method which wraps the supplied-string in a StringIO object. Might look something like this:

class Parser(object):
    def __init__(self, fh):
        # Can do things like:
        first_line = fh.readline()
        fh.seek(0)
        all_content = fh.read()


def parse(fh):
    return Parser(fh)


def parse_str(inputstring):
    fh = StringIO.StringIO(inputstring)
    return Parser(fh)
Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps the conventionn is to design two interfaces and let the user decide what type the are passing in, calling the appropriate method, rather than give them one interface and check the type behind the scenes?
2

That all depends on the interface of Something(). I don't know if it's fair to say that there's one strict convention for this. The nice part about duck typing is that you don't need to know the type of arguments to a function, only certain ways in which the arguments behave.

1 Comment

Good question, I guess I'm thinking abstractly at the moment.
0

It don't think there is any applicable convention. It totally depends on what your program wants to achieve.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.