0

Coming from other scripting languages like AutoHotkey and PowerShell, it seems verbose to have to declare a class in order to return an object from a function. Is there a simpler way to accomplish this in Python?

def structuring_element():
    return {kind: 'flat'; structure: []}

tool = structuring_element()
print(tool.kind)
# 'flat'
print(tool.structure)
# []

Looks like the simplest way is to declare a class and create the structuring element in the __init__ statement like so:

class structuring_element(object):
    def __init__(self):
        self.kind = 'flat'
        self.structure = []

Currently I'm using multiple outputs but it doesn't feel as elegant as being able to keep them in an object together:

def structuring_element():
    return 'flat', []

kind, structure = structuring_element()
  • 3
    Everything in Python is an object. What's wrong with the dictionary object you return in your first example? – Samwise May 06 '21 at 15:33
  • @Samwise `tool.kind` won't work, it has to be `tool['kind']` – Barmar May 06 '21 at 15:34
  • 2
    Don't name your variable the same as the function. You won't be able to call the function again. – Barmar May 06 '21 at 15:34
  • 1
    It should be a comma not a semicolon in the return statement. – Jan May 06 '21 at 15:35
  • 7
    I think what you want is a [named tuple](https://stackoverflow.com/questions/2970608/what-are-named-tuples-in-python) – Barmar May 06 '21 at 15:35
  • "Currently I'm using multiple outputs": no, you are returning a *tuple* that contains your elements. As such, you can keep them together as a tuple. And the namedtuple functions similarly, but with easier access to the individual elements. – 9769953 May 06 '21 at 15:44
  • A dict works but I'm not sure why I can't return an object just the same. ``` def tool(): return {'kind': 'flat', 'structure': []} ``` – Kevin Higby May 06 '21 at 15:45
  • My apologies, I'm new to Python. I thought a tuple was contained in parethesis. What's the difference between return x, y and return (x, y)? – Kevin Higby May 06 '21 at 15:48
  • @Barmar that's exactly what I'm looking for! `return namedtuple('nt', 'kind structure')(kind, structure)` – Kevin Higby May 06 '21 at 16:02

0 Answers0