Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.stack.nl!aioe.org!.POSTED!not-for-mail From: Marco Buttu Newsgroups: comp.lang.python Subject: Re: Behavior of staticmethod in Python 3 Date: Sat, 23 Nov 2013 10:39:44 +0100 Organization: Aioe.org NNTP Server Lines: 81 Message-ID: <529077E0.8090603@gmail.com> References: NNTP-Posting-Host: kf7DwN4FUBS92MXtMd7OlQ.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:16.0) Gecko/20121010 Thunderbird/16.0.1 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.python:60287 On 11/23/2013 10:01 AM, Peter Otten wrote: >> In Python 3 the following two classes should be equivalent: > Says who? > >> >$ cat foo.py >> >class Foo: >> > def foo(): >> > pass >> > print(callable(foo)) >> > >> >class Foo: >> > @staticmethod >> > def foo(): >> > pass >> > print(callable(foo)) >> > >> >But they do not: >> > >> >$ python3 foo.py >> >True >> >False >> > > Your script is saying that a staticmethod instance is not a callable object. > It need not be because > > Foo.foo() Yes, you are right about Python 3. But in Python 2, if I am not going wrong, there is not solution, and I need to define a function outside the class. For instance: $ cat config.py class Configuration(object): def positiveCheck(value): if not value > 0: raise AttributeError('Must be a positive number') attributes = { # Attribute name: (type, checkrule) 'myattr': (int, positiveCheck), } def __setattr__(self, name, value): if not name in Configuration.attributes: raise AttributeError("Attribute `%s` non allowed." %name) expected_type, checkrule = Configuration.attributes[name] if not isinstance(value, expected_type): raise TypeError('The value %s is not of type %s' \ %(value, expected_type.__name__)) if callable(checkrule): print('calling %s(%s)' %(checkrule.__name__, value)) checkrule(value) super(Configuration, self).__setattr__(name, value) The positive check works fine: >>> from config import Configuration >>> c = Configuration() >>> c.myattr = -10 calling positiveCheck(-10) Traceback (most recent call last): ... AttributeError: Must be a positive number But I cannot use the method as a function: >>> Configuration.positiveCheck(-10) Traceback (most recent call last): ... Configuration instance as first argument (got int instance instead). Furthemore, I cannot use the method as a staticmethod, becase otherwise it will not be callable inside the class body. -- Marco Buttu