How to remove "" from starting of a string if provided by the user
How to remove " from the starting and ending of a string , before
comparison . Here is an example and my solution wtih eval ( I am advised
not to use this one) , please suggest an alternative . I am on linux and
python 2.7
g1@X1:/tmp$ cat file2.py
#!/usr/bin/python
# Case 1 - server2 file is "'/fileno_100.txt'"
stat={}
stat['server1'] = '/fileno_100.txt'
stat['server2'] = "'/fileno_100.txt'"
if stat['server1'] == eval(stat['server2']):
print "OK"
# Case 2 - server2 file is '/fileno_100.txt'
stat['server2'] = "'/fileno_100.txt'"
if stat['server1'] == eval(stat['server2']):
print "OK"
# Case 3 - server2 file can be in (a) '/fileno_100.txt' or (b) :
"'/fileno_100.txt'" format
g1@X1:/tmp$ python file2.py
OK
OK
--
https://mail.python.org/mailman/listinfo/python-list
Strange namespace issue
Hi all,
today I faced an issue that, although very easy to fix, left me wondering
about what causes it.
The context is an application that execute small scripts coming from an
external source (say, a database). The application first compile the script,
then execute it passing it some values: in the script I wrote this morning I
used a list comprehension, executing a method of an instance passed in in the
local context.
The following example illustrates the problem:
class Test:
def create_value(self, a):
return a*2
script = """\
# This works
cv = test.create_value
x = []
for i in range(3):
x.append(cv(i))
print(x)
# This does not: NameError: name 'test' is not defined
x = [test.create_value(i) for i in range(3)]
print(x)
# This neither: NameError: name 'cv' is not defined
x = [cv(i) for i in range(3)]
print(x)
"""
code = compile(script, 'script', 'exec')
exec(code, {}, {'test': Test()})
I must be missing something, as I cannot understand why within the list
comprehension the neither the name "test" nor the name "cv" are defined...
Thanks in advance for any enlightenment!
ciao, lele.
--
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected] | -- Fortunato Depero, 1929.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How explain why Python is easier/nicer than Lisp which has a simpler grammar/syntax?
Terry Reedy schreef op 7/08/2020 om 22:08: On 8/7/2020 11:46 AM, Chris Angelico wrote: My point is that doing Fibonacci recursively is arguably more elegant while being materially worse at performance. This is a common misconception. Linear iteration and tail recursion are equivalent. The issue is calculating values once versus multiple times. Here is the fast recursion equivalent to the fast iteration. def fib(n, pair=(1,0)): previous, current = pair if n: return fib(n-1, (current, previous + current)) else: return current Of course, but now you've lost the elegance of the recursive version being near-literal translation of the mathematical definition. It's a gripe I have with many introductory texts to functional programming. Recursion is super cool, they say, it lets you decompose problems in smaller problems in an elegant natural way. But then show examples like Fibonacci where the elegant natural way is a bad solution, so they introduce accumulators and stuff, and then Fibonacci does work much better indeed. But they fail to notice that the new solution is not elegant and natural at all anymore. It has just become iteration in a recursive disguise. I'm not saying there is nothing useful in functional programming and the use of recursion; there most certainly is. But the way many texts introduce it IMO doesn't help at all to understand the elegance that can be achieved. -- "Honest criticism is hard to take, particularly from a relative, a friend, an acquaintance, or a stranger." -- Franklin P. Jones Roel Schroeven -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange namespace issue
On Tue, Aug 11, 2020 at 5:44 AM Lele Gaifax wrote:
>
> Hi all,
>
> today I faced an issue that, although very easy to fix, left me wondering
> about what causes it.
>
> The context is an application that execute small scripts coming from an
> external source (say, a database). The application first compile the script,
> then execute it passing it some values: in the script I wrote this morning I
> used a list comprehension, executing a method of an instance passed in in the
> local context.
>
> The following example illustrates the problem:
>
> class Test:
> def create_value(self, a):
> return a*2
>
> script = """\
> # This works
> cv = test.create_value
> x = []
> for i in range(3):
> x.append(cv(i))
> print(x)
>
> # This does not: NameError: name 'test' is not defined
> x = [test.create_value(i) for i in range(3)]
> print(x)
>
> # This neither: NameError: name 'cv' is not defined
> x = [cv(i) for i in range(3)]
> print(x)
> """
>
> code = compile(script, 'script', 'exec')
> exec(code, {}, {'test': Test()})
>
> I must be missing something, as I cannot understand why within the list
> comprehension the neither the name "test" nor the name "cv" are defined...
>
> Thanks in advance for any enlightenment!
>
Interesting. You're passing an empty globals and a non-empty locals
(the second and third arguments to exec, respectively). Is that
deliberate? By the look of this code, it's meant to be at global scope
(as if it's the top level code in a module), which is best done by
passing just a single dict to exec (it'll be both globals and locals).
The reason your first block works but the comprehensions don't is that
comprehensions act in a nested scope. I think you've hit on a curious
edge case where empty globals results in strange behaviour.
I tried your code with the empty dict removed and it appears to work,
but if you had a good reason for having separate dicts, that might
break.
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
Re: How explain why Python is easier/nicer than Lisp which has a simpler grammar/syntax?
On Tue, Aug 11, 2020 at 5:48 AM Roel Schroeven wrote: > I'm not saying there is nothing useful in functional programming and the > use of recursion; there most certainly is. But the way many texts > introduce it IMO doesn't help at all to understand the elegance that can > be achieved. Indeed. When I'm talking to students about recursion, often the question "why bother" comes up... but when they finally 'get it', it's usually because of an example far more elegant than Fibonacci numbers. One of my favourites is: Given a binary tree, calculate its height. def height(tree): if not tree: return 0 return max(height(tree.left), height(tree.right)) + 1 THIS is the sort of thing that shows off the beauty of recursion. Convoluted code with accumulator parameters just shows off that you can write bad code in any style. (Though the accumulator parameter form does have its place. Ever written callback-based asynchronous code that needs to iterate over something? Such fun.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user
On 11Aug2020 00:05, Ganesh Pal wrote: >How to remove " from the starting and ending of a string , before >comparison . Here is an example and my solution wtih eval ( I am advised >not to use this one) , please suggest an alternative . I am on linux and >python 2.7 Indeed. Using eval is extremely dangerous - it can execute _any_ python code at all. Do not do that. I would look for the quote character (you say " above but all your examples actually use the ' character) at the start and end with .startswith and .endswith methods, and cut out the middle with a slice if they are both your target quote character (don't forget that Python supports negative indices, making this pretty easy). But I suspect that in the real world you'll find this approach simplistic. Normally quotes introduce a special syntax between them, such a \n to indicate a newline character and so forth, so _only_ stripping the quotes is not al that would be required. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user
On 2020-08-10 19:35, Ganesh Pal wrote:
How to remove " from the starting and ending of a string , before
comparison . Here is an example and my solution wtih eval ( I am advised
not to use this one) , please suggest an alternative . I am on linux and
python 2.7
g1@X1:/tmp$ cat file2.py
#!/usr/bin/python
# Case 1 - server2 file is "'/fileno_100.txt'"
stat={}
stat['server1'] = '/fileno_100.txt'
stat['server2'] = "'/fileno_100.txt'"
if stat['server1'] == eval(stat['server2']):
print "OK"
# Case 2 - server2 file is '/fileno_100.txt'
stat['server2'] = "'/fileno_100.txt'"
if stat['server1'] == eval(stat['server2']):
print "OK"
# Case 3 - server2 file can be in (a) '/fileno_100.txt' or (b) :
"'/fileno_100.txt'" format
g1@X1:/tmp$ python file2.py
OK
OK
You could strip off the quotes with the .strip method or use
literal_eval from the ast module.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Save-to-file code not quite working completely
On 10/08/2020 05:23, Dennis Lee Bieber wrote: On Sun, 9 Aug 2020 11:50:51 +1200, dn via Python-list declaimed the following: To be a logomach, let's talk about "update":- May I advise that a 'good practice' would be to create a new file, and thus be able to (also) maintain the old version as a 'backup'. (also: advantage when debugging/testing logic!) Per the documentation, this is exactly what the "inplace=True" does! It renames the original file, then writes the output under the original name. Keeping the backup after processing requires providing an explicit "backup=.ext" option, otherwise it uses .bak and deletes the file when processing completes. Apologies for incomplete answer. I have finally remembered why I (have long) steer-clear of fileinput: a) criticism from Martijn Pieters https://www.zopatista.com/python/2013/11/26/inplace-file-rewriting/ b) I can't recall 'my' last application requiring/desiring a flat-file that wasn't JSON or YAML. The above article is (2013) old. I notice that whilst the github received a trivial update one month back, that the PyPI entry is almost two years old. I (am biased, admittedly) still maintain that for anything more than the trivial, a direct-access mechanism is the tool-for-the-job, and because I think they are 'easy', an RDBMS. YMMV! -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: How to remove "" from starting of a string if provided by the user
The possible value of stat['server2'] can be either (a)
"'/fileno_100.txt'" or (b) '/fileno_100.txt' .
How do I check if it the value was (a) i.e string started and ended
with a quote , so that I can use ast.literal_eval()
>>> import ast
>>> stat = {}
>>> stat['server2'] = "'/fileno_100.txt'"
>>> stat['server2'] = ast.literal_eval(stat['server2'])
>>> print stat['server2']
/fileno_100.txt
>>>
>>> if stat['server2'].startswith("\"") and stat['server2'].endswith("\""):
...stat['server2'] = ast.literal_eval(stat['server2'])
...
>>>
I tried startswith() and endswith(), doesn't seem to work ?. Is there
a simpler way ?
Regards,
Ganesh
On Tue, Aug 11, 2020 at 4:06 AM MRAB wrote:
> On 2020-08-10 19:35, Ganesh Pal wrote:
> > How to remove " from the starting and ending of a string , before
> > comparison . Here is an example and my solution wtih eval ( I am advised
> > not to use this one) , please suggest an alternative . I am on linux and
> > python 2.7
> >
> > g1@X1:/tmp$ cat file2.py
> > #!/usr/bin/python
> >
> > # Case 1 - server2 file is "'/fileno_100.txt'"
> > stat={}
> > stat['server1'] = '/fileno_100.txt'
> > stat['server2'] = "'/fileno_100.txt'"
> >
> > if stat['server1'] == eval(stat['server2']):
> > print "OK"
> >
> > # Case 2 - server2 file is '/fileno_100.txt'
> > stat['server2'] = "'/fileno_100.txt'"
> >
> > if stat['server1'] == eval(stat['server2']):
> > print "OK"
> >
> >
> > # Case 3 - server2 file can be in (a) '/fileno_100.txt' or (b) :
> > "'/fileno_100.txt'" format
> >
> > g1@X1:/tmp$ python file2.py
> > OK
> > OK
> >
> You could strip off the quotes with the .strip method or use
> literal_eval from the ast module.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
https://mail.python.org/mailman/listinfo/python-list
Re: importlib: import X as Y; from A import B
> > import pandas; pd = pandas > > >df = pd.from_csv (...) > >from selenium import webdriver > > import selenium.webdriver; webdriver = selenium.webdriver > Thank you, this works. -- https://mail.python.org/mailman/listinfo/python-list
Any timeline for PIL for Python 3.4
Hi, I am running Python 3.4.4, and would like to use the Python Imaging Library (PIL). This is currently not available for Python Version 3. Does anybody know when it will become available? Plan B is to install Python 2.7.18. I just need an idea of how long I would need to wait for Plan A. -- Regards, Martin Leese E-mail: [email protected] Web: http://members.tripod.com/martin_leese/ -- https://mail.python.org/mailman/listinfo/python-list
Re: Any timeline for PIL for Python 3.4
On 11/08/2020 2:35 pm, Martin wrote: > Hi, > > I am running Python 3.4.4, and would like to > use the Python Imaging Library (PIL). This > is currently not available for Python > Version 3. Does anybody know when it will > become available? Try Pillow https://pillow.readthedocs.io/en/stable/installation.html > > Plan B is to install Python 2.7.18. I just > need an idea of how long I would need to > wait for Plan A. > -- Signed email is an absolute defence against phishing. This email has been signed with my private key. If you import my public key you can automatically decrypt my signature and be sure it came from me. Just ask and I'll send it to you. Your email software can handle signing. signature.asc Description: OpenPGP digital signature -- https://mail.python.org/mailman/listinfo/python-list
Re: Any timeline for PIL for Python 3.4
On 11/08/2020 16:35, Martin wrote: I am running Python 3.4.4, and would like to use the Python Imaging Library (PIL). This is currently not available for Python Version 3. Does anybody know when it will become available? Plan B is to install Python 2.7.18. I just need an idea of how long I would need to wait for Plan A. 1 PIL was discontinued about a decade back. Please use "Pillow" (a fork - note first three letters), which is available from PyPI (pip3) 2 Bad news though, IIRC it requires Python 3.5+ 3 Don't degrade to Py2 if you can at all avoid doing-so! -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Any timeline for PIL for Python 3.4
dn於 2020年8月11日星期二 UTC+8下午1時29分47秒寫道: > On 11/08/2020 16:35, Martin wrote: > > I am running Python 3.4.4, and would like to > > use the Python Imaging Library (PIL). This > > is currently not available for Python > > Version 3. Does anybody know when it will > > become available? > > > > Plan B is to install Python 2.7.18. I just > > need an idea of how long I would need to > > wait for Plan A. > > > 1 PIL was discontinued about a decade back. Please use "Pillow" (a fork > - note first three letters), which is available from PyPI (pip3) > > 2 Bad news though, IIRC it requires Python 3.5+ > > 3 Don't degrade to Py2 if you can at all avoid doing-so! > -- > Regards =dn Pillow for Python 3.4 can be downloaded at this moment in time:-) https://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow --Jach -- https://mail.python.org/mailman/listinfo/python-list
Re: Any timeline for PIL for Python 3.4
On Tue, Aug 11, 2020 at 2:41 PM Martin wrote: > > Hi, > > I am running Python 3.4.4, and would like to > use the Python Imaging Library (PIL). This > is currently not available for Python > Version 3. Does anybody know when it will > become available? > > Plan B is to install Python 2.7.18. I just > need an idea of how long I would need to > wait for Plan A. > As others have said, Pillow is the way to go (it's API-compatible with original PIL). But you may want to consider a newer Python - 3.4 is now quite old. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
