p.exists() p.is_dir() p.parts() p.with_name('sibling.png') # only change the name, but keep the folder p.with_suffix('.jpg') # only change the extension, but keep the folder and the name p.chmod(mode) p.rmdir()
类型提醒: Type hinting
在Pycharm中,类型提醒是这个样子的:
类型提醒在复杂的项目中可以很好的帮助我们规避一些手误或者类型错误,Python2的时候是靠IDE来识别,格式IDE识别方法不一致,并且只是识别,并不具备严格限定。例如有下面的代码,参数可以是numpy.array , astropy.Table and astropy.Column, bcolz, cupy, mxnet.ndarray等等。
1 2 3 4 5 6
defrepeat_each_entry(data): """ Each entry in the data is doubled <blah blah nobody reads the documentation till the end> """ index = numpy.repeat(numpy.arange(len(data)), 2) return data[index]
同样上面的代码,传入pandas.Series类型的参数也是可以,但是运行时会出错。
1
repeat_each_entry(pandas.Series(data=[0, 1, 2], index=[3, 4, 5])) # returns Series with Nones inside
# Python 3 _print = print# store the original print function defprint(*args, **kargs): pass# do something useful, e.g. store output to some file
再比如下面的代码
1 2 3 4 5 6 7 8 9 10 11
@contextlib.contextmanager defreplace_print(): import builtins _print = print# saving old print function # or use some other function here builtins.print = lambda *args, **kwargs: _print('new printing', *args, **kwargs) yield builtins.print = _print
with replace_print(): <code here will invoke other print function>
# Python 3.6+, how it *can* be done, not supported right now in pytorch model = nn.Sequential( conv1=nn.Conv2d(1,20,5), relu1=nn.ReLU(), conv2=nn.Conv2d(20,64,5), relu2=nn.ReLU()) )
Iterable unpacking
1 2 3 4 5 6 7 8 9
# handy when amount of additional stored info may vary between experiments, but the same code can be used in all cases model_paramteres, optimizer_parameters, *other_params = load(checkpoint_name)
# picking two last values from a sequence *prev, next_to_last, last = values_history
# This also works with any iterables, so if you have a function that yields e.g. qualities, # below is a simple way to take only last two values from a list *prev, next_to_last, last = iter_train(args)
x = dict(a=1, b=2) y = dict(b=3, d=4) # Python 3.5+ z = {**x, **y} # z = {'a': 1, 'b': 3, 'd': 4}, note that value for `b` is taken from the latter dict.