Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are imported packages visible inside other packages?

Tags:

python

package

If I create a package named foo that imports bar, why is bar visible under foo as foo.bar when I import foo in another module? Is there a way to prevent this; to keep bar hidden so as not to clutter the namespace?

like image 890
Emre Avatar asked Dec 06 '25 23:12

Emre


1 Answers

Import bar wherever you use it, rather than globally

If bar is being used in a function, import as

def func():
  import bar
  ....

Or even,

if __name__ == '__main__':
    import bar
    my_main(bar)

Or if you love classes,

class Fubar():
    def __init__(self):
        import bar
        self.bar = bar
like image 76
rjv Avatar answered Dec 09 '25 13:12

rjv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!