سؤال

I have a third-party module (cx_Oracle) that I'd like to import whose location is unknown from environment to environment. I am currently using pythons configparser so I thought it would be a neat trick to set the location of the module within the config parser, append that location to path, and then import the third-party module from there.

This worked all fine and dandy until I began to refactor my code and started to split out logic into their own class/methods:

class Database:

    def __init__(self, config):
        self.CONFIG=config
        sys.path.append(self.CONFIG.cx_oracle_path)
        from cx_Oracle import cx_Oracle

        self.open()

    def open(self):
        self.CONNECTION = cx_Oracle.Connection(self.CONFIG.username,
        self.CONFIG.password,
        self.CONFIG.db_sid)
        self.CURSOR = self.CONNECTION.cursor()
     ....
     ....
     ....

Of course, the open method does not know what to do because cx_Oracle was defined in init and so the open method cannot see it.

I can't picture the proper way to do this, so I'm assuming I am over thinking this. What should I do instead so that open (and all other methods within the Database class) can see the imported module?

Thank you.

هل كانت مفيدة؟

المحلول

If you only need to use cx_Oracle within that class, you can just set it as an attribute on this instance, for example:

class Database:

    def __init__(self, config):
        self.CONFIG=config
        sys.path.append(self.CONFIG.cx_oracle_path)
        from cx_Oracle import cx_Oracle
        self.cx_Oracle = cx_Oracle
        self.open()

    def open(self):
        self.CONNECTION = self.cx_Oracle.Connection(self.CONFIG.username,
                                                    self.CONFIG.password,
                                                    self.CONFIG.db_sid)
        self.CURSOR = self.CONNECTION.cursor()

As a side note, if you are creating multiple Database instances this is an odd approach, since you would end up adding multiple identical entries to sys.path.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top