Python and object name names

Note the following Python module snippets:

foo.py:

class Foo: (...) 

bar.py:

 import foo foo = foo.Foo() 

The variable foo, which was the module object, is overwritten by the Foo object.

I know that I can use other names for the object, for example:

 foobar = foo.Foo() 

but semantically it makes sense in my code to call it foo, as it will be the only instance.

(I tried to work around this by dropping classes and using only modules, but I returned to using classes because using modules had "stability" issues.)

This is a kind of philosophical question, but what is the โ€œrightโ€ way to handle these potential names of object / module names?

+6
source share
2 answers

In my opinion, there is nothing wrong with what you are doing now, but to make it easier for everyone reading the code, I would suggest changing the code to something like the following:

 import foo as foo_mod foo = foo_mod.Foo() 

Or alternatively:

 from foo import Foo foo = Foo() 

This prevents name collisions, so it will be more obvious that the foo variable in your module will not refer to a module with the same name.

+6
source

I also approve of the following style now:

 import foo my_foo = foo.Foo() 

I prefer this because it leaves the module names unchanged and they are more global and sacred than local variables.

0
source

All Articles