0

If I try to pass a class "Human" to a method while defining the static attributes of that class, I get the error "Undefined variable: Human".

=>How can I access the current class (-name) to pass it to the shown method?

(In line 7 there is no instance of the class Human available. Therefore this is a different question than Getting the class name of an instance?)

I could pass the class name as hard coded string "Human" but I would like to avoid hard coded strings if possible.

Screenshot:

enter image description here

Human class:

from h_database_orm.domain.entity import Entity

class Human(Entity):   
    first_name = Entity.string()
    last_name = Entity.string()  

    spouse_id = Entity.foreign_key(Human)
    spouse = Entity.one_to_one_attribute(Human)

Parent class Entity:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Column, Integer, Float, String, ForeignKey
from sqlalchemy.orm import relation

class AbstractEntity():

    @declared_attr
    def __tablename__(self):
        return AbstractEntity.table_name_for_class(self)

    id = Column(Integer, primary_key=True) 

    @staticmethod
    def table_name_for_class(clazz):
        return clazz.__name__.lower()              

    @staticmethod
    def integer():       
        return Column(Integer) 

    @staticmethod
    def float():
        return Column(Float)  

    @staticmethod
    def string():
        return Column(String)           

    @staticmethod
    def foreign_key(referencedClass):
        table_name = AbstractEntity.table_name_for_class(referencedClass)
        foreign_key_path = table_name + '.id'
        return Column(Integer, ForeignKey(foreign_key_path))

    @staticmethod
    def one_to_one_attribute(referenced_class):
        class_name = referenced_class.__name__
        return relation(class_name, uselist=False)


Entity = declarative_base(cls=AbstractEntity)
Stefan
  • 10,010
  • 7
  • 61
  • 117
  • Can't you just change the staticmethod to a classmethod? For the caller it should make no difference. – Mike Scotty Jun 12 '19 at 13:12
  • I would like to use line 7 to define a static attribute "spouse_id". Would it be possible to define that static attribute within a class method? – Stefan Jun 12 '19 at 13:14
  • 1
    Hm, probably not, it would most likely still reference ``Entity`` instead of ``Human``. AFAIK, the class as such cannot be accessed from its own class attributes, because it does "not yet exist". – Mike Scotty Jun 12 '19 at 13:18

1 Answers1

0

Ugly work around ... but seems to work:

from h_database_orm.domain.entity import Entity

class Human(Entity):   
    first_name = Entity.string()

Human.last_name = Entity.string()  

Human.spouse_id = Entity.foreign_key(Human)
Human.spouse = Entity.one_to_one_attribute(Human)
Stefan
  • 10,010
  • 7
  • 61
  • 117