10

I'm writing a module called foo that has many internal functions, but ultimately boils down to a single external function foo(). When using this module/function, I'd like to do

import foo
foo(whatever)

instead of

from foo import foo
foo(whatever)

Is this possible?

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103

2 Answers2

17

You could monkey patch the sys.modules dictionary to make the name of your module point to the function instead of your module.

foo.py (the file defining your module foo) would look like this

import sys

def foo(x):
    return x + x

sys.modules[__name__] = foo

then you can use this module from a different file like this

import foo
print(foo(3))
6

There are probably reasons for why you shouldn't do this. sys.modules isn't supposed to point to functions, when you do from some_module import some_function, the module some_module is what gets added to sys.modules, not the function some_function.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
0

It is not strictly possible. Python module names are ment to help the programmer distinguish between modules. So even if you had one function, bar in your module foo, using import foo will still need a foo.bar(). You're probably better off just using from foo import *.

However there may be a way around this. Python also has built-in functions, and you may be able to add your own functions to this. Doing so might require rewriting the compile though.

So conclusion: writing from foo import * isn't all that ugly and is a lot easier and prettier than the long way around.

Preston Hager
  • 1,514
  • 18
  • 33