9

I'm wonder why this simple code doesn't work.

In main.py I have

def foo():
    HTTPHelper.setHost("foo")
    host = HTTPHelper.host()

and in HTTPHelper.py:

_host = None
def setHost(host):
    _host = host
def host():
    return _host

But when I step through foo() host becomes NoneType, even though I set it on the line before. Very confused...

dutt
  • 7,909
  • 11
  • 52
  • 85

2 Answers2

9

Glenn's answer will fix your immediate issue from within a module, but for the sake of giving a man a fishing pole rather than a fish: Short Description of the Scoping Rules?

You'd do well reading on scopes and Python's LEGB rule. Scope and domain of existence concepts also apply to programming and analysis in general, and will be worth the time spent understanding the concepts.

It's also worth noting that if you're treating such things as objects (and what you write makes it seem like you intend to), you should be writing a class and set its attributes, and not global variables that you handle after a module import.

Community
  • 1
  • 1
  • I gave him a picture of a fish, and expected him to do his own research to learn how to build his own fishing pole--the `global` keyword and a search engine should be enough for him to find the rest. – Glenn Maynard Oct 06 '10 at 02:55
  • Fair enough, I meant no offense or slant on your reply with mine btw, was just noting why another reply to the same subject. –  Oct 06 '10 at 03:17
  • 1
    Thanks for the tips. I'm was aware of how this should be designed and it's a proper class now, I was working on another part and just wanted something quick that worked and got really bugged out when something simple as that it didn't. I'm new to python, not that new to programming. Working in Python, C++, C#, PHP in the same project messes up your syntax-mind :) – dutt Oct 06 '10 at 04:07
5
def setHost(host):
    global _host
    _host = host
Glenn Maynard
  • 55,829
  • 10
  • 121
  • 131