leonard vertighel
leonard vertighel

Reputation: 1068

Python check if an argument is a string or a list with one string

I want to pass to a function a string argument. But a list containing one string element is ok, too.

Is there a more compact / pythonic way to to this?

files = ["myfile"]
isinstance(files[0], list) and len(files[0]) == 1

Upvotes: 0

Views: 1374

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55679

I tend to use a *args parameter to avoid the check.

def f(*args):
    for arg in args:
        print(arg)

f('foo')
foo

f(*['foo'])
foo

Of course the caller must use the correct calling convention, which may or may not be problematic.

If the above approach is not feasible, and it also not feasible to redesign the application to avoid this argument overloading then isinstance is as good as anything.

I would check vs str so that containers other than lists are accepted by the function (such as deques and tuples).

s = files if isinstance(files, str) else files[0] 

Upvotes: 1

Leo Arad
Leo Arad

Reputation: 4472

You can do it by

files = ["myfile"]
function(files if isinstance(files, list) and len(files) == 1 else files[0])

or you can change the files[0] to other element if you want a diffrent element in case files is not a list that contain 1 item.

Upvotes: 1

Related Questions