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.
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.)
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, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With