Re: Plumbing behind super()

2019-06-28 Thread Thomas Jollans

On 28/06/2019 02:13, adam.pre...@gmail.com wrote:

I'm trying to mimick Python 3.6 as a .NET science project and have started to 
get into subclassing. The super() not-a-keyword-honestly-guys has tripped me 
up. I have to admit that I've professionally been doing a ton Python 2.7, so 
I'm not good on my Python 3.6 trivia yet. I think I have the general gist of 
this, but want some affirmation.

If you use super() in a method, all it does is load super as a global on to the 
interpreter stack and call it without any arguments. So I'm left to wonder how 
it's able to figure anything out when it's being literally given nothing...


Python is open source, so let's open the source!

The magic happens when super() is constructed, in super_init 
https://github.com/python/cpython/blob/a8b27e623d75377aabe50df27e97cab4e81a174a/Objects/typeobject.c#L7814


Once super_getattro is called, the super object has already been set up, 
and it already knows which object/class to look at.


As you can see, super_init takes the calling frame and checks the first 
argument of the previous call, which, when called from a method, will 
generally be 'self'


https://github.com/python/cpython/blob/a8b27e623d75377aabe50df27e97cab4e81a174a/Objects/typeobject.c#L7849

There's some additional code that, I think, handles being called from a 
closure (but I don't know the C api well enough to be sure)


We can sort-of emulate this in pure Python with the inspect module

###

def not_quite_super():
    f = inspect.stack()[1].frame
    obj = list(f.f_locals.values())[0]
    print(type(obj), obj)

class A:
    def __init__(self, a=0, b=1):
    c = a + b # this is just to add some more locals to the mix
    not_quite_super()

A()


###

Once you have the caller object, the rest is just like calling super() 
with arguments.


I'm not actually sure that Python example above is guaranteed to work, 
but I *think* it should in versions where dicts are ordered (3.6+). 
Obviously it doesn't handle all the cases super() handles.





except that it's not being given literally nothing:

static PyObject *
super_getattro(PyObject *self, PyObject *name)

I was thinking maybe self has become more special in Python 3.6, but I don't think that's 
true since I've ported code to Python3 before that had inner classes where I'd use 
"inner_self" to disambiguate with the outer self. And though I thought it was 
so at first, it just turned out I screwed up my little code snippet to expose it. If self 
was special then I presume I could find it in my lookups and inject it.

So how do I go from CALL_FUNCTION on a super() global without anything else on 
the stack to somehow having all the information I need? Is there something 
tracking that I'm in an object scope when calling stuff?



--
https://mail.python.org/mailman/listinfo/python-list


Re: Make sure the window title is visible in tkinter

2019-06-28 Thread Cecil Westerhof
Cecil Westerhof  writes:

> Wildman  writes:
>
>> On Wed, 26 Jun 2019 13:25:15 +0200, Cecil Westerhof wrote:
>>
>>> I need to write a desktop program. I choose to use tkinter. How can I
>>> make sure the window title is visible? For example when I have the
>>> following code:
>>> from tkinter  import Button, filedialog, Label, messagebox, Tk
>>> 
>>> 
>>> window = Tk()
>>> window.title('A long window title')
>>> Button (window, text = 'Short text').pack()
>>> window.mainloop()
>>> 
>>> I see only a part of the 'A', but I would like to see the complete:
>>> 'A long window title'
>>
>> According to link below, it is not possible...
>> "Tkinter has no way of knowing how long the title is on the titlebar."
>>
>> https://stackoverflow.com/questions/35273690/tkinter-window-not-wide-enough-to-display-window-title
>
> OK, then I will have to live with it.

I just make sure something is in my window that has such a width that
the tittle will be displayed. ;-)

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a Windows executable on a Linux system

2019-06-28 Thread Cecil Westerhof
Cecil Westerhof  writes:

> I need to write a Python desktop program. I create it on a Linux
> system, but it has to run on a Windows system. When looking at how to
> create an executable it seems that you need to be on a Windows system
> to create a Windows executable. Is this true, or is it possible to
> create a Windows executable on a Linux system?
>
> Any pointers about best practice creating a standalone executable are
> welcome.

