Pass package/module as argument in Python
Asked Answered
D

0

6

Suppose I write some plotting program. This program depends on a module that can draw graphics primitives. But that graphics module could be anything that supports the used operations. It could be a module that plots on screen or writes to a file format or controls a robot with a pen.

I'd like to dynamically switch that module. In C++, one would typically use the abstract factory pattern: The plotting program receives a factory as a parameter from where it constructs the desired graphics primitives. It would be perfectly feasible to implement the factory pattern also in Python.

But - would it be a good idea to just use the package as a parameter? From the pure technical perspective, a program like following would work:

import screen_graphics
import robot_graphics

def my_plot_prog(graphics_lib):
   ...

my_plot_prog(screen_graphics) # plot on screen
my_plot_prog(robot_graphics) # R/C robot with a pen

Can I do it like that or are there some serious pitfalls or better approaches?

Darondarooge answered 30/7, 2016 at 7:34 Comment(6)
Seems related to: #600690Exhibitor
Slightly related. The other question is about a global state, this question is purely about functionality to import.Darondarooge
Yes, in short my answer would be: Modules are first class objects in Python and there is nothing wrong with using them the way you propose. The only thing to keep in mind is that they behave like singletons, which may be a drawback if you need to manage state.Exhibitor
@kloffy: But that would only happen if those modules use (module-)global variables? Or are there any other ways to accidentally introduce state into modules?Darondarooge
Pretty much, yes. I will give others a chance to chime in, but if you just want to pass around interchangeable sets of functions, this seems like a perfectly valid way of doing it.Exhibitor
"But that graphics module could be anything that supports the used operations" - including not a module at all! You could pass in some other kind of object, if it has the right methods. You could mix and match, passing in modules sometimes and instances of other types when it makes sense.Faust

© 2022 - 2024 — McMap. All rights reserved.