Reputation: 2546
Suppose I use some 3rd party module that depends on code from another one:
# third_party.py
from package import fun, A
class B(A):
def foo(self):
self.do()
self.some()
self.stuff()
return fun(self)
And then I want to inherit this class in my code to change functionality:
# my_code.py
from third_party import B
# from third_party import fun?
# from package import fun?
class C(B):
def foo(self):
return fun(self)
What is better: from package import fun
or from third_party import fun
to get access to fun
?
I like second variant since I may do not bother with actual paths and import all dependences from third_party
package, but has this way any drawbacks? Is this a good or bad practice?
Thanks!
Upvotes: 2
Views: 185
Reputation: 35039
I dont't think that importing a function/class from a third party package is a bad practice, it may even has some benefits (e.g: If you want to monkey patch a package, or need to be sure, that something is set up correctly).
It even may be necessary to support a variety of setups. Consider the ElementTree
API, which is differently available on specific Python versions and may even be provided from third party libraries (taken from here):
# somepackage.py
try:
from lxml import etree
print("running with lxml.etree")
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
print("running with cElementTree on Python 2.5+")
except ImportError:
try:
# Python 2.5
import xml.etree.ElementTree as etree
print("running with ElementTree on Python 2.5+")
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
print("running with cElementTree")
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
print("running with ElementTree")
except ImportError:
print("Failed to import ElementTree from any known place")
Now, it is guranteed that somepackage
contains a working etree
implementation, even on different Python installations and your package serves as an abstraction.
Upvotes: 1