繁体   English   中英

格式化可选文本字符串的更有效方法

[英]More efficient way of formatting optional text string

我已经写了这段代码:

@staticmethod
def __ver_upload_url(document_type, document_subtype=None):

    verification_base = 'verification/{0}/'.format(document_type)
    verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''

我想知道是否有一种更清洁,更Python化的方式来仅用一行来格式化URL路径。 我最初有:

verification_base = 'verification/{0}/{1}'.format(document_type, document_subtype) \
if document_subtype is not None else 'verification/{0}/'.format(document_type)

我认为它现在更干净,可读性更好,但也许还有更好的方法。

注意:我正在尝试为必须上载的Django文件生成路径,并且文件始终具有类型,但不总是具有子类型(如类别和子类别)。 我想添加一个子目录以仅在文件具有子类型的情况下指定该子类型,并且如果不将其保留在命名为类型的文件夹中。

编辑

我不得不升级我的功能,现在看起来像:

def verification_url(document_type, document_subtype=None, company=False, company_administrator=False):
    verification_base = 'verification/'
    verification_base += 'companies/' if company or company_administrator else ''
    verification_base += 'admins/' if company_administrator else ''
    verification_base += '{0}/'.format(document_type)
    verification_base += '{0}/'.format(document_subtype) if document_subtype is not None else ''

    def function(instance, filename):
        id = instance.id if company else instance.user.id
        return verification_base + '{user_id}/{filename}'.format(id=id, filename=filename)

我想知道我是否可以编写一个URL构建器,该构建器依赖于将插入到由斜杠限制的字符串中的元素列表,以减少代码的长度,或者至少使其可重用。

您对提高代码的效率/可扩展性有何建议?

您要合并的令牌的规则性建议基于join的方法:

bits = ('verification', 'companies', 'admins', document_type, document_subtype)
flags = (1, company or company_administrator, company_administrator, document_type, document_subtype)

verification_base = '/'.join([b for b, f in zip(bits, flags) if f]) + '/'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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