1

When i use pytorch,i am wondering why i can't import partial functions or variables from torchvision.models.vgg using "from torchvision.models.vgg import *"

Like this:

from torchvision.models.vgg import *

if __name__=="__main__":
    print(cfgs["A"])

and

from torchvision.models.vgg import *

from typing import Union, List, Dict, Any, cast
cfgs: Dict[str, List[Union[str, int]]] = {
    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}

if __name__=="__main__":
    print(make_layers(cfgs["A"]))

variables "cfgs" and function "make_layers" can't be found

But i could use function like "vgg16_bn()" which is in the same file as "make_layers"

from torchvision.models.vgg import *


if __name__=="__main__":
    print(vgg16_bn())

I need to import like this:

from torchvision.models.vgg import cfgs,make_layers


if __name__=="__main__":
    print(make_layers(cfgs["A"]))

But if the file i import is created by myself like this:

b.py:

url="http"

def a ():
    return True

main.py could find variable "url" and function "a()"

from b import *


if __name__=="__main__":
    print(url)
    print(a())

I don't know why it happens like this,could someone explain it.Thanks!

Darcy
  • 21
  • 4
  • `torchvision.models.vgg` is not a publicly documented part of the `torchvision` API. You're not supposed to access it directly like that. – user2357112 Oct 29 '21 at 03:57

1 Answers1

1

torchvision/models/vgg.py sets this particular __all__ indicating their exported symbols:

__all__ = [
    "VGG",
    "vgg11",
    "vgg11_bn",
    "vgg13",
    "vgg13_bn",
    "vgg16",
    "vgg16_bn",
    "vgg19_bn",
    "vgg19",
]

* imports (while generally discouraged) will by default expose the names in __all__ (or if __all__ is missing, any names which do not start with _)

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
  • Would cite your comment with this question: https://stackoverflow.com/questions/2386714/why-is-import-bad – flakes Oct 29 '21 at 04:03