0

I've inherited some code with imports in each function and using underscores for each module imported as below

def my_func():
    from foo import bar as _bar
    from spam import meat as _meat

    # Do some work

What is the point in the _bar? All imports are done like this.

deepak
  • 1,081
  • 12
  • 18
  • Maybe to distinguish them from other variables? Also useful if you’re paid by the keystroke. – Ry- Oct 02 '19 at 17:24
  • 1
    If you see this done at module scope, it suppresses those names from being exported as public. But here, within a function def, there is no point - since these name bindings are to local variables anyway. Probably the person who wrote the code is just not very experienced in Python. – wim Oct 02 '19 at 17:26
  • In addition to @Ry- it's possible there are other methods/variables with the same name, this could be a way of avoiding collisions, but if not, it's a bit off. – Phix Oct 02 '19 at 17:28
  • @wim So this could be worthwhile at the top of a file but not within a function? – jeff_27 Oct 02 '19 at 17:35
  • @jeff_27 Yes. But the more usual (and better) pattern is to define a module's public names explicitly using `__all__`. – wim Oct 02 '19 at 17:50

2 Answers2

1

If the actual names are things that exist as a part of the built in commands in python, this is done as a way to avoid shadowing those built in functions (for example - from mymodule import open would make the built in open which returns file handles inaccessble). Otherwise, it's simply convention for the original author.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
-1

I believe functions with name starting with a single underscore can't be imported using this line :

from module import *

for example this module :

def _some_function_1():
    pass
def some_function_2():
    pass

if you imported this module, you will be able to access only some_function_2()