开发者

Storing a list of modules

开发者 https://www.devze.com 2023-03-17 09:22 出处:网络
I recently learned of the __ import__ 开发者_开发技巧function and found that I could store a module in a variable, so I was thinking of making a list of modules and then calling the appropriate one wh

I recently learned of the __ import__ 开发者_开发技巧function and found that I could store a module in a variable, so I was thinking of making a list of modules and then calling the appropriate one when necessary.

So I might have three modules test1, test2, test3, each containing a single function "print_hello" that simply prints "hello, I'm [module name]"

At runtime, I would call some function to import those modules and put them in a list. Then I would pick a random number between 0 and 2 inclusively, pick that module from the list, and print hello.

#run function to import each module, resulting in the following list
#my_modules = [module1, module2, module3]

#generate some number i
chosen_module = my_modules[i]
chosen_module.print_hello()

Is this acceptable coding practice? Or are there any reasons that would discourage this?


I use this sort of approach in some of my testing code. I want to test output from one version of a module against a different versions of the same module. Being able to iterate over different module instances makes the code cleaner.

But this sort of code is the exception to the rule. It's very infrequently that this approach is the cleanest solution to a problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号