Use of a deprecated module 'string'
I just ran pylint
on my code and it shows up this message:
Uses o开发者_如何学Cf a deprecated module 'string'
I am using the module string
for join / split mainly.
>>> names = ['Pulp', 'Fiction']
>>> import string
>>> fullname = string.join(names)
>>> print fullname
Pulp Fiction
Above is an example. In my code I have to make use of split
and join
a lot and for that I was using the string
module.
Has this been deprecated? If yes, what is the way to handle split/ join in Python 2.6? I have tried searching but I could not find myself being clear so I asked here.
Equivalent to your code would be:
' '.join(names)
string
is not deprecated, deprecated are certain functions that were duplicates of str
methods. For split
you could also use:
>>> 'Pulp Fiction'.split()
['Pulp', 'Fiction']
In docs there is a full list of deprecated functions with suggested replacements.
not all functions from "strings" are deprecated. if you want to use a function from strings which is not deprecated, then remove a string from deprecated-modules configuration in pylint config.
[IMPORTS]
deprecated-modules=string
I used to call split
, join
and strip
as methods of string objects until one day I needed to make a script more efficient.
Profiling using cProfile
showed me that a lot of time was spent on these method calls. Performance tips suggested me to instead make a "copy" of these methods in my scope to avoid this:
split = str.split
join = str.join
for _ in xrange(1000000):
print join("_", split("Pulp Fiction"))
If I remember well, the trick indeed resulted in performance gains.
However, if I need these string manipulation functions in several functions, I make these copies in the "global scope" of my program (not sure this is the correct way to say it). pylint
then complains that I'm not using the correct convention for naming my variables:
Invalid name "split" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
So I end up naming them with capital letters:
SPLIT = str.split
JOIN = str.join
def main():
for _ in xrange(1000000):
print JOIN("_", SPLIT("Pulp Fiction"))
It's a bit ugly, though.
Sometimes I forget about the possibility to make copies and do imports:
from string import split, join
And then I get the Uses of a deprecated module 'string'
warning.
精彩评论