Python: How to import, from two modules, Classes t

2020-03-29 07:15发布

问题:

I'm writing a python programm to do granular syncs between different DB.

I'm using SQLAlchemy and a module named sqlautocode for DB inspecting and Schema Classes production.

Having two DB to sync, with same tables name, the Classes written by sqlautocode results with same names.

I have to import theese Classes with arbitrary prefixes, I'm thinking about something like this:

from module_name import * with prefixes

Otherwise I should import every Classes name with an "as" modifier, like this:

from module_name import x as master_x

First of HardCode name extraction procedures with control lists and exec/eval complex code I'd like some suggestions about it.

UPDATE: The solution is a sqlautocode option: --table-prefix=TABLE_PREFIX

thank you all

回答1:

Just import the modules and don't try to pull the names from them. from X import Y should be used sporadically, anyway.

import module_a
import module_b

module_a.x
module_b.x


回答2:

You don't have to import classes from modules in this case. Instead import both modules. Like this:

import moda, modb

moda.MyClass()
modb.MyClass()

On the other hand this doesn't let you use cool tools like pyflakes. So I would do the hard work (you have to do it only once, right?) and import classes with renaming. I am great supporter of from x import something because it let's you detect errors the earliest possible.