def ensure_list(papers):
if type(papers) is not list:
papers = [papers]
return papers
papers = 1
try:
papers.append(7)
except:
print "not a list"
papers = ensure_list(papers)
papers.append(5)
for item in papers:
print item
This question is asking what is the best way to check and change a variable to a type if it is not. Is there a better way to make papers a list with the object as its first element? I am writing some code that may be given an object or a list of objects and if it is an object I want it to be appended to a list and then handled.
This is only done once so it seems like over kill to have a separate function for this.
Edit: The elements will always be a known type (custom class), and always be a list of custom type object or custom type object .
Here the answer: (Thank you Random832)
papers if isinstance(papers, list) else [papers]
Edit2: this is not a duplicate of the other question as this is not asking how to check if something is a list. This question is asking what is the best way to check and change a variable to a type if it is not. This would apply to any type we like really, the general answer is to inline with isinstance. The answer to this specific question question is the inlined statement provided by Random832 nowhere in that other question is that listed. Please read and understand the question before you flag it.