In python how can I use/manipulate an object defined in a script from a function defined in an imported module?
Question: This might be a terribly simple one, but I don't know what's the "right"
answer. Assume that I have a script

    
    
    import utils
    bar = 1
    utils.foo()
    print bar
    

Furthermore, the module `utils` is:

    
    
    def foo():
      bar = bar+1
    

As given above, I ,obviously, get:

    
    
    UnboundLocalError: local variable 'bar' referenced before assignment
    

**How can I use`bar` inside `foo()`?** In my specific case, I don't really
want to alter `foo`, but I _do_ need to be able to use it and its state inside
`foo()`.

One workaround would be to pass `bar` to `foo()`:

    
    
    def foo(bar):
        return bar+1
    

And replace the third line in the script: `bar = utils.foo(bar)`.

However, this feels like a cumbersome solution; in particular if bar is a
complex object.

I am interested in a _best-practice_ approach the case described above.


Answer: Why don't you want to alter foo? If you import a module, you want to use its
functionality. If the foo function is without parameters, then bar or other
variables in it are used in the module utils itself. If you want to use a
function with values that are not inside the module, then:

    
    
    def foo(bar):
        return bar+1
    

is totally acceptable.

EDIT: // When you create class foo1, just set bar in the constructor. class
foo1: def **init**(self, bar): self.bar = bar

Image this situation:

    
    
    import someModule
    
    # now you want to use a function of this module
    foo()
    

Maybe then there would be an error like: bar is not defined or whatever -->
modules are not loosely coupled. Either make the function foo as you proposed
with parameters (totally acceptable) or set the bar value via a constructor or
setBar method.

