小编Mar*_*son的帖子

在 github actions 中什么时候应该使用单花括号和双花括号来引用变量?

我开始学习 github actions(从 jenkins piplines 转换)。我对 yaml 不是很熟悉。

我无法弄清楚何时或为何应使用双花括号与单花括号引用变量。我感觉这里有一个重要的区别......你能告诉我吗?

name: sample
on:
  workflow_dispatch
env:
  MY_VAR: "something"

jobs:
  do_things:
    runs-on: ubuntu-latest
    steps:
      - name: "Step 1"
        run: echo "${MY_VAR}"
      - name: "Step 2"
        run: echo "${{env.MY_VAR}}"

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

github-actions

27
推荐指数
1
解决办法
6556
查看次数

这个循环可以实现Pythonic列表理解吗?

我与列表理解有一种爱/恨的关系.一方面我认为它们整洁优雅.另一方面,我讨厌阅读它们.(特别是那些我没写的)我通常遵循规则,让它可读,直到需要速度.所以我的问题在这一点上确实是学术性的.

我想要一张表格中的电台列表,这些电台的字符串通常有额外的空格.我需要剥掉那些空间.有时这些站是空白的,不应包括在内.

stations = []
for row in data:
    if row.strip():
        stations.append(row.strip())
Run Code Online (Sandbox Code Playgroud)

这转化为这个列表理解:

stations = [row.strip() for row in data if row.strip()]
Run Code Online (Sandbox Code Playgroud)

这种方法效果很好,但我发现我正在做两次剥离.我猜测.strip()实际上并不需要两次,并且通常比分配变量慢.

stations = []
for row in data:
    blah = row.strip()
    if blah:
        stations.append(blah)
Run Code Online (Sandbox Code Playgroud)

事实证明我是对的.

> Striptwice list comp 14.5714301669     
> Striptwice loop 17.9919670399
> Striponce loop 13.0950567955
Run Code Online (Sandbox Code Playgroud)

Timeit显示在两个循环段之间,第二个(条带一次)更快.这里没有真正的惊喜.令我感到惊讶的是,列表理解只是略微慢一些,即使它正在做两次.

我的问题:有没有办法写一个列表理解,只做一次剥离?



结果:

以下是建议的时间结果

# @JonClements & @ErikAllik
> Striptonce list comp 10.7998494348
# @adhie
> Mapmethod loop 14.4501044569
Run Code Online (Sandbox Code Playgroud)

python loops list-comprehension

15
推荐指数
2
解决办法
840
查看次数

是否可以在数据类中使用*args?

我最近开始使用数据类,它们将是3.7的一个很好的补充.我很好奇是否或如何使用数据类重新创建此类的相同功能.

class Nav(object):
    def __init__(self, name:str, menu, page, *submenus):
        self.name = name
        self.menu = menu
        self.page = page
        self.submenus = submenus

foo = Nav("name", "menu", "page")
Run Code Online (Sandbox Code Playgroud)

这不起作用.提出例外TypeError: __init__() missing 1 required positional argument: 'submenus'

@dataclass
class Nav(object):
    name:str
    menu: Any
    page: Any
    submenus: tuple

foo = Nav("name", "menu", "page")
Run Code Online (Sandbox Code Playgroud)

我假设这是因为该类没有指令来解析参数. 有没有办法指示数据类装饰器需要解压缩子菜单?

python python-3.x python-dataclasses

13
推荐指数
1
解决办法
860
查看次数

日期时间字符串格式对齐

在Python 2.7中,我想使用字符串格式的模板打印日期时间对象.由于某些原因,使用左/右对齐不能正确打印字符串.

import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l)  #print items in the list using template
Run Code Online (Sandbox Code Playgroud)

这将导致:

>25 >25
Run Code Online (Sandbox Code Playgroud)

代替

  2013-06-26 09:00:00       2013-06-26 09:00:00
Run Code Online (Sandbox Code Playgroud)

是否有一些技巧使用字符串格式模板打印日期时间对象?

当我强制将datetime对象强制为str()时似乎有效

print template.format(str(l[0]), str(l[1]))
Run Code Online (Sandbox Code Playgroud)

但我宁愿不必这样做,因为我正在尝试打印一个值列表,其中一些不是字符串.制作字符串模板的重点是打印列表中的项目.

我是否遗漏了有关字符串格式的内容,或者这对任何人来说都像是一个python bug?


@mgilson指出了我在文档中遗漏的解决方案.链接

目前支持两个转换标志:'!s'在值上调用str(),'!r'调用repr().

一些例子:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
Run Code Online (Sandbox Code Playgroud)

python datetime string-formatting

9
推荐指数
1
解决办法
966
查看次数

如何在 PyCharm 中将所有单引号字符串转换为双引号字符串?

我想做一些代码清理,并使模块中的所有字符串一致地用双引号引起来。我的问题是它们有很多,手动浏览(alt+enter、箭头、enter)很乏味,而且我的正则表达式-Fu 很弱。(不断遇到奇怪的情况,其中单引号出现在文档字符串等中)

在 Pycharm 中是否有一些更快的方法将所有单引号字符串转换为双引号字符串?

python pycharm

8
推荐指数
3
解决办法
7068
查看次数

使用 types.FunctionType 与打字.Callable 的类型提示注释?

使用types.FunctionTypeTyping.Callable作为类型提示注释有何缺点或优点?

考虑下面的代码...

import types
import typing

