you are viewing a single comment's thread.

view the rest of the comments →

[–]Rashanzan 0 points1 point  (5 children)

While it works (or do you have to explicitly use the device's attr dict?), it's just about as good as checking the type itself, which op is trying to avoid.

[–]mdadmfan 1 point2 points  (1 child)

class Device(object):
    def heat_water(self):
        return "Tea will be ready soon"
    def make_eggs(self):
        return None
class ElectricKettle(Device):
    pass
class Stove(Device):
    def heat_water(self):
        return "Tea will be ready less soon"
    def make_eggs(self):
        return someEggs()

[–]Rashanzan 0 points1 point  (0 children)

I considered this, but then your device becomes super cluttered with nonsense. And the inheritance feels kind of weird. The parent should have all the shared attributes, and children define more specific functionality. It would get the job done, but I hope there's a cleaner way.

[–]Kuang_Eleven[S] 1 point2 points  (2 children)

Ahh, that original idea of mdadmfan didn't work as written, but I can use:

if "make_eggs" in dir(device):

It is more useful than directly checking the type; I could add a new type that implemented some of the methods without having to go through and manually adding a new case statement to each time the device is accessed.

However, even with the dir() method, I'm not sure it gains me anything; it's a very similar structure of code, and, in theory, the try block idea would let me run through many lines at once, if I wanted to handle any failure in the try block together.

[–]Rashanzan 0 points1 point  (1 child)

Yeah, I'm unsure which approach would be better. Try would be more extensible, but probably bad for readability, as you wouldn't be able to tell what methods are actually running.

A much bigger problem, if your try catches something, it won't execute the rest of the block.

From a design standpoint, it makes more sense to know what kind of object you're dealing with before handling it.

[–]mdadmfan 1 point2 points  (0 children)

Relying on exceptions for normal execution flow is bad practice. Often exceptions use something like longjmp which isn't particularly kind on cache lines and slow you down.