0

This might be a dumb question, but I did some googling and digging on SO and came up short of a proper answer. So I'll just ask:

Is it possible to assign a __call__ method to a Python module or package?

What I mean is, instead of calling a method from the module/package's namespace, could I call an assigned method directly?

How it is now:

import foo

foo.bar(123)

What I want to do:

import foo

foo(123)

If this isn't possible, what would it take to monkeypatch in a feature like this? (That might be asking a lot)

martineau
  • 119,623
  • 25
  • 170
  • 301
frissyn
  • 91
  • 8
  • @Carcigenicate I don't **need** the module itself to be called, I was just wondering since it seemed more semantically appealing to me. – frissyn Feb 16 '21 at 23:04

2 Answers2

0

I thought that you could name the file hello.py then do:

class hello:
   def hi():
     return "hello"

then in the main file do:

from hello import hello
hello.hi()
BRUH
  • 1
  • 2
0

Yes, you can do something like that.

foo_module.py

class Foo:
    def __call__(self, arg):
        print(f'Foo({arg!r}) called')

_ref, sys.modules[__name__] = sys.modules[__name__], Foo()

main.py

import foo_module

foo_module(123)  # -> Foo(123) called
martineau
  • 119,623
  • 25
  • 170
  • 301
  • ooo, that's a pretty hacky way of doing it, but it works, so no complaints from me! thanks! – frissyn Feb 16 '21 at 23:12
  • It may be hacky, but I learned about it a book by the venerable @[Alex Martelli](https://stackoverflow.com/users/95810/alex-martelli), one of the true masters of the language. See his answer to [Can modules have properties the same way that objects can?](https://stackoverflow.com/questions/880530/can-modules-have-properties-the-same-way-that-objects-can) for another example. – martineau Feb 16 '21 at 23:16
  • Thanks for the information, I'll take a look – frissyn Feb 16 '21 at 23:17
  • Note: I just changed `foo_module` a little to prevent a problem I ran into once—see [Why is the value of __name__ changing after assignment to sys.modules\[\_\_name\_\_\]?](https://stackoverflow.com/questions/5365562/why-is-the-value-of-name-changing-after-assignment-to-sys-modules-name) – martineau Feb 16 '21 at 23:31