How can I tell if a python variable is a string or a list?

后端 未结 8 1811
孤独总比滥情好
孤独总比滥情好 2020-12-02 19:45

I have a routine that takes a list of strings as a parameter, but I\'d like to support passing in a single string and converting it to a list of one string. For example:

8条回答
  •  被撕碎了的回忆
    2020-12-02 20:29

    I would say the most Python'y way is to make the user always pass a list, even if there is only one item in it. It makes it really obvious func() can take a list of files

    def func(files):
        for cur_file in files:
            blah(cur_file)
    
    func(['file1'])
    

    As Dave suggested, you could use the func(*files) syntax, but I never liked this feature, and it seems more explicit ("explicit is better than implicit") to simply require a list. It's also turning your special-case (calling func with a single file) into the default case, because now you have to use extra syntax to call func with a list..

    If you do want to make a special-case for an argument being a string, use the isinstance() builtin, and compare to basestring (which both str() and unicode() are derived from) for example:

    def func(files):
        if isinstance(files, basestring):
            doSomethingWithASingleFile(files)
        else:
            for f in files:
                doSomethingWithFile(f)
    

    Really, I suggest simply requiring a list, even with only one file (after all, it only requires two extra characters!)

提交回复
热议问题