0

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
3
  • 2
    I don't think so. However, it looks like it should be isinstance(files, list) and len(files) == 1 instead Commented Apr 26, 2020 at 11:05
  • 1
    you can use final_string = ' '.join(lis[0]) also your isinstance(files[0], list) and len(files[0]) == 1 will result in false. the correct way can be isinstance(files[0], str) and len(files) == 1 Commented Apr 26, 2020 at 11:07
  • @ForceBru yes, you're right. In my case it returns False, in yours True Commented Apr 26, 2020 at 13:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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] 

1 Comment

This is a very nice solution, but I have multiple arguments to check this way, and I cannot use def f(*args1, *args2, *args3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.