简体   繁体   中英

How do I return an expression in Python

I have a function that takes in a weird argument due to **kwargs

def create_record_table(Base, table_name, **kwargs):
  class RecordTable(Base):
      __tablename__ = table_name
      id = Column(Integer, primary_key=True)
      for key, value in kwargs.items():
          exec("{0} = {1}".format(key,value))
  return RecordTable

here is an example of someone calling this function

test = create_record_table(Base, "testtable", index="Column(String)")

I would like to create a function or a class that creates or return the index="Column(String)" part.

for example, a user could do this

index = Atomic("col_name", "String")
test = create_record_table(Base, "testtable", index)

or similarly:

index = Atomic("col_name", "Integer")
test = create_record_table(Base, "testtable", index)

How about:

def Atomic(col_name, col_type):
    return {'index': '%s(%s)' % (col_name, col_type)}

And then you need to call create_record_table like this:

kwargs = Atomic('testcol', 'String')
create_record_table(Base, 'testtable', **kwargs)

If you don't want to add ** before kwargs when calling create_record_table , you can change the declaration of create_record_table to this:

def create_record_table(Base, table_name, kwargs):

Now, you can call it just like this:

kwargs = Atomic('testcol', 'String')
create_record_table(Base, 'testtable', kwargs)

But in this way, it will make the create_record_table not compatible with the older code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM