Set a flag on the function or a global?
Ron Adam
ron3200 at gmail.com
Tue Jun 16 07:02:03 EDT 2015
On 06/16/2015 05:15 AM, Steven D'Aprano wrote:
> On Tuesday 16 June 2015 10:24, Ron Adam wrote:
>
>> >Another way is to make it an object with a __call__ method.
>> >
>> >The the attribute can be accessed from both outside and inside dependably.
> That's what functions are, objects with a __call__ method:
>
>
> py> (lambda: None).__call__
> <method-wrapper '__call__' of function object at 0xb7301a04>
Yes ;-)
> One slight disadvantage is that functions don't take a "self" parameter by
> default, which means they have to refer to themselves by name:
>
> def spam():
> print spam.attr
>
>
> Here's a fun hack:
>
> py> from types import MethodType
> py> def physician(func):
> ... # As in, "Physician, Know Thyself":-)
> ... return MethodType(func, func)
> ...
> py> @physician
> ... def spam(this, n):
> ... return this.food * n
> ...
> py> spam.__func__.food = "spam-and-eggs "
> py> spam(3)
> 'spam-and-eggs spam-and-eggs spam-and-eggs'
How about this?: (paste it into your console)
#---------------------
import sys
class EDir:
long = False
def __call__(self, obj=None):
if obj == None:
d = sys._getframe(1).f_locals
else:
d = dir(obj)
return [x for x in d if self.long or not x.startswith("_")]
edir = EDir()
edir()
edir(edir)
edir.long = True
edir(edir)
edir.long = False
edir(edir)
#----------------------
I didn't test how that works from other modules or in nested scopes. Also
replacing None with a unique sentinel object may be better so dir(None)
will work.
Cheers,
Ron
More information about the Python-list
mailing list