Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python is there a way to know if an object "implements an interface" before I pass it to a function?

I know this may sound like a stupid question, especially to someone who knows python's nature, but I was just wondering, is there a way to know if an object "implements an interface" so as to say?

To give an example of what I want to say:

let's say I have this function:

def get_counts(sequence):
     counts = {}
     for x in sequence:
         if x in counts:
             counts[x] += 1
         else:
             counts[x] = 1
     return counts

My question is: Is there a way to make sure that the object passed to the function is iterable? I know that in Java or C# I could do this by having the method accept any object that implements a specific interface, let's say (for example) iIterable like this: void get_counts(iIterable sequence)

My guess is that in Python I would have to employ preemptive introspection checks (in a decorator perhaps?) and throw a custom exception if the object doesn't have an __iter__ attribute). But is there a more pythonic way to do this?

like image 433
NlightNFotis Avatar asked Dec 17 '12 18:12

NlightNFotis


People also ask

How do you check if an object implements an interface?

Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.

Which keyword validates whether a class implements an interface?

With the aim to make the code robust, i would like to check that the class implements the interface before instantiation / casting. I would like the the keyword 'instanceof' to verify a class implements an interface, as i understand it, it only verifies class type.

Can an object be an instance of an interface?

You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance. And an abstract class is missing parts of its implementation, or is explicitly marked as abstract to prohibit instantiation.


1 Answers

Python (since 2.6) has abstract base classes (aka virtual interfaces), which are more flexible than Java or C# interfaces. To check whether an object is iterable, use collections.Iterable:

if isinstance(obj, collections.Iterable):
    ...

However, if your else block would just raise an exception, then the most Python answer is: don't check! It's up to your caller to pass in an appropriate type; you just need to document that you're expecting an iterable object.

like image 127
ecatmur Avatar answered Oct 27 '22 22:10

ecatmur