Python Module Import: Single-line vs Multi-line

后端 未结 3 1372
天涯浪人
天涯浪人 2020-12-13 08:07

So this is just a simple question. In python when importing modules, what is the difference between this:

from module import a, b, c, d

and

3条回答
  •  北海茫月
    2020-12-13 08:37

    I would suggest not to follow PEP-8 blindly. When you have about half screen worth of imports, things start becoming uncomfortable and PEP-8 is then in conflicts with PEP-20 readability guidelines.

    My preference is,

    1. Put all built-in imports on one line such as sys, os, time etc.
    2. For other imports, use one line per package (not module)

    Above gives you good balance because the reader can still quickly glance the dependencies while achieving reasonable compactness.

    For example,

    My Preference

    # one line per package
    
    import os, json, time, sys, math
    import numpy as np
    import torch, torch.nn as nn, torch.autograd, torch.nn.functional as F
    from torchvision models, transforms
    

    PEP-8 Recommandation

    # one line per module or from ... import statement
    
    import os
    import json
    import time
    import sys
    import math
    
    import numpy as np
    
    import torch
    from torch import nn as nn, autograd, nn.functional as F
    from torchvision import models, transforms
    

提交回复
热议问题