Should you import all the classes you use in Python?

The absence of static typing of Python allows you to use and rely on classes without importing them. Should you import them anyway? Does it matter?

Example

someclass.py

class SomeClass:
    def __init__(self, some_value):
        self.some_value = some_value

someclient.py

class SomeClient:
    def __init__(self, some_class_instance):
        self.some_class_helper = some_class_instance

Here, the functionality SomeClientclearly depends on, SomeClassor at least on, how it behaves. However, someclient.py will work fine without import someclass. This is normal? It is wrong to use something without saying a word that you even use it.

+3
source share
4 answers

, . some_class_instance , SomeClass. , , SomeClass, , , .

+9

SomeClass .

, , , SomeClient SomeClass / docstring.

, SomeClient SomeClass, assert :

class SomeClient:
    def __init__(self, some_class_instance):
        assert isinstance(some_class_instance, SomeClass)
        self.some_class_helper = some_class_instance

SomeClass. , , , Mock SomeClass . ( : "isinstance() " .)

+6

.

Python , duck typing" - , , .

, . , , , , "SomeClass".

-

, , ( "If , , , ".) , , , . - () isinstance(). ( , , .) hasattr() EAFP.

+4

Python, " ", , , .

+1

Source: https://habr.com/ru/post/1719921/


All Articles