def functionA(func: types.FunctionType):
    rt = func()
    print(func.__name__)
    return rt

def functionB(func: typing.Callable):
    rt = func()
    print(func.__name__)
    return rt
Run Code Online (Sandbox Code Playgroud)

我能看到的唯一区别是Callable可以是任何类型的可调用对象(函数、方法、类等),而FunctionType仅限于函数。
我是否忽略了什么?在某些情况下使用FunctionTypeover有好处吗?Callable

python type-hinting pycharm python-3.x

8
推荐指数
1
解决办法
3153
查看次数

grequest多个request.session池?

我想为REST webserivce做很多url requets.通常在75-90k之间.但是,我需要限制与Web服务的并发连接数.

我开始以下面的方式玩弄问候,但很快就开始咀嚼打开的插座.

concurrent_limit = 30
urllist = buildUrls()
hdrs = {'Host' : 'hostserver'}
g_requests = (grequests.get(url, headers=hdrs) for url in urls)
g_responses = grequests.map(g_requests, size=concurrent_limit)
Run Code Online (Sandbox Code Playgroud)

由于运行了一分钟左右,我遇到了"达到最大插槽数"错误.据我所知,grequests中的每个requests.get调用都使用它自己的会话,这意味着为每个请求打开一个新的套接字.

我在github上找到了一条关于如何让grequest使用单个会话的注释.但这似乎有效地将所有请求瓶颈到一个共享池中.这似乎打败了异步http请求的目的.

s = requests.session()
rs = [grequests.get(url, session=s) for url in urls]
grequests.map(rs)
Run Code Online (Sandbox Code Playgroud)

是否可以以创建多个会话的方式使用grequests或gevent.Pool?

换句话说:如何通过排队或连接池来创建许多并发的http请求?

python sockets gevent grequests

7
推荐指数
1
解决办法
5709
查看次数

将mock.patch.object 与wraps 和side_effect一起使用有什么区别吗?

下面两个测试有什么区别? (如果有的话)

**在 python 3.10 中

import unittest
from unittest.mock import Mock, patch

class Potato(object):
    def spam(self, n):
        return self.foo(n=n)

    def foo(self, n):
        return self.bar(n)

    def bar(self, n):
        return n + 2

class PotatoTest(unittest.TestCase):
    def test_side_effect(self):
        spud = Potato()
        with patch.object(spud, 'foo', side_effect=spud.foo) as mock_foo:
            forty_two = spud.spam(n=40)
            mock_foo.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)

    def test_wraps(self):
        spud = Potato()
        with patch.object(spud, 'foo', wraps=spud.foo) as mock_foo:
            forty_two = spud.spam(n=40)
            mock_foo.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)
Run Code Online (Sandbox Code Playgroud)

一个用于side_effect保留原始方法,而另一个用于wraps有效地做同样的事情(或者至少据我所知)。

python python-mock python-3.10

7
推荐指数
0
解决办法
679
查看次数

结合memoization和尾调用优化

我最近了解了一种使用装饰器来记忆递归函数的强大方法.
"嘿,这很整洁,让我们玩吧!"

class memoize:
    """Speeds up a recursive function"""
    def __init__(self, function):
        self.function = function
        self.memoized = {}

    def __call__(self, *args):
        try:
            return self.memoized[args]
        except KeyError:
            self.memoized[args] = self.function(*args)
            return self.memoized[args]
#fibmemo
@memoize
def fibm(n, current=0, next=1):
    if n == 0:
        return current
    else:
        return fibm(n - 1, next, current+next)
Run Code Online (Sandbox Code Playgroud)

timeit表明这确实加速了算法:

fibmemo     0.000868436280412
fibnorm     0.0244713692225
Run Code Online (Sandbox Code Playgroud)

"哇,这可能真的很有用!我想知道我可以推动多远?"
我发现当我开始使用高于140的输入时,我很快就遇到了RuntimeError: maximum recursion depth exceeded."啊糟透了.."

经过一番搜索,我发现了一个似乎可以解决问题的黑客攻击.
"这看起来也很整洁!让我们玩吧"

class TailRecurseException:
    def __init__(self, args, kwargs): …
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
1
解决办法
615
查看次数

如何找到字符串中未转义的单花括号的索引位置?

a = "a"
sample_string = "asdf {{a}} {{ { {a} { {a} }"
## need to find these brackets ^     ^     ^
print(sample_string.format(a=a))
Run Code Online (Sandbox Code Playgroud)

上面的字符串将引发

ValueError: unexpected '{' in field name
Run Code Online (Sandbox Code Playgroud)

我希望能够摆脱令人窒息的大括号_string.formatter_parser。我开始沿着寻找所有不匹配对的道路走下去,但意识到这对于双转义花括号不起作用。我意识到我不知道如何解决这个问题。

ValueError: unexpected '{' in field name
Run Code Online (Sandbox Code Playgroud)

我知道我不能简单地寻找单个牙套而不查看它们是否也配对。我不能在查看它们是否逃脱之前就先寻找它们。但有些情况让我感到困惑,如下所示:

## this does not solve the problem.
def find_unmatched(s):
    indices = []
    stack = []
    indexstack = []
    for i, e in enumerate(s):
        if e == "{":
            stack.append(e)
            indexstack.append(i)
        elif e == "}":
            if len(stack) < 1:
                indices.append(i)
            else:
                stack.pop() …
Run Code Online (Sandbox Code Playgroud)

python string

5
推荐指数
1
解决办法
588
查看次数