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
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]
def f(*args1, *args2, *args3)
isinstance(files, list) and len(files) == 1insteadfinal_string = ' '.join(lis[0])also yourisinstance(files[0], list) and len(files[0]) == 1will result in false. the correct way can beisinstance(files[0], str) and len(files) == 1False, in yoursTrue