Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I use an attribute as both and attribute and a method/callable?

Tags:

python

This is kindof an experiment. I'm interested in an API that supports both of these syntaxes:

obj.thing

--> returns default value

obj.thing(2, 'a')

--> returns value derived from *args and **kwargs

"thing" is the same object in both cases; I'd like the calling of thing to be optional (or implicit, if there are not () after it).

I tried over-riding __repr__, but that's just the visual representation of the the object itself, and what is actually returned is an instance of the containing object (here, 'obj'). So, no good.

I'm thinking that there would be an attribute set on an object that was a callable (don't care if it's an instance, a def, or just __call__ on the object) that has enough default values:

class CallableDefault(object):
    __call__(self, num=3, letter="z"):
        return letter * num

class DumbObject(object):
    foo = CallableDefault()

obj = DumbObject()

so, ideally, doing obj alone would return "zzz", but one could also do obj(7,'a') and get 'aaaaaaa'.

I'm thinking decorators might be the way to do this, but I'm not great with decorators. One could override the getattr() call on the containing class, but that would mean that it has to be in a containing class that supports this feature.

like image 518
Matt Feifarek Avatar asked Jan 29 '26 05:01

Matt Feifarek


1 Answers

What you describe could work, but notice that now the value of the attribute is constrained to be an object of your CallableDefault class. This probably won't be very useful.

I strongly suggest that you don't try to do this. For one thing, you're spending a lot of time trying to trick Python into doing something it doesn't want to do. For another, the users of your API will be confused because it acts differently than every other Python code they've ever seen. They will be confused.

Write a Python API that works naturally in Python.

like image 91
Ned Batchelder Avatar answered Jan 30 '26 19:01

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!