pablowilks2
pablowilks2

Reputation: 339

Is it possible to set a Metaclass globally so it applies to all classes created by default?

I get that a metaclass can be substituted for type and define how a newly created class behaves.

ex:

class NoMixedCase(type):
   def __new__(cls,clsname,base,clsdict):
       for name in clsdict:
          if name.lower() != name:
              raise TypeError("Bad name.Don't mix case!")
       return super().__new__(cls,clsname,base,clsdict)

class Root(metaclass=NoMixedCase):
    pass

class B(Root):
    def Foo(self): #type error
        pass

However, is there a way of setting NoMixedCase globally, so anytime a new class is created it's behavior is defined by NoMixedCase by default, without havining to inherit from Root?

So if you did...

Class B:  
    def Foo(self):
        pass

...it would still check case on method names.

Upvotes: 0

Views: 44

Answers (1)

jsbueno
jsbueno

Reputation: 110271

As for your question, no, it it is not ordinarily - and possibly not even some extra-ordinary thng that will work for this - a lot of CPythons inner things are tied to the type class, and hardcoded to it.

What is possible of trying, without crashing the interpretrer right away, would be to write a wrapper for type.__new__ and use ctypes to replace it directly in type.__new__ slot. (Ordinary assignment won't do it). You'd probably still crash things.

So, in real life, if you decide not to go via a linter program with a plug-in and commit hooks as I suggested in the comment above, the way to go is to have a Base class that uses your metaclass, and get everyone in your project to inherit from that Base.

Upvotes: 1

Related Questions