Cách import lib python

Em mới làm quen với python. Tuy nhiên không biết nên import kiểu nào cho hợp lý để đạt được hiệu suất tốt nhất

Ex:

Import ngay từ đầu ở 1 nơi nhưng mỗi def chỉ sử dụng GẦN NHƯ 1 LẦN

import numpy as np
import scipy.interpolate as interpolate
from math import sqrt
from uuid import uuid1


def a():
    # use np
    pass


def b():
    # use interpolate
    pass


def c():
    # use sqrt
    pass


def d():
    # use uuid1
    pass

hay là thằng nào dùng thì import cho thằng đó

def a():
    import numpy as np
    # use np
    pass


def b():
    import scipy.interpolate as interpolate
    # use interpolate
    pass


def c():
    from math import sqrt
    # use sqrt
    pass


def d():
    from uuid import uuid1
    # use uuid1
    pass

Cách nào tối ưu hơn và ưu nhược điểm của mỗi cách?

Đây là quy tắc import của PEP-8

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?