For the moment it is not a problem. It is allowed to install Python
openpyxl on the systems where this application has to run. Letting the
application name end on pyw and put a link on the desktop makes it
work for the people that need to work with it.

Still interested in getting it to work (for when I get in the
situation that I have to distribute a Python program where it is not
allowed to install Python), but it is not urgent anymore.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Copying a row from a range of Excel files to another

2019-06-28 Thread Cecil Westerhof
MRAB  writes:

> On 2019-06-26 22:14, Cecil Westerhof wrote:
>> MRAB  writes:
>>
>>> Does Workbook support the 'with' statement?
>>>
>>> If it does, then that's the best way of doing it.
>>>
>>> (Untested)
>>>
>>> with Workbook() as wb_out:
>>> for filepath in filepathArr:
>>> current_row = []
>>>
>>> with load_workbook(filepath) as wb_in:
>>> for cell in wb_in.active[src_row]:
>>> current_row.append(cell.value)
>>>
>>> wb_out.active.append(current_row)
>>>
>>> wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') +
>>> report_end)
>>
>> It seems not. I get AttributeError.
>>
> You didn't say which line.

I made a minimalist program to show it:
#!/usr/bin/env python3


from openpyxl import Workbook


with Workbook() as wb_out:
print('In loop')
print('After loop')

This results in:
Traceback (most recent call last):
  File "./test.py", line 7, in 
with Workbook() as wb_out:
AttributeError: __exit__


> Anyway, if Workbooks are closed using a method called "close", you can
> wrap them in a "closing" context manager:

That seems to work. I changed it to:
#!/usr/bin/env python3


from contextlib   import closing
from datetime import datetime
from openpyxl import Workbook


with closing(Workbook()) as wb_out:
print('In loop')
wb_out.save('testing_' + datetime.now().strftime('%Y-%m-%d') + '.xlsx')
print('After loop')

And I see:
In loop
After loop

And a testing Excel file.

Thanks.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a Windows executable on a Linux system

2019-06-28 Thread Cecil Westerhof
Cecil Westerhof  writes:

> Cecil Westerhof  writes:
>
>> I need to write a Python desktop program. I create it on a Linux
>> system, but it has to run on a Windows system. When looking at how to
>> create an executable it seems that you need to be on a Windows system
>> to create a Windows executable. Is this true, or is it possible to
>> create a Windows executable on a Linux system?
>>
>> Any pointers about best practice creating a standalone executable are
>> welcome.
>
> For the moment it is not a problem.
> It is allowed to install Python openpyxl on the systems

Oops, that should have been:
It is allowed to install Python AND openpyxl on the systems


> where this application has to run. Letting the
> application name end on pyw and put a link on the desktop makes it
> work for the people that need to work with it.
>
> Still interested in getting it to work (for when I get in the
> situation that I have to distribute a Python program where it is not
> allowed to install Python), but it is not urgent anymore.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Only a message at the highest exception

2019-06-28 Thread Cecil Westerhof
I have a tkinter program where I have a function generate_report which
in a try block calls the function append_row. This function has also a
try block. When they get an exception they give message. But when
append_row has already given a message then generate_report should
not. To implement this I use the following class:
class AlreadyHandledException(Exception):
pass

Then in append_row I have:
except Exception as err:
messagebox.showerror(error_str,
 error_append + '\n\n\n\n' + str(err))
raise AlreadyHandledException()

And in generate_report I have:
except Exception as err:
if type(err).__name__ != "AlreadyHandledException":
messagebox.showerror(error_str,
 error_generate + '\n\n\n\n' + str(err))
progress.pack_forget()

Is this an acceptable way, or should I do it differently?

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Only a message at the highest exception

