Python 3.8 introduced = specifier in f-strings (see this issue and pull request).
It allows to quickly represent both the value and the name of the variable:
from math import pi as π
f'{π=}'
# 'π=3.141592653589793'
I would like to use this feature on a pre-defined string with str.format():
'{π=}'.format(π=π)
However, it raises an exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'π='
Is there a way to make it work (e.g. with a special dunder method)?
Why it may be useful?
one could have a programmatic template for multiple values of the same variable (in a loop)
in contrasts, f-strings have to be hardcoded; think about internationalization
one could reference constants defined in a module in its docstring (module.__doc__.format(**vars(module));
workaround: define an f-string variable at the end of the module, overwrite the module.__doc__ at runtime.
Related
Am a newbie to Python. I have come across this code:
Xtrain is a pandas dataframe object with a shape of X train shape= (42000, 784)
But am able to call the python any() builtin function on the object returned by isnull function of a pandas dataframe
train = pd.read_csv(datapath+"/" +"train.csv")
X_train = train.drop(labels=["label"],axis=1)
X_train.isnull().any().describe()
I understood that builtin functions can be called directly from anywhere. Does the above mean that they are accessible to all objects also ? i.e. in some way every class inherits builtin functions ?
The comments already address the question, but for the sake of posting a solution...
builtin functions can be called from anywhere, on anything - though whether or not they will work depends on whether or not you are passing in a valid input for that function.
any is a builtin function.
HOWEVER.. in this case, you are actually working with an any method that belongs to the pd.DataFrame class.
try dir(pd.DataFrame) .. you will see any listed in there.
this means it's a function that belongs to the class (making it a method).
this is NOT the same as the builtin any.
Further proof...
import inspect
print(inspect.getfile(any))
output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\deden\AppData\Local\Continuum\anaconda3\lib\inspect.py", line 666, in getfile
type(object).__name__))
TypeError: module, class, method, function, traceback, frame, or code object was expected, got builtin_function_or_method
print(inspect.getfile(pd.DataFrame.any))
output
C:\Users\deden\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py
I'm just getting started with HarfBuzz, and have switched to using the GObject Introspection interface to explore its API. Everything has been easy so far, but I'm a bit confused with language_from_string, which has the following docstring:
language_from_string(str:list) -> HarfBuzz.language_t
i.e. in IPython, I do:
from gi.repository import HarfBuzz
?HarfBuzz.language_from_string
in vanilla Python, you can replace the last line with: print(HarfBuzz.language_from_string.__doc__) (or similar)
if I call this method with a string, e.g:
HarfBuzz.language_from_string('en')
I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Item 0: Must be number, not str
back, while if I convert to a list of code points first:
en = HarfBuzz.language_from_string(list(map(ord, 'en')))
the error goes away, and I get something useful back. e.g. I can do:
HarfBuzz.language_to_string(en)
and I get the expected en back, in a string.
HarfBuzz Issue #91 is about this method, but doesn't seem to be relevant.
You have to call it like HarfBuzz.language_from_string(b'en') (string but prefixed with b) in python3 as strings are not just sequence of bytes anymore in py3 unlike py2.
Do you know any gi API that gets an actual python representation of string in python3? If so let me know otherwise this is expected from HarfBuzz side.
Is is possible to monkeypatch PEP 461 functionality in to Python 3.0-3.4?
(I'm working on porting dulwich to python 3, and as it has a lot of protocol and file format code, it relies heavily on byte formatting.)
To monkeypatch it in, you would need to assign a relevant function to bytes.format. Trying it with a dummy function does this:
>>> bytes.format = lambda *s: None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'bytes'
So, no, you can't do this. You would need to modify the C code that creates the bytes class - at which point, you might as well just apply the patch from the relevant bug.
I am starting to play around with python a little, and as a novice i tried this:
>>> s="";str=""
>>> for x in [ 1,2,3,4,5,6 ] :
... s += str(x)
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
TypeError: 'str' object is not callable
I accidentally declared a variable called str (str is supposed to be a function).
Assuming it would break the semantics too much, even in a dynamically
typed language, is there a namespace i can use to qualify methods
like str and ensure this does not happen or make it difficult?
This is what import <module> instead of from <module> import * is used for. As long as you use str in the only meaning of local variable value in <module>, you can use
module.str elswhere, without mangling namespace.
The only tokens that can't be clashed are keywords. This is intended functionality and there is no way to prevent this: everything is an object in Python
You might want to use some IDE tools, p.ex. Eclipse+PyDev, that checks your code and warn for possible errors.
As per your question you have already defined str=""
so when you will call str method which converts values into string it will not call actual method in place of that it will call str="".
that's why you are getting error because you can not call a str object to convert int to string.
Can I use type as a name for a python function argument?
def fun(name, type):
....
You can, but you shouldn't. It's not a good habit to use names of built-ins because they will override the name of the built-in in that scope. If you must use that word, modify it slightly for the given context.
While it probably won't matter for a small project that is not using type, it's better to stay out of the habit of using the names of keywords/built-ins. The Python Style Guide provides a solution for this if you absolutely must use a name that conflicts with a keyword:
single_trailing_underscore_: used by
convention to avoid conflicts with
Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
You can, and that's fine. Even though the advice not to shadow builtins is important, it applies more strongly if an identifier is common, as it will increase confusion and collision. It does not appear type will cause confusion here (but you'll know about that more than anyone else), and I could use exactly what you have.
You can use any non-keyword as an identifier (as long as it's a valid identifier of course). type is not a keyword, but using it will shadow the type built-in.
You can, but you would be masking the built-in name type. So it's better not to do that.
You can use _type for that. For example:
def foo(_type):
pass
If you use type, you can't use type() in that function. For example:
>>> type('foo')
<type 'str'>
>>> type = 'bar'
>>> type('foo')
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'str' object is not callable