Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not exporting functions from Python module

Tags:

python

If I have a module/file foo.py with the following contents:

from math import sqrt

def foo():
    pass

If I import it in another script, sqrt is also defined within the module foo.

import foo    
dir(foo)

The output of which is

[..., # other things
 'foo',
 'sqrt']

How do I prevent this? i.e., either specify sqrt not to be exported, or export only specific functions - in this case, only the user-defined ones. I know for user-defined functions you can define them privately within the module by prefixing with an underscore, but in this case it's not a user-defined function so I can't define it with an underscore prefix.

like image 958
hatmatrix Avatar asked Jan 12 '13 16:01

hatmatrix


2 Answers

in this case it's not a user-defined function so I can't define it with an underscore prefix.

Yes, you can:

from math import sqrt as _sqrt

An alternative is to only import objects in function scopes, where you need them.

(While this may answer your question, I still have no idea why you'd want to do it. Both options are cumbersome and won't make your codebase look any better.)

like image 134
Kos Avatar answered Oct 11 '22 03:10

Kos


You can't, but it should never get in the way, it is bound to the foo namespace, as foo.sqrt. If you import sqrt from math it will be math.sqrt. That is the whole point of namespaces.

If you really want to avoid importing certain names, you might do this:

from foo import foo, bar, ...

like image 41
Fredrick Brennan Avatar answered Oct 11 '22 02:10

Fredrick Brennan