2019-06-28 Thread Chris Angelico
On Fri, Jun 28, 2019 at 7:33 PM Cecil Westerhof  wrote:
>
> I have a tkinter program where I have a function generate_report which
> in a try block calls the function append_row. This function has also a
> try block. When they get an exception they give message. But when
> append_row has already given a message then generate_report should
> not. To implement this I use the following class:
> class AlreadyHandledException(Exception):
> pass
>
> Then in append_row I have:
> except Exception as err:
> messagebox.showerror(error_str,
>  error_append + '\n\n\n\n' + str(err))
> raise AlreadyHandledException()
>
> And in generate_report I have:
> except Exception as err:
> if type(err).__name__ != "AlreadyHandledException":
> messagebox.showerror(error_str,
>  error_generate + '\n\n\n\n' + str(err))
> progress.pack_forget()
>
> Is this an acceptable way, or should I do it differently?
>

Well, first off, I would use two separate except clauses, rather than
a type check. But are you able to just NOT catch the exception inside
append_row? Let it be handled at the top level only.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Hiding a progressbar in tkinter

2019-06-28 Thread Cecil Westerhof
MRAB  writes:

> On 2019-06-26 16:47, Cecil Westerhof wrote:
>> I just started with GUI stuff in tkinter. I have a progressbar, but I
>> want it to be only visible when it is used. So I tried the following:
>>  window = Tk()
>>  window.title(window_str)
>>  frame  = Frame(window)
>>  frame.pack(side = "top", fill = "both", expand = True)
>>  Button(window, text = button_str, command = select_dir).pack()
>>  progress = ttk.Progressbar(window, orient = "horizontal", length = 200,
>> mode = "determinate")
>>  progress.pack()
>>  progress.lower(frame)
>>  window.mainloop()
>>
>> But that does not hide the progressbar. What am I doing wrong?
>>
>> I could use pack_forget, but that will change the dimensions of the
>> window.
>>
> The progress bar isn't hidden because there's nothing on top of it to
> hide it.
>
> import tkinter as tk
> import tkinter.ttk as ttk
>
> window = tk.Tk()
> window.title(window_str)
> frame = tk.Frame(window)
> frame.pack(side='top', fill='both', expand=True)
> tk.Button(window, text=button_str, command=select_dir).pack()
>
> # Create a frame to hold the progress bar.
> progress_frame = tk.Frame(window)
> progress_frame.pack(fill='x', expand=True)
>
> # Put the progress bar into the progress frame, ensuring that it fills
> the grid cell.
> progress = ttk.Progressbar(progress_frame, orient='horizontal',
> length=200, mode='determinate')
> progress.grid(row=0, column=0, sticky='nsew')
>
> # Now put a blank frame into the progress frame over the progress bar,
> ensuring that it fills the same grid cell.
> blank = tk.Frame(progress_frame)
> blank.grid(row=0, column=0, sticky='nsew')
>
> # Raise the progress bar over the blank frame to reveal it.
> progress.tkraise()
>
> # Lower the progress bar underneath the blank frame to hide it.
> progress.lower()
>
> window.mainloop()

Works like a charm. Thanks.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Only a message at the highest exception

2019-06-28 Thread Cecil Westerhof
Chris Angelico  writes:

> On Fri, Jun 28, 2019 at 7:33 PM Cecil Westerhof  wrote:
>>
>> I have a tkinter program where I have a function generate_report which
>> in a try block calls the function append_row. This function has also a
>> try block. When they get an exception they give message. But when
>> append_row has already given a message then generate_report should
>> not. To implement this I use the following class:
>> class AlreadyHandledException(Exception):
>> pass
>>
>> Then in append_row I have:
>> except Exception as err:
>> messagebox.showerror(error_str,
>>  error_append + '\n\n\n\n' + str(err))
>> raise AlreadyHandledException()
>>
>> And in generate_report I have:
>> except Exception as err:
>> if type(err).__name__ != "AlreadyHandledException":
>> messagebox.showerror(error_str,
>>  error_generate + '\n\n\n\n' + str(err))
>> progress.pack_forget()
>>
>> Is this an acceptable way, or should I do it differently?
>>
>
> Well, first off, I would use two separate except clauses, rather than
> a type check.

You are completely right.


> But are you able to just NOT catch the exception inside
> append_row? Let it be handled at the top level only.

