kkaaii
kkaaii

Reputation: 31

ModuleNotFoundError while importing from alias

e.g.

import os as my_os
import my_os.path

ModuleNotFoundError: No module named 'my_os'

but the following script is ok

import os
import os.path

Upvotes: 0

Views: 295

Answers (2)

kkaaii
kkaaii

Reputation: 31

Tried the similar way as os.py did:

import json as my_json
from my_json.decoder import *   # ModuleNotFoundError: No module named 'my_json'

import sys
import json.decoder as my_decoder
sys.modules['my_json.decoder'] = my_decoder
from my_json.decoder import *   # it's ok now

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71600

You can't do that in Python.

  1. import statements are importing from Python file names.

  2. You aren't renaming the file of os to my_os, therefore this wouldn't work.

As mentioned in the documentation:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.

Upvotes: 2

Related Questions