当前位置:   article > 正文

python中syntaxerror_【已解决】Python中两个星号**参数去传递给函数出错:SyntaxError invalid syntax...

python version < 3.5 do not allow keyword arguments after **expression

python 3.4中,代码:print("type(self.config)=%s" % (type(self.config)))

self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)

出错:    self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)

^

SyntaxError: invalid syntax

而调试期间,在前面已经打印,确定此处的config,的确是dict:type(config)=<class 'dict'>, type(self.config)=<class 'dict'>

但是为何语法出错,还是不懂为何。

因为同样的代码,之前在Mac本地调试的时候,是好好的。

然后上传到服务器上,才出错的。

所以以为是2个星号方面的问题呢

python ** 两个星号

“单星号(*):*agrs

将所以参数以元组(tuple)的形式导入:”

“单星号就是起到将元组“解包””

python ** dict not work

python **  syntax error

python double asterisk syntax error

一直都找不到错误原因。

无意间看到,PyCharm中,其实早已有语法错误提示了:

864cda483461349e721104b356a066cf.png

Python version < 3.5 not allow keyword argument after **exception

看来是:

此处的Python 3.4中,版本小于3.5,不支持**someDictOrTuple之后,再跟着其他参数的写法

换成:self.config["cursorclass"] = pymysql.cursors.DictCursor

self.connection = pymysql.connect(**self.config)

结果就好了,没有语法错误了。

【总结】

作为一个dict类型的变量,前面加上2个星号,去传递给函数:self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)

之前在Mac本地,用PyCharm调试时是没有问题的

-》因为当时Mac中的Python版本是虚拟环境中安装的Python 3.6

-〉Python3.5之后支持:someFuntion(**someDict, otherParameter)

的写法

而同样代码上传到服务器中,结果却报错:

SyntaxError: invalid syntax

原因是:

服务器中Python是3.4版本,小于3.5,不支持这种写法。

而之所以服务器中,不是和本地一样的虚拟环境中python的3.6版本一样,是因为:

pipenv去install,尝试复制同样的虚拟环境时,发现服务器中只有python 3.4的

所以就暂时忽略python 3.4和3.6的区别,继续正常作为虚拟环境去使用了。

-》也可以看出pipenv的一个缺点:

在本地Mac已经安装了Python3.6的情况,去创建的虚拟环境后,

想要迁移到服务器中,其之前已经安装了Python3.4的前提下,则无法用pipenv复制同样的python 3.6的虚拟环境。

而此处,解决办法很简单,改为:self.config["cursorclass"] = pymysql.cursors.DictCursor

self.connection = pymysql.connect(**self.config)

即可消除语法错误。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/914721
推荐阅读
相关标签
  

闽ICP备14008679号