I am giving different messages. I changed the top part to:
except AlreadyHandledException:
pass
except Exception as err:
messagebox.showerror(error_str, error_generate + '\n\n\n\n' + str(err))
progress.lower()

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Only a message at the highest exception

2019-06-28 Thread Cameron Simpson

On 28Jun2019 12:17, Cecil Westerhof  wrote:

Chris Angelico  writes:

On Fri, Jun 28, 2019 at 7:33 PM Cecil Westerhof  wrote:
I have a tkinter program where I have a function generate_report 
which

in a try block calls the function append_row. This function has also a
try block. When they get an exception they give message. But when
append_row has already given a message then generate_report should
not. To implement this I use the following class:

class AlreadyHandledException(Exception):
pass

Then in append_row I have:
except Exception as err:
messagebox.showerror(error_str,
 error_append + '\n\n\n\n' + str(err))
raise AlreadyHandledException()

And in generate_report I have:
except Exception as err:
if type(err).__name__ != "AlreadyHandledException":
messagebox.showerror(error_str,
 error_generate + '\n\n\n\n' + str(err))
progress.pack_forget()

Is this an acceptable way, or should I do it differently?


Well, first off, I would use two separate except clauses, rather than
a type check.


You are completely right.


But are you able to just NOT catch the exception inside
append_row? Let it be handled at the top level only.


I am giving different messages. I changed the top part to:
   except AlreadyHandledException:
   pass
   except Exception as err:
   messagebox.showerror(error_str, error_generate + '\n\n\n\n' + str(err))
   progress.lower()


For contrast, another approach.

By catching AlreadyHandledException and just going "pass" you're 
effectively swalling that exception. For your purpose, that works.


However, in a since, why raise an exception you _know_ you're going to 
deliberately ignore?


What if you have append_row return a Boolean? True on success, False on 
failure but situation handled (i.e. append_row has shown an error, or 
whatever recovery you adopt). And keep the uncaught exceptions for the 
_unhandled_ situation. The "exceptional" situation.


Example:

 def append_row(...):
 ...
 try:
 ...stuff...
 except ExpectedExceptionHere as err:
 messagebox.showerror()
 ...maybe some cleanup...
 return False
 ...
 return True

Then your generate_report code goes:

   try:
   appended = append_row()
   except Exception as err:
   messagebox.showerror()
   else:
   if appended:
   hooray!
   else:
   unhappy, but continuing

avoiding a "do nothing" special except clause.

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Only a message at the highest exception

2019-06-28 Thread Cecil Westerhof
Cameron Simpson  writes:

> On 28Jun2019 12:17, Cecil Westerhof  wrote:
>>Chris Angelico  writes:
>>> On Fri, Jun 28, 2019 at 7:33 PM Cecil Westerhof  wrote:
 I have a tkinter program where I have a function generate_report
 which
 in a try block calls the function append_row. This function has also a
 try block. When they get an exception they give message. But when
 append_row has already given a message then generate_report should
 not. To implement this I use the following class:

 class AlreadyHandledException(Exception):
 pass

 Then in append_row I have:
 except Exception as err:
 messagebox.showerror(error_str,
  error_append + '\n\n\n\n' + str(err))
 raise AlreadyHandledException()

 And in generate_report I have:
 except Exception as err:
 if type(err).__name__ != "AlreadyHandledException":
 messagebox.showerror(error_str,
  error_generate + '\n\n\n\n' + str(err))
 progress.pack_forget()

 Is this an acceptable way, or should I do it differently?
>>>
>>> Well, first off, I would use two separate except clauses, rather than
>>> a type check.
>>
>>You are completely right.
>>
>>> But are you able to just NOT catch the exception inside
>>> append_row? Let it be handled at the top level only.
>>
>>I am giving different messages. I changed the top part to:
>>except AlreadyHandledException:
>>pass
>>except Exception as err:
>>messagebox.showerror(error_str, error_generate + '\n\n\n\n' + 
>> str(err))
>>progress.lower()
>
> For contrast, another approach.
>
> By catching AlreadyHandledException and just going "pass" you're
> effectively swalling that exception. For your purpose, that works.
>
> However, in a since, why raise an exception you _know_ you're going to
> deliberately ignore?

