Question

Suppose I initialize a library, say, in python object -

#filename: file_A
import file_
class A():
    def __init__(self):
        self.pd = file_.pd
        self.np = file_.np

And suppose the content of the file_ is,

#filename: file_
import pandas as pd
import numpy as np

You might be wondering what's the sense of including those libraries as objects, for import file_ will anyway include namespace of pd & np but the reason of inclusion is to make these libraries available for child classes, as bellow.

#filename: file_B
from file_A import A
Class B(A):
    # Getting all the libraries without even importing them again. 

My concern is about the implications of this strategy. Is it a better idea to adopt such way?

Was it helpful?

Solution

Modules are objects in Python, and objects can be assigned to variables. There is nothing inherently good nor bad about it. If it solves your problem then it's probably fine, if it causes problems that you're concerned with, then it's probably bad.

The only thing that I would have done differently is to just move the import into inside the class:

class A(object):
    from file_ import *

or

class A(object):
    import pandas as pd
    import numpy as np

which is simpler and makes it clearer that you do intend to import those into the class namespace. Assigning the variables in __init__ have the drawback that child classes will have to remember to call super().__init__() if they override __init__.

Licensed under: CC-BY-SA with attribution
scroll top