Set a flag on the function or a global?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jun 16 05:07:28 EDT 2015


On Tuesday 16 June 2015 10:20, Ben Finney wrote:

> Chris Angelico <rosuav at gmail.com> writes:
> 
>> On Tue, Jun 16, 2015 at 9:57 AM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>> > I can use a flag set on the function object itself:
>> >
>> > edir.dunders = False
>>
>> For most situations, the last one is extremely surprising - attributes
>> on functions aren't normally meant to be changed by outside callers,
>> it always feels wrong (they belong to the function itself).
> 
> I'm surprised by your assertion. To my mind, outside callers get simple
> and direct access to the attribute, whereas the code of the function
> itself does not have such easy access; unlike ‘self’ for the current
> instance of a class, there's no obvious name to use for referring to the
> function object within the function object's own code.
> 
> In what sense do they “belong to” the function itself *more than* to
> outside callers?

I won't answer for Chris, but speaking for myself, I think that an attribute 
attached to a function is very clearly "part of" the function object in a 
way that a global is not.

A bare global gives no hint as to which function(s) it will affect:

dunders = True

We can simulate a namespace by giving the name a prefix:

edir_dunders = True
hasattr(edir, "dunders")  # False, despite the simulated namespace


but using a real namespace is much better:

edir.dunders = True
hasattr(edir, "dunders")  # True


But having said that, I think that especially in Python the implication here 
is that such an attribute is public and intended for outsiders to at least 
read, if not write.

Adding public attributes to functions is deliberately supported in Python, 
but it is greatly under-utilized.


-- 
Steve




More information about the Python-list mailing list