最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

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

Python crifan 4985浏览 0评论

python 3.4中,代码:

<code>print("type(self.config)=%s" % (type(self.config)))
self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)
</code>

出错:

<code>    self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)
                                                   ^
SyntaxError: invalid syntax
</code>

而调试期间,在前面已经打印,确定此处的config,的确是dict:

<code>type(config)=&lt;class 'dict'&gt;, type(self.config)=&lt;class 'dict'&gt;
</code>

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

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

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

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

python ** 两个星号

python函数参数前面单星号(*)和双星号(**)的区别 – Arkenstone – 博客园

“单星号(*):*agrs

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

Python 参数知识(变量前加星号的意义) – CSDN博客

Python星号操作符的作用 – CSDN博客

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

python ** dict not work

update method of python dictionary did not work – Stack Overflow

python **  syntax error

Invalid syntax-error with print(*args, **kwargs) · Issue #1027 · PyCQA/pylint

python double asterisk syntax error

python – What does ** (double star/asterisk) and * (star/asterisk) do for parameters? – Stack Overflow

4. More Control Flow Tools — Python 3.8.0a0 documentation

Carlos Isaac Balderas

一直都找不到错误原因。

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

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

看来是:

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

换成:

<code>self.config["cursorclass"] = pymysql.cursors.DictCursor
self.connection = pymysql.connect(**self.config)
</code>

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

【总结】

作为一个dict类型的变量,前面加上2个星号,去传递给函数:

<code>self.connection = pymysql.connect(**self.config, cursorclass=pymysql.cursors.DictCursor)
</code>

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

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

-〉Python3.5之后支持:

<code>someFuntion(**someDict, otherParameter)
</code>

的写法

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

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的虚拟环境。

而此处,解决办法很简单,改为:

<code>self.config["cursorclass"] = pymysql.cursors.DictCursor
self.connection = pymysql.connect(**self.config)
</code>

即可消除语法错误。

转载请注明:在路上 » 【已解决】Python中两个星号**参数去传递给函数出错:SyntaxError invalid syntax

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.179 seconds, using 22.12MB memory