I am not. I am using it to quit generating the report. Just ignoring
that I could not append a record does not sound correct to me. Yes
they got a message that something went wrong. But if there is still a
generated report, things will go wrong.


> What if you have append_row return a Boolean? True on success, False on
> failure but situation handled (i.e. append_row has shown an error, or
> whatever recovery you adopt). And keep the uncaught exceptions for the
> _unhandled_ situation. The "exceptional" situation.
>
> Example:
>
>  def append_row(...):
>  ...
>  try:
>  ...stuff...
>  except ExpectedExceptionHere as err:
>  messagebox.showerror()
>  ...maybe some cleanup...
>  return False
>  ...
>  return True
>
> Then your generate_report code goes:
>
>try:
>appended = append_row()
>except Exception as err:
>messagebox.showerror()
>else:
>if appended:
>hooray!
>else:
>unhappy, but continuing

And that is exactly what I not want to do.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


How do you insert an item into a dictionary (in python 3.7.2)?

2019-06-28 Thread CrazyVideoGamez
How do you insert an item into a dictionary? For example, I make a dictionary 
called "dictionary".

dictionary = {1: 'value1', 2: 'value3'}

What if I wanted to add a value2 in the middle of value1 and value3?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Make sure the window title is visible in tkinter

2019-06-28 Thread CrazyVideoGamez
On Wednesday, June 26, 2019, at 7:44:15 AM UTC-4, Cecil Westerhof wrote:
> I need to write a desktop program. I choose to use tkinter. How can I
> make sure the window title is visible? For example when I have the
> following code:
> from tkinter  import Button, filedialog, Label, messagebox, Tk
> 
> 
> window = Tk()
> window.title('A long window title')
> Button (window, text = 'Short text').pack()
> window.mainloop()
> 
> I see only a part of the 'A', but I would like to see the complete:
> 'A long window title'
> 
> -- 
> Cecil Westerhof
> Senior Software Engineer
> LinkedIn: http://www.linkedin.com/in/cecilwesterhof

Maybe you should try to maximize the window so you can see everything. It put 
in your code and I could see more of the title.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you insert an item into a dictionary (in python 3.7.2)?

2019-06-28 Thread Calvin Spealman
You simply assign to the key, like so:

dictionary[3] = 'value2'

But it isn't clear what you mean by "in the middle".

On Fri, Jun 28, 2019 at 11:10 AM CrazyVideoGamez 
wrote:

> How do you insert an item into a dictionary? For example, I make a
> dictionary called "dictionary".
>
> dictionary = {1: 'value1', 2: 'value3'}
>
> What if I wanted to add a value2 in the middle of value1 and value3?
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

