0

I'm trying to build some custom Python modules.

Even though I was able to use all modules. When I try to import a module other modules are being imported.

For example:

mod1.py

import os
import sys

def f(x):
    return (x**2)

main.py

import mod1

dir(mod1.os)

how can I avoid this behaviour? The user should not be able to access the other modules from mod1. In this example os and sys.

Should I put the import statements inside the function? Are there other ways to prevent such thing?

GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26
kaihami
  • 815
  • 7
  • 18
  • I'm afraid that except naming every thing you want to import (`from mod1 import f`), there is now way to avoid this behaviour. Python has a way of controlling the star imports (`from mod1 import *`), but not the one you described. There are some nice answers mentioning both variants here https://stackoverflow.com/questions/44834/can-someone-explain-all-in-python – mfrackowiak Jan 11 '19 at 16:34

1 Answers1

0

The behavior you are seeing is perfectly normal. Python does not hide elements quite so strongly as some other languages. We're all adults here, and are expected to behave responsibly, without strong enforcement from the language.

Should I put the import statements inside the function?

No, your code is just fine the way it is.

If you plan to write a bunch of python code, you should follow the usual conventions that everyone else does, as shown in your example code. In main.py, if you want to access an os function, you should certainly import it there, rather than borrowing a reference from mod1.os.

J_H
  • 17,926
  • 4
  • 24
  • 44