Re: EAFP
On 13/05/2022 18:37, bryangan41 wrote:
Is the following LBYL:foo = 123if foo < 200: do()If so, how to change to
EAFP?Thanks!Sent from Samsung tablet.
The distinction between look-before-you-leap and
easier-to-ask-forgiveness-than-permission is weaker than yo might expect.
When you write
filename = ...
if exists(filename):
with open(filename) as instream:
# do stuff
else:
# fallback
there are two checks for the file's existence, one explicit, and one
implicitly inside open() -- and worse, the first, explicit, check is
unreliable because between exists() and open() there is a small delay
that may be sufficient to create or delete the file. Therefore the
recommended (EAFP) version of the above is
filename = ...
try:
with open(filename) as instrem:
# do stuff
except FileNotFoundError
# fallback
or just
with open(filename) as instream:
# do stuff
if there is no meaningful fallback.
Regarding your example code, whether you can write an EAFP version for
if foo < 200:
do()
depends on the contents of do(). If do() fails in a well-defined way,
let's say by raising a FooAbove199 exception you can write just
do()
or, if you need a fallback
try:
do()
except FooAbove199:
# fallback
Note that if you change do() from
do():
# do stuff
to
def do():
if foo < 200:
# do stuff
else:
raise FooAbove199(f"Invalid {foo=!r}")
the
do()
invocation becomes EAFP even though you are actually performing the same
test as before.
--
https://mail.python.org/mailman/listinfo/python-list
Python
Hello, in coding, may be is a question of transivity in this code line. Thank you. Philippe -- https://mail.python.org/mailman/listinfo/python-list
Re: tail
On Fri, 13 May 2022 at 12:49, <[email protected]> wrote: > > On 2022-05-13 at 12:16:57 +0200, > Marco Sulla wrote: > > > On Fri, 13 May 2022 at 00:31, Cameron Simpson wrote: > > [...] > > > > This is nearly the worst "specification" I have ever seen. > > > You're lucky. I've seen much worse (or no one). > > At least with *no* documentation, the source code stands for itself. So I did it well to not put one in the first time. I think that after 100 posts about tail, chunks etc it was clear what that stuff was about and how to use it. Speaking about more serious things, so far I've done a test with: * a file that does not end with \n * a file that ends with \n (after Stefan test) * a file with more than 10 lines * a file with less than 10 lines It seemed to work. I've only to benchmark it. I suppose I have to test with at least 1 GB file, a big lorem ipsum, and do an unequal comparison with Linux tail. I'll do it when I have time, so Chris will be no more angry with me. -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Mon, 16 May 2022 17:22:17 -0700 (PDT), "[email protected]" declaimed the following: > >I tried with the repr() method as follows, but it doesn't give any output: I have no idea what 50% of those libraries are supposed to do, and am not going to install them just to try out your posted code. If you really want such help, post the MINIMUM example code the produces your problem. >a=str(strmat(lst)) >a=re.sub(r"'","",a) Explain what you believe this operation is doing, show us the input and the output. The best I can make out of that is that it is looking for single quote characters within whatever "a" is, and replacing them with nothing. Something much more understandable, without invoking a regular expression library (especially when neither the search nor the replacement terms are regular expressions) with simple string operations... stripped = "".join(quoted.split("'")) You also don't need to specify RAW format for the "'" -- Python is quite happy mixing single and double quotes (that is: single quotes inside a string using double quotes, double quotes inside a string using single quotes, either inside strings using triply quoted delimiters) >>> "'" "'" >>> '"' '"' >>> """'"'""" '\'"\'' >>> '''"'"''' '"\'"' >>> (Note that the interactive console displays results using repr(), and hence escapes ' that are internal to avoid conflict with the ones wrapping the output) >>> repr('''"'"''') '\'"\\\'"\'' >>> str('''"'"''') '"\'"' >>> print('''"'"''') "'" >>> The print() operation does not wrap the output with extraneous quotes. -- Wulfraed Dennis Lee Bieber AF6VN [email protected]://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Mon, 16 May 2022 02:03:26 -0700 (PDT), "[email protected]" declaimed the following: >print(lst) Printing higher level structures uses the repr() of the structure and its contents -- theoretically a form that could be used within code as a literal. If you want human-readable str() you will need to write your own output loop to do the formatting of the structure, and explicitly print each item of the structure. -- Wulfraed Dennis Lee Bieber AF6VN [email protected]://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Tuesday, May 17, 2022 at 8:48:27 AM UTC+8, Dennis Lee Bieber wrote: > On Mon, 16 May 2022 17:22:17 -0700 (PDT), "[email protected]" > declaimed the following: > > > > > >I tried with the repr() method as follows, but it doesn't give any output: > I have no idea what 50% of those libraries are supposed to do, and am > not going to install them just to try out your posted code. If you really > want such help, post the MINIMUM example code the produces your problem. > > >a=str(strmat(lst)) > >a=re.sub(r"'","",a) > > Explain what you believe this operation is doing, show us the input and > the output. > > The best I can make out of that is that it is looking for single quote > characters within whatever "a" is, and replacing them with nothing. > Something much more understandable, without invoking a regular expression > library (especially when neither the search nor the replacement terms are > regular expressions) with simple string operations... > > stripped = "".join(quoted.split("'")) Thank you for your above trick. I tried with the following code snippet: ``` from fractions import Fraction def strmat(m): if(np.array([m]).ndim==1): return str(Fraction(m)) else: return list(map(lambda L:strmat(L), np.array(m))) # For test: b=[[0.0, -1.0, 0.0, 0.25], [1.0, 0.0, 0.0, 0.25], [0.0, 0.0, 1.0, 0.25], [0.0, 0.0, 0.0, 1.0]] a=str(strmat(b)) a1=stripped = "".join(a.split("'")) a=re.sub(r"'","",a) #repr(a) print("a1 = "+ a1) print("a = "+ a) ``` As you can see, both methods give the same results: ``` a1 = [[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]] a = [[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]] ``` > You also don't need to specify RAW format for the "'" -- Python is quite > happy mixing single and double quotes (that is: single quotes inside a > string using double quotes, double quotes inside a string using single > quotes, either inside strings using triply quoted delimiters) > > >>> "'" > "'" > >>> '"' > '"' > >>> """'"'""" > '\'"\'' > >>> '''"'"''' > '"\'"' > >>> > > (Note that the interactive console displays results using repr(), and hence > escapes ' that are internal to avoid conflict with the ones wrapping the > output) > > >>> repr('''"'"''') > '\'"\\\'"\'' > >>> str('''"'"''') > '"\'"' > >>> print('''"'"''') > "'" > >>> > > The print() operation does not wrap the output with extraneous quotes. Thank your insightful explanation. Regards, HZ > -- > Wulfraed Dennis Lee Bieber AF6VN > [email protected] http://wlfraed.microdiversity.freeddns.org/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote: > On Mon, 16 May 2022 02:03:26 -0700 (PDT), "[email protected]" > declaimed the following: > > > >print(lst) > > Printing higher level structures uses the repr() of the structure and > its contents -- theoretically a form that could be used within code as a > literal. If you want human-readable str() you will need to write your own > output loop to do the formatting of the structure, and explicitly print > each item of the structure. Thank you for your explanation. I have come up with the following methods: ``` b=[[0.0, -1.0, 0.0, 0.25], [1.0, 0.0, 0.0, 0.25], [0.0, 0.0, 1.0, 0.25], [0.0, 0.0, 0.0, 1.0]] import numpy as np from fractions import Fraction import re def strmat(m): if(np.array([m]).ndim==1): return str(Fraction(m)) else: return list(map(lambda L:strmat(L), np.array(m))) a=str(strmat(b)) a=re.sub(r"'","",a) repr(a) print(repr(a)) '[[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]]' ``` Best, HZ -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Tuesday, May 17, 2022 at 7:11:24 AM UTC+8, [email protected] wrote: > On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote: > > On Mon, 16 May 2022 02:03:26 -0700 (PDT), "[email protected]" > > declaimed the following: > > > > > > >print(lst) > > > > Printing higher level structures uses the repr() of the structure and > > its contents -- theoretically a form that could be used within code as a > > literal. If you want human-readable str() you will need to write your own > > output loop to do the formatting of the structure, and explicitly print > > each item of the structure. > Thank you for your explanation. I have come up with the following methods: > ``` > b=[[0.0, -1.0, 0.0, 0.25], [1.0, 0.0, 0.0, 0.25], [0.0, 0.0, 1.0, 0.25], > [0.0, 0.0, 0.0, 1.0]] > import numpy as np > from fractions import Fraction > import re > > def strmat(m): > if(np.array([m]).ndim==1): > return str(Fraction(m)) > else: return list(map(lambda L:strmat(L), np.array(m))) > > a=str(strmat(b)) > a=re.sub(r"'","",a) > repr(a) > print(repr(a)) > '[[0, -1, 0, 1/4], [1, 0, 0, 1/4], [0, 0, 1, 1/4], [0, 0, 0, 1]]' > ``` > Best, > HZ See here [1] for the related discussion. [1] https://discuss.python.org/t/convert-the-decimal-numbers-expressed-in-a-numpy-ndarray-into-a-matrix-representing-elements-in-fractional-form/15780 -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote: > On Mon, 16 May 2022 02:03:26 -0700 (PDT), "[email protected]" > declaimed the following: > > > >print(lst) > > Printing higher level structures uses the repr() of the structure and > its contents -- theoretically a form that could be used within code as a > literal. I tried with the repr() method as follows, but it doesn't give any output: ``` import os,sys import numpy as np from fractions import Fraction import re from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.core import Lattice, Structure, Molecule, IStructure def filepath(file): script_dirname=os.path.dirname(os.path.realpath(__file__)) return (script_dirname + '/' + file) s=IStructure.from_file(filepath('EntryWithCollCode136212.cif')) a = SpacegroupAnalyzer(s) SymOp=a.get_symmetry_operations() b=SymOp[1].affine_matrix.tolist() def strmat(m): if(np.array([m]).ndim==1): return str(Fraction(m)) else: return list(map(lambda L:strmat(L), np.array(m))) lst=[] for i in SymOp: lst.append(i.affine_matrix.tolist()) a=str(strmat(lst)) a=re.sub(r"'","",a) repr(a) ``` > If you want human-readable str() you will need to write your own > output loop to do the formatting of the structure, and explicitly print > each item of the structure. -- https://mail.python.org/mailman/listinfo/python-list
Re: Convert the decimal numbers expressed in a `numpy.ndarray` into a matrix representing elements in fractional form
> On 17 May 2022, at 05:59, [email protected] wrote: > > On Monday, May 16, 2022 at 11:27:58 PM UTC+8, Dennis Lee Bieber wrote: >> On Mon, 16 May 2022 02:03:26 -0700 (PDT), "[email protected]" >> declaimed the following: >> >> >>> print(lst) >> >> Printing higher level structures uses the repr() of the structure and >> its contents -- theoretically a form that could be used within code as a >> literal. > > I tried with the repr() method as follows, but it doesn't give any output: Repr returns a string. You need to print its value to see it. > > ``` > import os,sys > import numpy as np > from fractions import Fraction > import re > from pymatgen.symmetry.analyzer import SpacegroupAnalyzer > from pymatgen.core import Lattice, Structure, Molecule, IStructure > > def filepath(file): > script_dirname=os.path.dirname(os.path.realpath(__file__)) > return (script_dirname + '/' + file) > > s=IStructure.from_file(filepath('EntryWithCollCode136212.cif')) > a = SpacegroupAnalyzer(s) > SymOp=a.get_symmetry_operations() > b=SymOp[1].affine_matrix.tolist() > > def strmat(m): > if(np.array([m]).ndim==1): > return str(Fraction(m)) > else: return list(map(lambda L:strmat(L), np.array(m))) > > lst=[] > for i in SymOp: > lst.append(i.affine_matrix.tolist()) > > a=str(strmat(lst)) > a=re.sub(r"'","",a) > repr(a) print(repr(a)) Barry > ``` > >> If you want human-readable str() you will need to write your own >> output loop to do the formatting of the structure, and explicitly print >> each item of the structure. > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
