Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload from/import in Python?

Is it possible to overload the from/import statement in Python?

For example, assuming jvm_object is an instance of class JVM, is it possible to write this code:

class JVM(object):

  def import_func(self, cls):
    return something...

jvm = JVM()

# would invoke JVM.import_func
from jvm import Foo
like image 695
Barthelemy Avatar asked Oct 13 '10 21:10

Barthelemy


People also ask

Why no function overloading in Python?

Why no Function Overloading in Python? Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.

What happens when Python import a file with multiple @overload definitions?

When Python imports the file, the @overload definitions create temporary double functions, but each is overridden by the next definition. After importing, only the implementation exists.

What is overloading in JavaScript?

Overloading is the ability of a function or an operator to behave in different ways based on the parameters that are passed to the function, or the operands that the operator acts on. Some of the advantagesof using overload are:

Why do I get a notimplementederror when using @overload in Python?

When Python imports the file, the @overload definitions create temporary double functions, but each is overridden by the next definition. After importing, only the implementation exists. As a protection against accidentally missing implementations, attempting to call an @overload definition will raise a NotImplementedError.


2 Answers

This post demonstrates how to use functionality introduced in PEP-302 to import modules over the web. I post it as an example of how to customize the import statement rather than as suggested usage ;)

like image 180
aaronasterling Avatar answered Oct 09 '22 10:10

aaronasterling


It's hard to find something which isn't possible in a dynamic language like Python, but do we really need to abuse everything? Anyway, here it is:

from types import ModuleType
import sys

class JVM(ModuleType):
    Foo = 3

sys.modules['JVM'] = JVM

from JVM import Foo
print Foo

But one pattern I've seen in several libraries/projects is some kind of a _make_module() function, which creates a ModuleType dynamically and initializes everything in it. After that, the current Module is replaced by the new module (using the assignment to sys.modules) and the _make_module() function gets deleted. The advantage of that, is that you can loop over the module and even add objects to the module inside that loop, which is quite useful sometimes (but use it with caution!).

like image 3
tux21b Avatar answered Oct 09 '22 10:10

tux21b