Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module and object names clash

Please consider the following Python modules excerpts:

foo.py:

class Foo:
  (...)

bar.py:

import foo

foo = foo.Foo()

The variable foo, which was a module object, is overwritten with a Foo object.

I know that I can use other names for the object, e.g.:

foobar = foo.Foo()

but semantically it makes more sense in my code to have it called foo, since it will be the only instance.

(I tried to workaround this by dropping classes and using modules only, but I went back to using classes because using modules only had "robustness" problems.)

This is kind of a philosophical question, but what is the "right" way of handling this potential object/module names clash?

like image 878
João M. S. Silva Avatar asked Apr 03 '13 23:04

João M. S. Silva


People also ask

What are the rules for naming a Python module?

Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Which variable names are illegal in Python?

Rules for Python variables: A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

Can two classes have same name in Python?

yes, if you define a class with the same name as an already existing class, it will override the definition. BUT existing instances of the first class will still behave as usual.

What is name clash in Python?

Name clashes can occur, for example, if two or more Python modules contain identifiers with the same name and are imported into the same program, as shown below: In this example, module1 and module2 are imported into the same program. Each module contains an identifier named double, which return very different results.


1 Answers

In my opinion there is nothing wrong with what you are currently doing, but to make it more clear for everyone reading the code I would suggest changing your 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 the name clash so it will be more obvious that the variable foo in your module is not going to refer to the module of the same name.

like image 158
Andrew Clark Avatar answered Oct 10 '22 09:10

Andrew Clark