Q: How does python know what the value of __name__ should be?
Well, if you write import foo Python will look for a module named 'foo' and set its name to 'foo'.
  Q: Can a module tell that it's being imported, ...
Yes, it can. Usually people do that with if __name__ == '__main__' -- if the test passes, it generally means that the module is being executed, if it fails it generally means that it is being imported.
A particular case where this test will fail is when you have a module named __main__ (in a file named __main__.py).
If you want to be 100% more sure, you can inspect the frames and see if the module is on top of the stack:
f = sys._getframe()
if f.f_back is None:
    # We're at the top of the stack: this module is being executed.
else:
    # There's a frame on top of us: this module has been imported.
  Q: ... and set the __name__ attribute accordingly?
And yes, you can change __name__ to whatever you want by simply setting it:
__name__ = 'bar'
Although there's no reason to do so, other than generating confusion and possibly introducing bugs.
     
    
__name__is the name of the module.