Re: Friday Finking: Imports, Namespaces, Poisoning, Readability
AFAIKT the "three" are readability, naming conflicts and source location. On 05/06/2020 01:15, DL Neil via Python-list wrote: - how do you like to balance these three (and any other criteria)? Readability is king. Or queen, if you prefer. Anything that damages readability drops dramatically in its desirability. One consequence of that is that I rarely use "import ... as", since as you mentioned, renamed libraries are a rich source of WTF moments. I would use "import numpy as np" (if I ever used numpy) because it seems to be standard, but I wouldn't type "import pygame as pg" despite having used PyGame extensively in the past. I tend to use "from xxx import yy_yy, " when I'm not importing many things from a library and their names are sufficiently obvious. The definitions of "not many" and "sufficiently obvious" are pretty flexible. In particular, I'll list more items as the qualified names get longer, as you noted. Source location is a non-issue; it's trivial to jump to the imports at the top of the file, look it up and jump back again. Or have two buffers viewing the same file; that's a technique I use quite a lot anyway. If I need to know the signature, that's what documentation is for. I would never rename an object I've imported using "as". It's just not worth the inevitable heartache. If that means I have namespace collisions, that's either a vote to use the qualified name or to change the name of whatever I wrote that clashes with it. - is your preference (or selection) influenced by the facilities offered by your favorite editor/IDE? Not really. I'm an EMACS user, so any of the "fancy" IDE handiwork is immediately out. The only reason you need an IDE is if your support tools suck (sorry, Windows users). - does your decision differ according to whether the 'target module' is one of yours, from the PSL, from some third party, corporate, ...? I'm more likely to change my own module to fit :-) - do you prefer PSL's importlib over Python's native import-s, for one of these (or any other) reason? Um, why would I? -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Re: Can't download Pygame and Pgzero
To whom it may concern, I have trouble installing the Pygame and Pgzero on Window. I based on the instruction on the "Computer Coding Python Games for Kids" by Carol Vorderman. Nothing works. I tried Python 3.6.2 as describe in the book and the latest version 3.8.3 still encounter on the same problem. I really need to get this sorted so my kid can spend his summer break mastering the coding. Brgs, -- https://mail.python.org/mailman/listinfo/python-list
Strange use of Lambda arrow
Hello to everyone, lately i building up an open source project, with some
collaborator, but one of them cannot contribute any more. He is a solution
architect so he is very skilled (much more than me!). I am now analysing
his code to finish the job but i don't get this use of the lambda arrow,
it's like he is deplaring the returned tipe in the function signature (as
you would do in Java). I have never seen something like this in python..
Can someone please explain to me this usage (the part regarding the
question is highlighted in yellow):
@classmethod
def extract_document_data(cls, file_path : str) -> DocumentData:
"""
Entry point of the module, it extracts the data from the document
whose path is passed as input.
The extraction strategy is automatically chosen based on the MIME
type
of the file.
@type file_path: str
@param file_path: The path of the document to be parsed.
@rtype: DocumentData
@returns: An object containing the data of the parsed document.
"""
mime = magic.Magic(mime=True)
mime_type = mime.from_file(file_path)
document_type = DocumentType.get_instance(mime_type)
strategy = cls.strategies[document_type]
return strategy.extract_document_data(file_path)
To be more verbose, this is the whole script:
from enum import Enum
import json
import magic
import docx
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTContainer, LTTextContainer
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
class DocumentType(Enum):
"""
Defines the handled document types.
Each value is associated to a MIME type.
"""
def __init__(self, mime_type):
self.mime_type = mime_type
@classmethod
def get_instance(cls, mime_type : str):
values = [e for e in cls]
for value in values:
if value.mime_type == mime_type:
return value
raise MimeNotValidError(mime_type)
PDF = 'application/pdf'
DOCX =
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
class MimeNotValidError(Exception):
"""
Exception to be raised when a not valid MIME type is processed.
"""
pass
class DocumentData:
"""
Wrapper for the extracted document data (TOC and contents).
"""
def __init__(self, toc : list = [], pages : list = [], document_text :
str = None):
self.toc = toc
self.pages = pages
if document_text is not None:
self.document_text = document_text
else:
self.document_text = ' '.join([page.replace('\n', ' ') for page
in pages])
def toc_as_json(self) -> str:
return json.dumps(self.toc)
class ExtractionStrategy:
"""
Base class for the extraction strategies.
"""
@staticmethod
def extract_document_data(file_path : str) -> DocumentData:
pass
class DOCXExtractionStrategy(ExtractionStrategy):
"""
It implements the TOC and contents extraction from a DOCX document.
"""
@staticmethod
def extract_document_data(file_path : str) -> DocumentData:
document = docx.Document(file_path)
body_elements = document._body._body
# Selecting only the elements from DOCX XML,
# as they're the only to contain some text.
text_elems = body_elements.xpath('.//w:t')
return DocumentData(document_text = ' '.join([elem.text for elem in
text_elems]))
class PDFExtractionStrategy(ExtractionStrategy):
"""
It implements the TOC and contents extraction from a PDF document.
"""
@staticmethod
def parse_toc(doc : PDFDocument) -> list:
raw_toc = []
try:
outlines = doc.get_outlines()
for (level, title, dest, a, se) in outlines:
raw_toc.append((level, title))
except PDFNoOutlines:
pass
return PDFExtractionStrategy.build_toc_tree(raw_toc)
@staticmethod
def build_toc_tree(items : list) -> list:
"""
Builds the TOC tree from a list of TOC items.
@type items: list
@param items: The TOC items.
Each item must have the following format: (, ).
E.g: [(1, 'Contents'), (2, 'Chapter 1'), (2, 'Chapter 2')]
@rtype: list
@returns: The TOC tree. The tree hasn't a root element, therefore it
actually is a list.
"""
toc = []
if items is None or len(items) == 0:
return toc
current_toc_level = toc
# Using an explicit stack containing the lists corresponding to
# the various levels of the TOC, to simulate the recursive building
# of the TOC tree in a more efficient way
toc_levels_stac
Re: Strange use of Lambda arrow
On Sat, Jun 6, 2020 at 2:36 AM Agnese Camellini wrote: > > Hello to everyone, lately i building up an open source project, with some > collaborator, but one of them cannot contribute any more. He is a solution > architect so he is very skilled (much more than me!). I am now analysing > his code to finish the job but i don't get this use of the lambda arrow, > it's like he is deplaring the returned tipe in the function signature (as > you would do in Java). I have never seen something like this in python.. > > Can someone please explain to me this usage (the part regarding the > question is highlighted in yellow): > > @classmethod > def extract_document_data(cls, file_path : str) -> DocumentData: I don't know what you highlighted in yellow, as that part didn't come through. But in Python, that arrow has nothing to do with lambda functions; it is exactly as you describe, annotating a function with the type of its return value. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Can't download Pygame and Pgzero
On 05/06/2020 11:54, Lily Sararat via Python-list wrote: I have trouble installing the Pygame and Pgzero on Window. I based on the instruction on the "Computer Coding Python Games for Kids" by Carol Vorderman. Nothing works. I tried Python 3.6.2 as describe in the book and the latest version 3.8.3 still encounter on the same problem. I really need to get this sorted so my kid can spend his summer break mastering the coding. Hi there Lily. We aren't Pygame specialists, but we can give it a go. However to do that you're going to need to give us some details. Which version of Windows are you using? What exactly did you do to install Pygame and Pgzero, in order, and what exactly went wrong. Please copy and paste any error messages, don't send screenshots because the mailing list will strip them off and we won't see them. -- Rhodri James *-* Kynesim Ltd -- https://mail.python.org/mailman/listinfo/python-list
Can I have a class with property named "from"
Hi, if I define class like this one: class abc: def __init__(self): self._from = None @property def from(self): return self._from @from.setter def from(self, value): self._from = value I get the error SyntaxError: invalid syntax because of the property named from. Looks like in python from is a keyword that cannot be used as a property name. I have to create a python object from a complex (nested) json object that has many keys with name "from" and value of date in string format. As I would like to keep property names as they are in the json file... is there a workaround? Regards. -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I have a class with property named "from"
On 06/05/2020 02:36 PM, [email protected] wrote: class abc: def __init__(self): self._from = None @property def from(self): return self._from @from.setter def from(self, value): self._from = value I get the error SyntaxError: invalid syntax because of the property named from. Looks like in python from is a keyword that cannot be used as a property name. I have to create a python object from a complex (nested) json object that has many keys with name "from" and value of date in string format. As I would like to keep property names as they are in the json file... is there a workaround? There is no workaround that allows a keyword to be used except as a keyword, other than making it a string. When faced with this kind of situation myself I use a synonym, like "since", or a translation, like "desde". -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I have a class with property named "from"
On 2020-06-05 22:50, Ethan Furman wrote: On 06/05/2020 02:36 PM, [email protected] wrote: class abc: def __init__(self): self._from = None @property def from(self): return self._from @from.setter def from(self, value): self._from = value I get the error SyntaxError: invalid syntax because of the property named from. Looks like in python from is a keyword that cannot be used as a property name. I have to create a python object from a complex (nested) json object that has many keys with name "from" and value of date in string format. As I would like to keep property names as they are in the json file... is there a workaround? There is no workaround that allows a keyword to be used except as a keyword, other than making it a string. When faced with this kind of situation myself I use a synonym, like "since", or a translation, like "desde". The usual workaround is to append an underscore: 'from_'. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange use of Lambda arrow
On 06Jun2020 02:40, Chris Angelico wrote: On Sat, Jun 6, 2020 at 2:36 AM Agnese Camellini wrote: Hello to everyone, lately i building up an open source project, with some collaborator, but one of them cannot contribute any more. He is a solution architect so he is very skilled (much more than me!). I am now analysing his code to finish the job but i don't get this use of the lambda arrow, it's like he is deplaring the returned tipe in the function signature (as you would do in Java). I have never seen something like this in python.. Can someone please explain to me this usage (the part regarding the question is highlighted in yellow): @classmethod def extract_document_data(cls, file_path : str) -> DocumentData: I don't know what you highlighted in yellow, as that part didn't come through. But in Python, that arrow has nothing to do with lambda functions; it is exactly as you describe, annotating a function with the type of its return value. The OP may be being confused by JavaScript, where they have "arrow functions", which are what Python calls lambda: anonymous functions. It uses an arrow in the syntax: (x,y) -> x+y To reiterate what Chris said: in Python the -> is just a type annotation, indicating the expected return type(s) for a function. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I have a class with property named "from"
On 06/05/2020 03:15 PM, MRAB wrote: On 2020-06-05 22:50, Ethan Furman wrote: There is no workaround that allows a keyword to be used except as a keyword, other than making it a string. When faced with this kind of situation myself I use a synonym, like "since", or a translation, like "desde". The usual workaround is to append an underscore: 'from_'. True, but ick. ;-) It's like a dangling preposition. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange use of Lambda arrow
On Sat, Jun 6, 2020 at 8:24 AM Cameron Simpson wrote: > The OP may be being confused by JavaScript, where they have "arrow > functions", which are what Python calls lambda: anonymous functions. It > uses an arrow in the syntax: > > (x,y) -> x+y > In JS, they're sometimes called "fat arrow" functions, because they are spelled "=>". Maybe there's some other language where they're spelled "->"? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange use of Lambda arrow
On 2020-06-06 01:01, Chris Angelico wrote: On Sat, Jun 6, 2020 at 8:24 AM Cameron Simpson wrote: The OP may be being confused by JavaScript, where they have "arrow functions", which are what Python calls lambda: anonymous functions. It uses an arrow in the syntax: (x,y) -> x+y In JS, they're sometimes called "fat arrow" functions, because they are spelled "=>". Maybe there's some other language where they're spelled "->"? I think it's Cameron who's confused. :-) The OP said "Java". Java has "->"; JavaScript has "=>". -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange use of Lambda arrow
On 06Jun2020 02:48, MRAB wrote: On 2020-06-06 01:01, Chris Angelico wrote: On Sat, Jun 6, 2020 at 8:24 AM Cameron Simpson wrote: The OP may be being confused by JavaScript, where they have "arrow functions", which are what Python calls lambda: anonymous functions. It uses an arrow in the syntax: (x,y) -> x+y In JS, they're sometimes called "fat arrow" functions, because they are spelled "=>". Maybe there's some other language where they're spelled "->"? I think it's Cameron who's confused. :-) Likely. It is months since I wrote any JavaScript, and I've never enjoyed it. It is a hellscape of callbacks and closures, and an object model as thin as Perl's. The OP said "Java". Java has "->"; JavaScript has "=>". Hah. Are there not languages where "=>" is an alternate spelling of greater-than-or-equal? Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Can I have a class with property named "from"
On 6/06/20 9:36 AM, [email protected] wrote: Hi, if I define class like this one: class abc: def __init__(self): self._from = None @property def from(self): return self._from @from.setter def from(self, value): self._from = value I get the error SyntaxError: invalid syntax because of the property named from. Looks like in python from is a keyword that cannot be used as a property name. I have to create a python object from a complex (nested) json object that has many keys with name "from" and value of date in string format. As I would like to keep property names as they are in the json file... is there a workaround? The from moduleNM import object/can't use a keyword issue has been discussed. When a JSON object is load-ed into a Python program, its native form is a dict. Thus, "from" will be one of the dict's keys, cf a Python identifier. Why have you chosen to go to the trouble of creating a separate data-attribute (with the from/_from/from_ name)? (I realise the above class is likely 'cut-down' to suit publication) Does the answer include terms such as 'understanding', 'control', 'easier to use', 'better suited to existing code'? Assuming a good reason (why wouldn't we?), then it is necessary for the Python object to include (or be able to access) 'serialise' and/or 'deserialise' routines - because Python objects will not do this, in and of themselves. This is the opportunity to rename the value between its JSON version and its internal (code) use. If there are <> then they can't all be called "from" anyway. Plus, a term such as "from", likely fails to convey its full meaning, eg a student might be enrolled_since, or "zljubisic" has been paid an higher salary rate_from. As such, 'expanding' its name would likely improve readability, comprehension, and thus code-quality! (I'm with the "ick" when it comes to 'artificial' name-mangling) -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
