5

Unlike in other languages like C#, there is no way to import an empty string from Python standard library. However, there is a built-in function str(), which defaults to an empty string when no argument was supplied.

What would be the pros and cons of using str()--compared to '' or empty_str = ''--to denote an empty string? I guess the overhead would be negligible, and it is as readable as '' or "". For one thing, it is visually clear that the variable is a str even in Notepad. One obvious disadvantage is that you have to type the keyboard a few more times than '' although not as many as empty_str. Can you think of any other merits or demerits?

3
  • From the docs it defaults to returning '' so the negligible constant time check to see if object was passed shouldn't matter. I declare empty string variables as var = '' because only assignment needs to occur. Commented Dec 19, 2018 at 8:12
  • 1
    "For one thing, it is visually clear that the variable is a str even in Notepad" - you really shouldn't be writing your code in Notepad. Commented Dec 19, 2018 at 8:28
  • 2
    I'm voting to close this question as primarily opinion based since there are no purely technical reasons to choose or the other (even if the general idiom is to use a string literal here). Commented Dec 19, 2018 at 9:05

2 Answers 2

4

It has exactly the same effect, and '' (or "") should be used (similar [] for list, and () for tuple, {} for dict).

And Python will indeed have an internal global cache for small constants (short strings, including the empty string, and small numbers). Check that by id('') or id(0), it will very likely always return the same. (This is implementation specific, but CPython will behave this way.)

Sign up to request clarification or add additional context in comments.

Comments

2

Use s = ''.

First, Python itself is not the fastest language in universe, and Python developers are not supposed to make such kind of optimization, like creating global variables for empty constants or optimizing variable initialization with constants. Your code will be considered as not maintainable, because others would not understand your purpose.

Second, any static code analyzer will always understand the type of your variable from a constant. But when function is called, analyzer has to find the declaration and get the return value type. I dont speak about str() - as a builtin, it's return type is well known to analyzers. But in general approach is not good, because in Python programmers not always explicitly define the return value type of functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.