Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class and Module with the same name - how to choose one or another?

I have encountered following situation:

There is

ModuleA::ModuleB::ClassC.do_something

in the definition of do_something I need to use model from the application

def do_something
...
    data = Order.all
...
end

But there also exists a module

ModuleA::Order

So I get an error

undefined method `all' for ModuleA::Order:Module

I found a solution by doing

def do_something
...
    data = Kernel.const_get('Order').all
...
end

That returns the model. My question is: what's the best way to do it? is there a cleaner solution? (despite the fact, that having the same name for Class and Module it's not the greatest idea, but it cannot be changed here...)

like image 746
santuxus Avatar asked Feb 09 '11 15:02

santuxus


People also ask

Can a module and class have the same name?

Class and Module can not be of same name (Example)

Can two different packages have modules with same name?

This is not possible with the pip. All of the packages on PyPI have unique names. Packages often require and depend on each other, and assume the name will not change. Even if you manage to put the code on Python path, when importing a module, python searches the paths in sys.

Is module and class the same?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

Can we have more than one class with the same name in Python?

Python classes store the names of their methods within the internal dictionary known as . __dict__ that holds class namespace. Similar to the other Python dictionary . __dict__ can't contain repeated keys, which means we cannot have more than one method with the same name within the same class.


1 Answers

Prefix the class name with :: in the do_something method...

def do_something
...
    data = ::Order.all
...
end
like image 199
idlefingers Avatar answered Oct 24 '22 18:10

idlefingers