cspea...@redhat.com  M: +1.336.210.5107
[image: https://red.ht/sig] 
TRIED. TESTED. TRUSTED. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you insert an item into a dictionary (in python 3.7.2)?

2019-06-28 Thread Larry Martell
On Fri, Jun 28, 2019 at 11:10 AM CrazyVideoGamez
 wrote:
>
> How do you insert an item into a dictionary? For example, I make a dictionary 
> called "dictionary".
>
> dictionary = {1: 'value1', 2: 'value3'}
>
> What if I wanted to add a value2 in the middle of value1 and value3?

Dicts are not ordered. If you need that use an OrderedDict
(https://docs.python.org/3.7/library/collections.html#collections.OrderedDict)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you insert an item into a dictionary (in python 3.7.2)?

2019-06-28 Thread Jon Ribbens via Python-list
On 2019-06-28, Larry Martell  wrote:
> On Fri, Jun 28, 2019 at 11:10 AM CrazyVideoGamez
> wrote:
>>
>> How do you insert an item into a dictionary? For example, I make a 
>> dictionary called "dictionary".
>>
>> dictionary = {1: 'value1', 2: 'value3'}
>>
>> What if I wanted to add a value2 in the middle of value1 and value3?
>
> Dicts are not ordered. If you need that use an OrderedDict
> (https://docs.python.org/3.7/library/collections.html#collections.OrderedDict)

This is no longer true from Python 3.6 onwards - dicts are ordered.
There's no way to insert an item anywhere other than at the end though.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How do you insert an item into a dictionary (in python 3.7.2)?

2019-06-28 Thread Chris Angelico
On Sat, Jun 29, 2019 at 1:51 AM Jon Ribbens via Python-list
 wrote:
>
> On 2019-06-28, Larry Martell  wrote:
> > On Fri, Jun 28, 2019 at 11:10 AM CrazyVideoGamez
> > wrote:
> >>
> >> How do you insert an item into a dictionary? For example, I make a 
> >> dictionary called "dictionary".
> >>
> >> dictionary = {1: 'value1', 2: 'value3'}
> >>
> >> What if I wanted to add a value2 in the middle of value1 and value3?
> >
> > Dicts are not ordered. If you need that use an OrderedDict
> > (https://docs.python.org/3.7/library/collections.html#collections.OrderedDict)
>
> This is no longer true from Python 3.6 onwards - dicts are ordered.
> There's no way to insert an item anywhere other than at the end though.

They retain order, but they're not an "ordered collection" the way a
list is. You can't logically insert into a sequence, because it's not
a sequence. You can't say "what's the 43rd entry in this dict?"
because it doesn't have a 43rd entry. All it has is a recollection of
the order things were inserted.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: change spacing to two instead of four with pep8 or flake8?

2019-06-28 Thread shivam . patel
On Tuesday, April 8, 2014 at 8:55:46 AM UTC-4, Peter Otten wrote:
> Dennis wrote:
> 
> > In Pylint you can change the spacing multiplier from 4 spaces to two
> > in its pylintrc, but for the life of me I cannot find a way to do this
> > with the flake8 / pep8 utilities.
> > 
> > I want to avoid ignoring E111 altogether if at all possible, because
> > it may catch other spacing problems that are not as obvious.
> > 
> > hacky/non-hacky solutions welcome of course.
> 
> The check is hardcoded
> 
> if indent_char == ' ' and indent_level % 4:
> yield 0, "E111 indentation is not a multiple of four"
> 
> so your only short-term solution is to modify the script's source code.

What file is this?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use global, or not

2019-06-28 Thread Rob Gaddi

On 6/28/19 6:44 AM, Cecil Westerhof wrote:

I have written a GUI program where I have quit a few global variables.
I did not like this, so I now use one global dict. Something like:

[snip]

 global_dict  = {
 'messages': messages,
 'progress': progress,
 'window':   window,
 }

And in the program do things like:
 global_dict['progress']['value'] += 1
 global_dict['window'].update_idletasks()
 global_dict['window'].update_idletasks()

and:
 messagebox.showwarning(global_dict['titles']['warning'],
global_dict['messages']['nofiles'])


Is that an acceptable way to do this?



It works.  I guess it makes your use of items in the global namespace inherently 
intentional rather than allowing accidental globals.  I'm not sure how much 
value it adds though.


That said, I've got a whole bunch of programs that all use a dict called 
Registry that they all import from a shared package; making them program-wide 
globals.  I use it for a few pieces of static information ('application', 
'version') as well as to pass device handles around, since an open connection to 
a given piece of physical hardware is an inherently global thing.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Use global, or not

2019-06-28 Thread Cecil Westerhof
I have written a GUI program where I have quit a few global variables.
I did not like this, so I now use one global dict. Something like:
global global_dict

canceled_report  = 'Genereren rapportage gecanceled.'
created_report   = 'Rapportage voor {} bestanden is gemaakt.'
error_append = 'Er ging iets fout bij het toevoegen van een record.'
error_generate   = 'Er ging iets fout bij het genereren van de 
rapportage.'
error_select = 'Er ging iets fout bij het selecteren van de 
directory.'
error_widening   = 'Er ging iets fout bij instellen van de wijdte.'
error_nofiles= 'Er zijn geen bestanden om te verwerken.'
messages = {
'canceled': canceled_report,
'created':  created_report,
'append':   error_append,
'generate': error_generate,
'select':   error_select,
'widening': error_widening,
'nofiles':  error_nofiles,
}
error_str   = 'Foutmelding'
info_str= 'Info'
warning_str = 'Waarschuwing'
titles  = {
'error':   error_str,
'info':info_str,
'warning': warning_str,
}
.
.
.
window = Tk()
.
.
.
progress   = ttk.Progressbar(progress_frame, orient = 'horizontal',
 length = 200, mode = 'determinate')
.
.
.
global_dict  = {
'messages': messages,
'progress': progress,
'window':   window,
}

And in the program do things like:
global_dict['progress']['value'] += 1
global_dict['window'].update_idletasks()
global_dict['window'].update_idletasks()

and:
messagebox.showwarning(global_dict['titles']['warning'],
   global_dict['messages']['nofiles'])


Is that an acceptable way to do this?

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
-- 
https://mail.python.org/mailman/listinfo/python-list


Handle foreign character web input

2019-06-28 Thread Tobiah

A guy comes in and enters his last name as RÖnngren.

So what did the browser really give me; is it encoded
in some way, like latin-1?  Does it depend on whether
the name was cut and pasted from a Word doc. etc?
Should I handle these internally as unicode?  Right
now my database tables are latin-1 and things seem
to usually work, but not always.

Also, what do people do when searching for a record.
Is there some way to get 'Ronngren' to match the other
possible foreign spellings?


--
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread Chris Angelico
On Sat, Jun 29, 2019 at 6:31 AM Tobiah  wrote:
>
> A guy comes in and enters his last name as RÖnngren.
>
> So what did the browser really give me; is it encoded
> in some way, like latin-1?  Does it depend on whether
> the name was cut and pasted from a Word doc. etc?
> Should I handle these internally as unicode?  Right
> now my database tables are latin-1 and things seem
> to usually work, but not always.

Definitely handle them as Unicode. You'll receive them in some
encoding, probably UTF-8, and it depends on the browser. Ideally, your
back-end library (eg Flask) will deal with that for you.

> Also, what do people do when searching for a record.
> Is there some way to get 'Ronngren' to match the other
> possible foreign spellings?

Ehh... probably not. That's a human problem, not a programming
one. Best of luck.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread Tobiah


On 6/28/19 1:33 PM, Chris Angelico wrote:> On Sat, Jun 29, 2019 at 6:31 AM Tobiah 
 wrote:


A guy comes in and enters his last name as RÖnngren.

So what did the browser really give me; is it encoded
in some way, like latin-1?  Does it depend on whether
the name was cut and pasted from a Word doc. etc?
Should I handle these internally as unicode?  Right
now my database tables are latin-1 and things seem
to usually work, but not always.


Definitely handle them as Unicode. You'll receive them in some
encoding, probably UTF-8, and it depends on the browser. Ideally, your
back-end library (eg Flask) will deal with that for you.

It varies by browser?
So these records are coming in from all over the world.  How
do people handle possibly assorted encodings that may come in?

I'm using Web2py.  Does the request come in with an encoding
built in?  Is that how people get the proper unicode object?


Also, what do people do when searching for a record.
Is there some way to get 'Ronngren' to match the other
possible foreign spellings?


Ehh... probably not. That's a human problem, not a programming
one. Best of luck.


Well so I'm at an event.  A guy comes up to me at the kiosk
and say his name is RÖnngren.  I can't find him, typing in "ron"
so I ask him how to spell his last name.  What does he say, and
what do I type?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread inhahe
:

>
> On 6/28/19 1:33 PM, Chris Angelico wrote:> On Sat, Jun 29, 2019 at 6:31 AM
> Tobiah  wrote:
>


> >> Also, what do people do when searching for a record.
> >> Is there some way to get 'Ronngren' to match the other
> >> possible foreign spellings?
> >
>
> I think I've heard of algorithms that can match spellings with exotic
characters, but I don't remember what they're
called. I think they're out there. It's a black science, though, so some of
their decisions in how to match or not match
are probably arbitrary.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread Chris Angelico
On Sat, Jun 29, 2019 at 7:01 AM Tobiah  wrote:
>
>
> On 6/28/19 1:33 PM, Chris Angelico wrote:> On Sat, Jun 29, 2019 at 6:31 AM 
> Tobiah  wrote:
> >>
> >> A guy comes in and enters his last name as RÖnngren.
> >>
> >> So what did the browser really give me; is it encoded
> >> in some way, like latin-1?  Does it depend on whether
> >> the name was cut and pasted from a Word doc. etc?
> >> Should I handle these internally as unicode?  Right
> >> now my database tables are latin-1 and things seem
> >> to usually work, but not always.
> >
> > Definitely handle them as Unicode. You'll receive them in some
> > encoding, probably UTF-8, and it depends on the browser. Ideally, your
> > back-end library (eg Flask) will deal with that for you.
> It varies by browser?
> So these records are coming in from all over the world.  How
> do people handle possibly assorted encodings that may come in?
>
> I'm using Web2py.  Does the request come in with an encoding
> built in?  Is that how people get the proper unicode object?

Yes. Normally, the browser will say "hey, here's a request body, and
this is the encoding and formatting".

Try it - see what you get.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread Akkana Peck
On Sat, Jun 29, 2019 at 6:31 AM Tobiah  wrote:
> Also, what do people do when searching for a record.
> Is there some way to get 'Ronngren' to match the other
> possible foreign spellings?

SequenceMatcher in difflib can do fuzzy string comparisons and
should work for cases like that. There are other methods too --
include "fuzzy" in your web searches and you'll probably find
several options.

...Akkana
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-06-28 Thread Terry Reedy

On 6/28/2019 4:25 PM, Tobiah wrote:

A guy comes in and enters his last name as RÖnngren.

So what did the browser really give me; is it encoded
in some way, like latin-1?  Does it depend on whether
the name was cut and pasted from a Word doc. etc?
Should I handle these internally as unicode?  Right
now my database tables are latin-1 and things seem
to usually work, but not always.


Unless you want to restrict your app to people with or converible to 
latin-1 (western Europe) names, you should use utf-8 or let the database

encode for you.


Also, what do people do when searching for a record.
Is there some way to get 'Ronngren' to match the other
possible foreign spellings?


I have seen a program that converts all latin-1 chars to ascii for matching.

--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list


Re: Use global, or not

2019-06-28 Thread DL Neil

On 29/06/19 1:44 AM, Cecil Westerhof wrote:

I have written a GUI program where I have quit a few global variables.
I did not like this, so I now use one global dict. Something like:
 global global_dict

...


Is that an acceptable way to do this?



If it works, isn't that the largest part of "acceptable"?

In each case, (previously discussed and/or below) you are taking 
advantage of "namespaces" to keep one 'lot' of values separated and 
distinct from others - as well as finding a means of 'passing them 
around'. The other half of the considerations is how the values are 
being retrieved/utilised within the mainline code.


An alternative might be to use a class. Then accessing a single value 
becomes instance.attribute, but when you have need for several 
attribute's values or to compute a value from several attributes, an 
instance.method() may simplify things.


I use the above idea for a 'configuration' class which has values built 
from constants/defaults, plus command-line arguments, etc (as 
appropriate to the application and user-needs).


Another approach might be to use a module. After import module as 
module_name, single-value access becomes module_name.cancelled_report (etc).


--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: change spacing to two instead of four with pep8 or flake8?

2019-06-28 Thread Cameron Simpson

On 07Apr2014 20:06, Dennis  wrote:

In Pylint you can change the spacing multiplier from 4 spaces to two
in its pylintrc, but for the life of me I cannot find a way to do this
with the flake8 / pep8 utilities.

I want to avoid ignoring E111 altogether if at all possible, because
it may catch other spacing problems that are not as obvious.


I ignore E111 and hope other linters catch stuff it will now miss.

I've also taken to having my files autoformatted with yapf on save, 
which makes a lot of formatting more rigorous.


My current lint script runs pyflakes, pep8 and pylint.

My personal lint script:

 https://bitbucket.org/cameron_simpson/css/src/tip/bin-cs/lint

My personal format script:

 https://bitbucket.org/cameron_simpson/css/src/tip/bin-cs/format

Take what you'd like.

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list