Home > database >  How can I call a python function strored as an attribute?
How can I call a python function strored as an attribute?

Time:11-07

I am not understanding something very basic about Python, variables, and functions. I am trying to store a function inside an attribute in an object, then retrieve it and call it.

def FilterHidden(path: pathlib.Path)->bool:
   return path.name.startswith('.')
   
class Filter(object) :
   dirFilterer=FilterHidden
   fileFilterer=FilterHidden
    
   def shouldFilter(s, path:pathlib.Path)->bool:
      filterer=s.dirFilterer if path.is_dir() else s.fileFilterer
      return filterer(path)

From the errors, I gather that the filterer function is attempted to be called with two arguments: The implicit self, and the exlpicit path.

mypy: Invalid self argument to "Filter" to attribute "dirfilterer" with type "Callable[[Path],bool]
python: TypeError: FilterHidden() takes 1 positional argument but 2 were given

It makes me feel better to expose that I have grown old and have trouble with new languages because nobody wants to say "Inside Python, this is what happens". I feel very mislead by simplified ideals. Computers are not conceptual; they are calculators that follow very precise patterns.

CodePudding user response:

s.dirFilterer returns a bound method instance instead of function FilterHidden. You could use a static method to make it work

>>> def foo():
...     pass
... 
>>> class Bar:
...     f = foo
... 
>>> b = Bar()
>>> b.f
<bound method foo of <__main__.Bar object at 0x7f04d0ad9430>>
>>> 
>>> class Qux:
...     f = staticmethod(foo)
... 
>>> q = Qux()
>>> q.f
<function foo at 0x7f04d0a84d30>

CodePudding user response:

I supose your are trying to make private Class Atributes, python doesnt have private method, bout you can build it arcficialy by using factory pattern, take a look:

from pathlib import Path


def filter_factory(object):

  #put your private methods here
  def FilterHidden(path: Path)->bool:
    return path.name.startswith('.')
    
  class Filter(object) :
    
    #put your public methods here 
    def shouldFilter(s, path:Path)->bool:
        return FilterHidden(path)

  return Filter()






  • Related