Re: Python and GUI development

2014-12-01 Thread Ben Finney
Ganesh Pal ganesh1...@gmail.com writes:

 I want to design a GUI interface for my project . I wanted it to use it
 Python and it has to work on freebsd .   Please provide me the latest
 trends for GUI development with python.

A good starting point URL:https://wiki.python.org/moin/GuiProgramming.

-- 
 \   “Truth is stranger than fiction, but it is because fiction is |
  `\ obliged to stick to possibilities, truth isn't.” —Mark Twain, |
_o__)  _Following the Equator_ |
Ben Finney

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


Re: Quotation Ugliness

2014-11-26 Thread Ben Finney
Tim Daneliuk tun...@tundraware.com writes:

 The problem I am trying to solve is to determine whether the user
 needs to provide a sudo password or not.

Again, the ‘sudo’ program itself will figure this out and ask for a
password if it needs one.

Examining the command line isn't enough. Even if you find a ‘sudo’
command there, there are common circumstances where no password is
needed. The program handles all this, you can't predict it from outside.

 Right now, the program just naively checks the arguments to see if
 .startswith(sudo'). As the example given illustrates, that clearly
 fails if the sudo is given later in a longer pipeline.

The problem as you've presented it requires you to re-implement the
command-line parsing from whatever command shell is used. You will
necessarily fall short of that, no matter what you do.

Your best course is to get the requirements changed, as they are
currently not implementable.

-- 
 \ “Facts are stubborn things; and whatever may be our wishes, our |
  `\   inclinations, or the dictates of our passion, they cannot alter |
_o__)the state of facts and evidence.” —John Adams, 1770-12-04 |
Ben Finney

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


Re: Quotation Ugliness

2014-11-25 Thread Ben Finney
Tim Daneliuk tun...@tundraware.com writes:

 Here's the problem: Determine is the string S appears *outside* or
 *inside* any such quotation.

This is a problem for parsing text. There is no general, simple
solution.

If someone tries to convince you they have one, be highly suspicious: it
will either be not general, or not simple, or neither simple nor general.

 I know lots of ugly/complicated/heavyweight ways to solve this, but
 I'm wondering if any of you geniuses have a pythonic/elegant/short
 algo that solves this.

I would recommend one of the following, in descending order of
preference:

* Try very hard to change the requirements so that the input must be in
  a mature well-known format for which there are *existing*, maintained,
  reliable parsers. Use those instead of rolling your own.

* If that fails, then: Try very hard to drastically simplify the
  specified input format so that every possible input is either
  obviously invalid, or obviously has exactly one meaning.

* If that fails, then: Bite the bullet and acknowledge you will be
  entering the complexities of parsing text. Use a mature library for
  writing your parser; don't attempt to write a parsing library
  yourself. *This is the worst option*; changing the requirements for
  input will be much less pain than this.

-- 
 \   “Fear him, which after he hath killed hath power to cast into |
  `\   hell; yea, I say unto you, Fear him.” –Jesus, as quoted in Luke |
_o__) 12:5 |
Ben Finney

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


Using a password with ‘sudo’ (was: Quotation Ugliness)

2014-11-25 Thread Ben Finney
Tim Daneliuk tun...@tundraware.com writes:

 Here's a usecase - I want to know whether I need to use a sudo
 password when the user passes a command on the command line of a
 program:

[…]

 In the first instance, I need the sudo passoword, in the second I don't.

I don't understand what “need a sudo password” means, or what you would
do differently if you detect one case or the other. It's the ‘sudo’
command itself that determines whether you need a password, so what is
your Python code going to do differently?

-- 
 \“We have to go forth and crush every world view that doesn't |
  `\believe in tolerance and free speech.” —David Brin |
_o__)  |
Ben Finney

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


Re: PyWart: Python's import statement and the history of external dependencies

2014-11-22 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 Just out of curiosity, why does the stdlib need modules for
 manipulating .wav and other sound files, but we have to go to PyPI to
 get a PostgreSQL client? It's a queer world...

I would venture the follow two reasons, either of which is sufficient to
explain the difference:

* Modules enter the standard library only if they are judged both to be
  good quality *and* have a credible promise to continue to maintain
  them in the standard library on an ongoing basis.

  If one module has reliable maintainers offering to do the work and
  another does not, the latter will not be a candidate for inclusion in
  the Python standard library.

* Modules enter the standard library only if their feature set is stable
  enough that they can remain essentially unchanged, feature-wise, for
  many years and still be widely useful.

  For a data stream format (like WAV and other mature formats), a module
  working well today is likely to work just as well for the same purpose
  in several years's time, long enough for today's Python to go through
  its full life cycle of support.

  PostgreSQL is a full-blown system that is itself under continual
  development, and its APIs continually change to match. Whatever Python
  API for PostgreSQL gets put into the standard library today is likely
  to be obsolete long before today's version of Python gets close to
  ending support. That makes it a poor candidate for inclusion in the
  standard library.

-- 
 \   “The generation of random numbers is too important to be left |
  `\to chance.” —Robert R. Coveyou |
_o__)  |
Ben Finney

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


Python-friendly IDE (was: Python IDE.)

2014-11-21 Thread Ben Finney
kiloran kiloran.pub...@gmail.com writes:

 I'm very happy with Eclipse

Eclipse has many benefits:

* It is not Python-specific. I consider it a grave mistake to invest a
  lot of effort in learning a Python-specific development environment,
  when there are plenty of good environments that do not tie you
  especially to one language.

* It respects software freedom, i.e. it is licensed as free software
  URL:https://www.eclipse.org/legal/epl-v10.html. This has many
  benefits URL:https://fsfe.org/about/basics/freesoftware.en.html.

* Because it is free software, any motivated programmer (not only the
  vendor) can adapt it for any platform, so as a result it runs fine on
  every major desktop platform today.

* Because it is free software, the user community (not only the vendor)
  can direct how it meets their needs, and there is a thriving ecosystem
  of plug-ins to adapt it to various workflows.

* Because it is free software, your investment spent learning to use it
  will not become worthless when the vendor loses interest in
  maintaining it.

* Because it is free software, the user community is free to set up an
  ecosystem that works with it, and they have: the Eclipse Marketplace
  URL:https://marketplace.eclipse.org/.

* Because it is free software with a thriving community, there are many
  resources available for putting it to work with popular languages like
  Python:

  * PyDev URL:http://pydev.org/ makes Eclipse into a Python IDE.

  * Lars Vogel maintains a tutorial for driving Eclipse and PyDev
URL:http://www.vogella.com/tutorials/Python/article.html.

  * Version control integration, using either Mercurial
URL:http://mercurial.selenic.com/wiki/MercurialEclipse
or Git URL:https://www.eclipse.org/egit/.

  * and more: build system integration, unit testing integration, code
refactoring, packaging, etc.

I don't actually use Eclipse (Unix is my IDE). But the fact that it's
free software with a thriving user-community-driven ecosystem makes me
very glad it exists.

For a counterpoint, with much discussion of the downsides, see
URL:https://wiki.python.org/moin/EclipsePythonIntegration.

-- 
 \ “Men never do evil so completely and cheerfully as when they do |
  `\it from religious conviction.” —Blaise Pascal (1623–1662), |
_o__)   Pensées, #894. |
Ben Finney

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


Import a module from a specific file path (was: PyWart: Python's import statement and the history of external dependencies)

2014-11-21 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 In other words, what you want is:

 # today's method, import based on search path
 import sys
 # new explicit path method
 import '/usr/local/lib/python3.5/lib-dynload/math.cpython-35m.so'

I don't think I'd ever want to specify an absolute file path for the
module. But it would make my Python life immeasurably better if I could
specify *relative* file paths for importing a module.

import '../foo/bar/beans.py' as beans

 Can you tell me, please, how this is going to work for *any* system
 other than the one it was built on?

Allowing relative paths makes this portable, so long as the
application's relative tree structure is maintained.

 There are a VERY VERY few cases where you really do want to import a
 module from a specific file path. For those situations, there are
 already techniques you can use. Why change the behaviour of import
 itself?

An example:

* I write a program, ‘fooprog’, using the hypothetical “import a module
  at a specified file path” feature::

#! /usr/bin/python3

import './bar/beans.py' as beans

beans.do_stuff()

* The program ‘fooprog’ and the module ‘beans.py’ are in a sensible
  directory structure::

foo-proj-1.0/
foo/
__init__.py
fooprog
bar/
__init__.py
beans.py
tests/
__init__.py
test_fooprog.py
test_bar.py

* Running the program ‘fooprog’ invokes Python (via its standard
  shebang), which invokes the file ‘fooprog’ as the ‘__main__’ module
  *with no package awareness*.

  Or, equivalently, ‘python foo/fooprog’ skips the shebang step.

* Regardless of package considerations, specifying ‘./bar/beans.py’
  locates the module ‘beans’ for import, just fine.

That example will work in the presence of this “import from a named file
location” feature.

But it will fail with the standard Python import feature today. How
would you expect this example to change so it will work with current
Python?

Solutions usually seem to entail contortions of cluttering the import
block by discovering the current path, and fussing around with
‘sys.path’, before finally doing the import::

#! /usr/bin/python3

import sys
import os.path

program_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(program_dir)
if not parent_dir in sys.path:
sys.path.insert(1, parent_dir)

import foo.bar.beans as beans

beans.do_stuff()

Maybe you can suggest a better portable method to do this today in
Python.

Importantly, once you've come up with how to do it today in Python: Do
you really consider that superior to simply specifying a filesystem path
for a file containing the module?

-- 
 \“I'd take the awe of understanding over the awe of ignorance |
  `\  any day.” —Douglas Adams |
_o__)  |
Ben Finney

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


Re: Import a module from a specific file path

2014-11-21 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 So can you simply:

 $ python -m foo.fooprog

 ? (or 'python3', either way)

So, that's a pretty awful user interface. (The file is named ‘fooprog’
because it's an executable, intended to be run directly at the command
line.) That solution would be rather inferior to the program being able
to import modules when invoked as the top-level program.

Can you suggest solutions that allow invoking the program as ‘./fooprog’
to work?

-- 
 \ “In economics, hope and faith coexist with great scientific |
  `\  pretension and also a deep desire for respectability.” —John |
_o__)Kenneth Galbraith, 1970-06-07 |
Ben Finney

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


Re: isiter builtin

2014-11-16 Thread Ben Finney
Garrett Berg googb...@gmail.com writes:

 However, there are times when I want to do type checking, and the
 builtin function *isinstance* is of great use.

I would advise that when you think you want type checking, you are
probably being overly restrictive.

 However, this function fails to be satisfactory in returning whether
 the object is a valid iterator. The call hasattr(obj, '__iter__') also
 fails because str and bytes types both have that

Yes, because both ‘str’ and ‘bytes’ objects are valid iterables.


Using ‘isinstance’ in particular is a code smell: it breaks duck typing
(checking not for the object's type, but for how the object behaves,
which is usually what matters) and is almost always the wrong choice.

Not *always* the wrong choice, which is why it's provided, and which is
why I call it a code smell: a strong but not infallible sign something
is wrong with the code as written.

When you reach for ‘isinstance’ (LBYL, which is un-Pythonic), instead
ask yourself: ignoring what type this object is, how do I want it to
behave, and should I just use it in the expectation that it will raise
an exception if it doesn't support that (EAFP, which is very Pythonic)?

-- 
 \ “What is needed is not the will to believe but the will to find |
  `\   out, which is the exact opposite.” —Bertrand Russell, _Free |
_o__)   Thought and Official Propaganda_, 1928 |
Ben Finney

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


Messages from code analysis tools (was: Using map())

2014-11-16 Thread Ben Finney
Ned Batchelder n...@nedbatchelder.com writes:

 Pylint isn't useful until you've tailored the messages.

Definitely agreed.

 The pylint message that always irked me was:

 W0142: Used * or ** magic

 magic? They're features of the language!

It's a warning, because the use of that feature clobbers the static code
inspection you've asked for. PyLint is warning you “because the code
uses this feature, I can't say anything about undefined names”.

-- 
 \   “The future always arrives too fast, and in the wrong order.” |
  `\—Alvin Toffler |
_o__)  |
Ben Finney

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


Re: How modules work in Python

2014-11-16 Thread Ben Finney
Abdul Abdul abdul.s...@gmail.com writes:

 Thanks for your nice explanation. For your answer on one of my
 questions:

(Please use “interleaved” posting style, for showing quoted material and
your responses 
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style.)

 * Modules don't have methods. open is an ordinary function in the module.*

 Isn't method and function used interchangeably?

No (or more accurately: if someone does use those interchangeably,
they're not correctly describing Python).

A method is always a function, but a function is not always a method.

A method is a function bound to a specific object instance.

-- 
 \  “As soon as we abandon our own reason, and are content to rely |
  `\   upon authority, there is no end to our troubles.” —Bertrand |
_o__)Russell, _Unpopular Essays_, 1950 |
Ben Finney

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


Re: Error when trying to open an image

2014-11-16 Thread Ben Finney
Abdul Abdul abdul.s...@gmail.com writes:

 Thanks for your kind reply.

Abdul, please don't top-post. Instead, trim the quoted material just to
what you're responding to; then post your responses interleaved
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style.

 I got the following output:

 Process finished with exit code 0

 So, what is the purpose of open() here?

I see no context for this question. Where is “here”?

Can you write a very minimal example of a complete program you're asking
about, and post it here so we can see what is confusing you?
URL:http://sscce.org/

-- 
 \   “I bet one legend that keeps recurring throughout history, in |
  `\  every culture, is the story of Popeye.” —Jack Handey |
_o__)  |
Ben Finney

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


Re: caught in the import web again

2014-11-15 Thread Ben Finney
Charles T. Smith cts.private.ya...@gmail.com writes:

 Now, I'm getting these errors:

Please reduce the problem to a minimal, complete example demonstrating
the behaviour URL:http://sscce.org/ so that you can show us exactly
what's happening.

   AttributeError: 'module' object has no attribute ...

 (what is 'module'?)

The type of the object which doesn't have the attribute. It's saying
you're tring to access an attribute on a particular object, and that
object (which is of type ‘module’, hence it is a “'module' object”)
doesn't have that attribute.

 Is there a way to resolve this without having to restructure my code 
 every couple of days?

Not knowing what the actual problem is, it's difficult to say.

Please come up with a (contrived, if you like) minimal clear example of
what's happening – i.e. make it from scratch, without irrelevant parts
from the rest of your program, but ensure it still does what you're
confused by – and present it here.

-- 
 \  “It's a terrible paradox that most charities are driven by |
  `\ religious belief.… if you think altruism without Jesus is not |
_o__)  altruism, then you're a dick.” —Tim Minchin, 2010-11-28 |
Ben Finney

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


Re: encode and decode builtins

2014-11-15 Thread Ben Finney
Garrett Berg googb...@gmail.com writes:

 I made the switch to python 3 about two months ago, and I have to say
 I love everything about it, *especially* the change to using only
 bytes and str (no more unicode! or... everything is unicode!) As
 someone who works with embedded devices, it is great to know what data
 I am working with.

THanks! It is great to hear from people directly benefiting from this
clear distinction.

 However, there are times that I do not care what data I am working
 with, and I find myself writing something like:

 if isinstance(data, bytes): data = data.decode()

Why are you in a position where ‘data’ is not known to be bytes? If you
want ‘unicode’ objects, isn't the API guaranteeing to provide them?

 This is tedious and breaks the pythonic method of not caring about
 what your input is.

I wouldn't call that Pythonic. Rather, in the face of ambiguity (“is
this text or bytes?”), Pythonic code refuses the temptation to guess:
you need to clarify what you have as early as possible in the process.

 If I expect that my input can always be decoded into valid data, then
 why do I have to write this?

I don't know. Why do you have to?

-- 
 \ “God was invented to explain mystery. God is always invented to |
  `\ explain those things that you do not understand.” —Richard P. |
_o__)Feynman, 1988 |
Ben Finney

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


Re: How to recover bytes function?

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 file = open('data.bin', 'rb')
 bytes = file.read()

These are both terrible names, not least because they clobber the
built-in objects ‘file’ and ‘bytes’.

Don't name an object for *or not only for) its data type. Instead,
choose names that convey the *purpose* for the object.

-- 
 \ “Alternative explanations are always welcome in science, if |
  `\   they are better and explain more. Alternative explanations that |
_o__) explain nothing are not welcome.” —Victor J. Stenger, 2001-11-05 |
Ben Finney

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


Re: io.UnsupportedOperation: fileno

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 What is the problem and how to overcome this problem?

First, please provide context (just as the previous respondent did), so
your message may be understood in the absence of those prior.
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

As to your question: Please describe what you expected, and how the
behaviour was different. Unless we know what you think is wrong, we
don't know what “the problem” is.

-- 
 \ “Sittin' on the fence, that's a dangerous course / You can even |
  `\   catch a bullet from the peace-keeping force” —Dire Straits, |
_o__)   _Once Upon A Time In The West_ |
Ben Finney

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


Re: io.UnsupportedOperation: fileno

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 fileno() in not supported.

It is supported, but it is behaving as the documentation describes
URL:https://docs.python.org/3/library/io.html#io.IOBase.fileno.

 Is it only in 3.1? What is the workaround?

Expect an exception when you ask for the file descriptor on a stream
that does not use a file descriptor.

-- 
 \   “Pinky, are you pondering what I'm pondering?” “Well, I think |
  `\   so, Brain, but ‘apply North Pole’ to what?” —_Pinky and The |
_o__)   Brain_ |
Ben Finney

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


Re: fileno() not supported in Python 3.1

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 Is there a workaround?

Please take the time to gather your thoughts, do not fire off a rapid
series of terse scattered questions.

What is it you're trying to do? What approach are you intending to take?

-- 
 \“I was in Las Vegas, at the roulette table, having a furious |
  `\ argument over what I considered to be an odd number.” —Steven |
_o__)   Wright |
Ben Finney

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


Re: Bad file descriptor

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 import os
 os.write(1, b'Hello descriptor world\n')
 OSError: Bad file descriptor

It works fine for me::

 import os
 os.write(1, b'Hello descriptor world\n')
Hello descriptor world
23

You don't say which Python, or which version, you're using. In the
absence of different information, most of us will assume the latest
stable release of CPython. Currently, that is CPython 3.4.

-- 
 \  “I am too firm in my consciousness of the marvelous to be ever |
  `\   fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__) Shadow-Line_ |
Ben Finney

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


Re: fileno() not supported in Python 3.1

2014-11-13 Thread Ben Finney
satishmlm...@gmail.com writes:

 How to get file descriptor number for the following:
 sys.stdin
 sys.stdout
 sys.stderr

Why do you need this? What are you intending to do?

-- 
 \   “Crime is contagious… if the government becomes a lawbreaker, |
  `\  it breeds contempt for the law.” —Justice Louis Brandeis |
_o__)  |
Ben Finney

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


Converting a PHP app to Python + Django (was: Communicating with a PHP script (and pretending I'm a browser))

2014-11-12 Thread Ben Finney
Michael Torrie torr...@gmail.com writes:

 If the shop is entire a PHP shop, and no one knows python, then
 rewriting things in Python and Django is a really bad idea.

It can be done well; see “Transitioning from PHP to Django on the sly”
URL:http://pyvideo.org/video/2233/transitioning-from-php-to-django-on-the-sly.

The presenter emphasises that one of the more important requirements is
to convince everyone: the management, the developers, even stakeholder
customers/users.

 I've worked in shops before where one person comes in with a new
 language, writes some code, then leaves, leaving us stranded as it
 were.

Right. On the other hand, I've worked in shops where the big PHP code
base is seen by all as a legacy code base, and the stakeholders were
quite open to being convinced to migrate — provided a clear migration
path.

That's what the above presentation goes into. I recommend it.

-- 
 \ “The double standard that exempts religious activities from |
  `\   almost all standards of accountability should be dismantled |
_o__)   once and for all.” —Daniel Dennett, 2010-01-12 |
Ben Finney

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


[issue22843] doc error: 6.2.4. Match Objects

2014-11-12 Thread Ben Finney

Ben Finney added the comment:

The current wording of the passage “Match objects always have a boolean value 
of True” implies that the value compares equal to the ‘True’ constant. That 
implication is incorrect.

I disagree with R. David Murray; if we want to say that a value is considered 
true *in a boolean context*, that's very different from saying it has the 
“True” value.

Georg, “evaluates true in a boolean context” has the meaning you're seeking; it 
is chosen precisely because it does *not* imply equality to the True constant.

--
nosy: +bignose

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue22843
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Trouble with python

2014-11-11 Thread Ben Finney
Ashleigh Deal a.e.d...@student.reading.ac.uk writes:

 I am trying to use python as part of my part 3 project but my coding
 has suddenly stopped working. I am using python(x,y) and it was
 working perfectly a couple of weeks ago but recently it hasn't been.

What has changed in the meantime, which could conceivably affect the
program's behaviour?

 Every time it runs, the program crashes and becomes unresponsive
 resulting in me having to exit.

When you say “the program crashes”, that implies it stops with a fatal
error. What is the complete error message text?

-- 
 \ “If you ever teach a yodeling class, probably the hardest thing |
  `\  is to keep the students from just trying to yodel right off. |
_o__) You see, we build to that.” —Jack Handey |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Ben Finney
Peter Cacioppi peter.cacio...@gmail.com writes:

 I get the impression that most Pythonistas aren't as habituated with
 assert statements as I am. Is that just a misimpression on my part? If
 not, is there a good reason to assert less with Python than other
 languages?

I don't know about comparisons like “use less with Python than other
languages”. But I can explain why I don't use ‘assert’ much.

 As far as I can tell, Python supports assert perfectly well. When run
 with the optimization flagging, the asserts are truly removed.

Exactly. I prefer the code I write to have as few surprises as possible.
A reader familiar with Python should be able to read it and know what it
does; ideally, even if that reader doesn't recall every detail of how
Python operates.

An ‘assert’ statement in the code will sometimes be active, and
sometimes be a no-op, for *exactly* the same code under different
circumstances. That's a trap for the reader, and I'd rather not set it.

 I think one needs to take care with some basic assert coding - it's
 not a substitute for unit tests, it doesn't absolve you of normal
 exception responsibilities, and, most of all, it should be used for
 passive inspection and not action. But given these guidelines, I still
 find it very useful as active comments.

It's fine for debugging code while developing. But, in my opinion, it
should never stay there, and should be removed before committing to VCS.

-- 
 \ “True greatness is measured by how much freedom you give to |
  `\  others, not by how much you can coerce others to do what you |
_o__)   want.” —Larry Wall |
Ben Finney

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


Re: Python modules

2014-11-11 Thread Ben Finney
Will Acheson willyac...@gmail.com writes:


 I have had a lot of trouble with executing relative imports with some
 of my projects in python.

 Are there any best practices or methods besides '../../' type
 hard-coding?

The important point to learn with Python's import system, as contrasted
with various other languages, is that it is *intentionally* abstracted
from the filesystem hierarchy.

That allows all kinds of helpful infrastructure, but it also comes with
the cost of learning how to let Python know where modules are to be
imported from; it's not a simple case of stating filesystem locations.

The point which tripped me up for a long time, and which I have to keep
reminding myself of:


Python looks for modules in its import search path. Corollary: structure
your project into a hierarchy of packages, including the top level, and
specify all relative imports starting at that top-level package.


Often the cause of my intra-project import woes comes from having
several *discrete* packages, but trying to do relative imports between
them::

hurgen/# Note: ‘hurgen’ is not a Python package.
foo/
__init__.py
spam.py
beans.py
bar/
__init__.py
eggs.py
ham.py

This is a poor structure, because Python needs to be told about each of
‘foo’ and ‘bar’ separately if relative imports are to work. Worse, a
module invoked as the top-level module (e.g. ‘eggs.py’) can't do imports
relative to itself, because it isn't even aware it's in a package!

Better is to structure the project explicitly under a top-level named
Python package::

hurgen/
__init__.py
foo/
__init__.py
spam.py
beans.py
bar/
__init__.py
eggs.py
ham.py

and import all the project's modules relative to the ‘hurgen’ package.

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


Re: I love assert

2014-11-11 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 We love 'assert' so much that we have 20-30 'assertXYZ' variations in
 unittest.

A function will not be disabled by a run-time option to the Python
interpreter.

 The statement 'assert expression' is almost equivalent to

 if not expression: raise AssertionError('expression')

With the important difference that this will be active no matter what
options Python's interpreter is run with. That makes it quite a
different proposition from using ‘assert’ statements.

-- 
 \ “You don't need a book of any description to help you have some |
  `\kind of moral awareness.” —Dr. Francesca Stavrakoloulou, bible |
_o__)  scholar, 2011-05-08 |
Ben Finney

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


Re: html page mail link to webmail program

2014-11-11 Thread Ben Finney
Ethan Furman et...@stoneleaf.us writes:

 My wife (using a Win7 machine) will be on a web page that has a link
 to mail somebody.  She clicks on it, and it opens the currently
 installed but unused Thunderbird.

 Ideally, what would happen is a new window/tab would open to gmail
 with a new compose window with the email address in place and the
 cursor in the subject line.

What is the Python question? I can't see anywhere that you would be
using Python code to address this.

-- 
 \“Some people, when confronted with a problem, think ‘I know, |
  `\   I'll use regular expressions’. Now they have two problems.” |
_o__)   —Jamie Zawinski, in alt.religion.emacs |
Ben Finney

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


Re: Combining lists to dictionary

2014-11-11 Thread Ben Finney
Denis McMahon denismfmcma...@gmail.com writes:

 Hi

 Given x,y are a lists of keys and value that I wish to combine to a 
 dictionary, such that x[n] is the key for value y[n], which is preferred:

 z = {a:b for (a,b) in zip(x,y)}

This one, with the caveat to use PEP-8 compatible formatting::

z = {a: b for (a, b) in zip(x, y)}

 z = {x[n]:y[n] for n in range(min(len(x),len(y)))}

Too much indirection for no gain that I can see.

 The zip feels more elegant, but it seems clunky to use the zip method to 
 create a list of tuples just to split them up into key:value pairs.

I think ‘zip’ has this as a primary intended purpose, so it seems fine
to me.

-- 
 \ “Of all classes the rich are the most noticed and the least |
  `\  studied.” —John Kenneth Galbraith, _The Age of Uncertainty_, |
_o__) 1977 |
Ben Finney

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


Re: html page mail link to webmail program

2014-11-11 Thread Ben Finney
Ethan Furman et...@stoneleaf.us writes:

 Okay, the explicit Python question: Clicking on a mail link in a web
 browser can start an external program. I would like that external
 program to be a Python script that [controls an already-running web
 browser to visit a URL and operate a web application].

 Surely this can be done in Python.

Perhaps. I'd advise a web search for “python script web browser”, and be
prepared for also learning how your specific operating system allows
programs to control each other in separate processes.

-- 
 \   “Either he's dead or my watch has stopped.” —Groucho Marx |
  `\   |
_o__)  |
Ben Finney

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


Re: I love assert

2014-11-11 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  An ‘assert’ statement in the code will sometimes be active, and
  sometimes be a no-op, for *exactly* the same code under different
  circumstances. That's a trap for the reader, and I'd rather not set
  it.

 This is no worse than other forms of preprocessor magic.

That other languages do it doesn't argue in favour of it. It argues,
rather, that we should be glad not to have it in our Python code.

 Again, not materially different from assert, and plenty of projects
 have this. Maybe people just need to understand assert == DEBUG and
 all's clear?

The more things people need to keep in mind when reading my code that
isn't stated explicitly in the code, the worse I consider the code to
be.

Python is a small, clear, expressive language. It has the valuable
property that one does not need to keep in mind a lot of reminders of
unexpected behaviour; good Python code behaves as it explicitly says it
will, with very few implied surprises.

To preserve this valuable but fragile property, I recommend treating
‘assert’ as a clever but obfuscatory trick, opposed to that property of
Python. So an ‘assert’ statement should, IMO, not remain in the code
past a debugging session.

-- 
 \  “The entertainment industry calls DRM security software, |
  `\ because it makes them secure from their customers.” —Cory |
_o__) Doctorow, 2014-02-05 |
Ben Finney

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


Re: What does (?Pname) pattern syntax do?

2014-11-10 Thread Ben Finney
satishmlm...@gmail.com writes:

 What does ?P and part1 match in the following piece of code?

Learn about Python's regular expression features from the documentation
URL:https://docs.python.org/3/library/re.html.

Experiment with regular expressions using online tools such as
URL:https://pythex.org/.

-- 
 \   “From the moment I picked your book up until I laid it down I |
  `\was convulsed with laughter. Someday I intend reading it.” |
_o__)—Groucho Marx |
Ben Finney

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


Re: Python modules

2014-11-09 Thread Ben Finney
Steve Hayes hayes...@telkomsa.net writes:

 I have a book on Python that advocates dividing programs into modules,
 and importing them when needed.

Which book is this? (This is not essential to your question, but it
might help to gauge your broader learning environment.)

 I can understand doing that in a compiled language, where different
 modules can be imported from all sorts of places when the program is
 compiled.

Python is a compiled language; when you run a Python program a necessary
step is to compile the Python source to a bytecode for actual execution.

Usually, the compilation step is done dynamically; but (barring
contrived examples) it is always done prior to running the program.

 But I understand that Python is an interpreted language

The two are not mutually exclusive. The Python interpreter works with
compiled Python code, it does not execute the source directly.

 If I wrote a program in Python like that, and wanted to run it on
 another computer, how would it find all the modules to import at
 run-time, unless I copied the whole directory structure over to the
 other computer?

That's the idea, yes. You need to distinguish between:

* The standard library: installed along with the Python interpreter when
  you install that, and available on the default module search path.

* Third-party modules: installed using your package manager (ideally by
  the operating system package manager), again to a location already
  part of the default module search path on your system.

* Modules specific to the application you're writing: Keep these in a
  known hierarchy, and use the distribution tools to package them to
  keep them together when distributing to oher machines.

Use abolute import for standard library and third-party modules. Use
relative import for application-private modules.

This ensures your aplication's private modules don't conflict with
current or future names of modules from the standard library or third
parties.

You are working through the Python tutorial step by step, right?
URL:https://docs.python.org/3/tutorial/ This topic is covered when you
learn about modules URL:https://docs.python.org/3/tutorial/modules.html.

-- 
 \   “I am amazed, O Wall, that you have not collapsed and fallen, |
  `\since you must bear the tedious stupidities of so many |
_o__)  scrawlers.” —anonymous graffiti, Pompeii, 79 CE |
Ben Finney

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


Re: Python modules

2014-11-09 Thread Ben Finney
Steve Hayes hayes...@telkomsa.net writes:

 So if I want to run it on another computer, where do I look for the
 compiled executable program to copy?

You generally don't do that (the compiled files tend to be specific to
various aspects of the target platform). This is a way that i's
important to remember that most Python interpreters require compiled
Python code.

Instead, to have a Python program run on a different computer, the files
to copy are the *source* files — preferably, in the hierarchy those
files expect.

You can do this with ‘rsync’ URL:https://rsync.samba.org/ for simple
cases.

For more complex cases, look into Python's distribution and packaging
tools URL:https://python-packaging-user-guide.readthedocs.org/.

For even more complex cases (e.g. where the Python code is only part of
a more diverse code base), look into deployment systems and operating
system packages.

-- 
 \ “When we pray to God we must be seeking nothing — nothing.” |
  `\—Francis of Assisi |
_o__)  |
Ben Finney

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


Re: What for -- for? (was A bug?)

2014-10-29 Thread Ben Finney
Zachary Ware zachary.ware+pyl...@gmail.com writes:

 […] just to avoid inconvenient line-wrapping (that I can avoid just by
 sticking to 80 column lines in the first place :).

That is a valid solution. If you have the discipline to stick to it,
congratulations :-)

-- 
 \“If you ever drop your keys into a river of molten lava, let |
  `\ 'em go, because, man, they're gone.” —Jack Handey |
_o__)  |
Ben Finney

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


Re: What for -- for? (was A bug?)

2014-10-28 Thread Ben Finney
Zachary Ware zachary.ware+pyl...@gmail.com writes:

 Of course, Gmail decided to wrap my long line for me. In case it's not
 obvious, that should be a single line.

Right, GMail is a poor choice for composing messages. You might get
better results installing a proper mail client, and communicating via
IMAP.

-- 
 \“Pinky, are you pondering what I'm pondering?” “Wuh, I think |
  `\  so, Brain, but how will we get three pink flamingos into one |
_o__) pair of Capri pants?” —_Pinky and The Brain_ |
Ben Finney

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


Dive Into Python 3, good tutorial (was: Newbie suggestion: nice tutorial)

2014-10-26 Thread Ben Finney
Martin S shieldf...@gmail.com writes:

 So it was back to the internet - and this one seems pretty
 comprehensive and understandable:

 http://www.diveintopython3.net/

Yes, Mark Pilgrim wrote this originally for Python 2, and it was one of
the best even then. The revised edition for Python 3 is highly
recommended.

 It doesn't cover the latest point version of Python (it's still Python
 3), but I hope it doesn't matter much?

You're right, it is still a good tutorial.

Unfortunately, the primary author has disappeared
URL:http://en.wikipedia.org/wiki/Mark_Pilgrim#.22Disappearance.22_from_the_Internet.

Fortunately, the work is free software, so every recipient already has
full permission to improve it and share the result.

Does anyone know of an active project maintaining this great resource
and releasing newer versions?

-- 
 \   “If you do not trust the source do not use this program.” |
  `\—Microsoft Vista security dialogue |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 Do you really not see the connection between counting and summing?

Connection? Of course. But I also see a huge distinction. I'm surprised
you could misunderstand my position to the extent you think such a
question needs to be asked.

The difference between “sum these values” versus “count these values” is
important. That's at the root of why I find it confusingly wrong to sum
True or False values.

Do you really not see the distinction between counting and summing?

The question is just as silly that way.

 If you have three apples, and I have two apples, then in total we have
 (count the apples: one two three, four five) five apples.

If you have three apples in one basket, and I have two apples in one
basket, “sum the baskets” is quite a different operation from “count the
baskets”.

[3, 2]

What is the sum of those values?

How many values are there?

The distinction between those is why I find it unhelpful to express “how
many values?” with “sum them”.

 Alas, you missed the bigger bug: I'm counting *blank lines*, not
 non-blank lines. You need a `not` in there.

Which is, shall we say, not incompatible with the position that the
“count the matches by summing bools” method is an unclear expression of
intent :-)

-- 
 \ “Sittin' on the fence, that's a dangerous course / You can even |
  `\   catch a bullet from the peace-keeping force” —Dire Straits, |
_o__)   _Once Upon A Time In The West_ |
Ben Finney

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


Re: id == vs is

2014-10-26 Thread Ben Finney
Dan Stromberg drsali...@gmail.com writes:

 Are the following two expressions the same?

 x is y

 Id(x) == id(y)

It depends what you mean by “the same”.

Do they give the same result? Sometimes yes, sometimes no. It depends on
what the types of the values are.

Do they express the same intent? Always no. The first queries object
identity, the second queries object equality.

-- 
 \  “Ridicule is the only weapon which can be used against |
  `\   unintelligible propositions.” —Thomas Jefferson, 1816-07-30 |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Joshua Landau jos...@landau.ws writes:

 Guido van Rossum answered Jul 28 '11 at 21:20,
 http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints
  False==0 and True==1, and there's nothing wrong with that.

Guido is incorrect. I've already stated what's wrong.

That's different from saying I want to change how Python behaves *now*,
of course. But to say “there's nothing wrong with that” dismisses the
problems without addressing them. Guido isn't perfect, so that's okay.

-- 
 \“Telling pious lies to trusting children is a form of abuse, |
  `\plain and simple.” —Daniel Dennett, 2010-01-12 |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-26 Thread Ben Finney
Joshua Landau jos...@landau.ws writes:

 On 27 October 2014 02:28, Ben Finney ben+pyt...@benfinney.id.au wrote:
  Guido is incorrect. I've already stated what's wrong.

 You were arguing about what Guido thinks.

I don't know where I did that; to my knowledge, this is the first time
I've mentioned Guido, and it's in rebuttal to his authority on the issue
of whether “there's nothing wrong with” bool-as-a-special-int.

(On the separate issue of whether Guido is an authority on how Python
will behave, I haven't even commented. To be clear: yes, he is the BDFL
and therefore is authoritative on that issue.)

 Regardless, I feel you're making this out as a black and white issue.

There either is something problematic with a behaviour, or there isn't.

The *degree* of wrongness can vary. I'm merely pointing out that, in
this case, it's non-zero.

-- 
 \ “I must say that I find television very educational. The minute |
  `\   somebody turns it on, I go to the library and read a book.” |
_o__)—Groucho Marx |
Ben Finney

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


Re: Classes and the command line

2014-10-26 Thread Ben Finney
Seymore4Head Seymore4Head@Hotmail.invalid writes:

 I am trying to learn classes.
 I am currently using Python 2.7 at the command line.

(I think you mean “the interactive Python interpreter”, or just “the
Python shell”.)

Since you are learning Python, I will strongly recommend you ignore
Python 2 unless it becomes unavoidable.

Instead, learn Python 3 primarily; it is much better because it omits a
bunch of legacy behaviour you don't need.

 If you try to type commands at the [interactive shell] and make the
 slightest mistake you have to start over.

Right. There is line-by-line history, and editing enabled with the
“readline” plug-in. (This is an advantage of using a programmer-friendly
operating system, which MS Windows sadly is not.)

 I was trying to copy and paste these instructions into the
 [interactive Python shell].

 http://en.wikibooks.org/wiki/Python_Programming/Classes
  class Foo:
 ... def setx(self, x):
 ... self.x = x
 ... def bar(self):
 ... print self.x

 There is really no way to do that without pasting line by line is
 there and adding deleting spaces?  And if you use spaces and tabs,
 they are not the same.

Right on all counts.

The interactive Python shell is good for very quickly experimenting and
demonstrating how Python actually behaves, statement by statement. But
as you point out, it is not a good choice for anything more complex. It
is a good learning and debugging tool.

When you start to write larger units of code, like a class or a
function, you can trade immediacy for flexibility: write your code into
a text editor, save it to a file ‘foo.py’, then run that code at a
separate OS command prompt by invoking ‘python foo.py’ in the terminal.

That way, you can continue to adjust and tweak the code as you learn how
your changes affect the code. You do need to keep invoking the actions
separately – edit the file, save the file, run the file with Python –
but this is what's needed when you want to run a program more than once
anyway, so it's a good step to take.

Find a good, *general-purpose* programmer's editor. Preferably licensed
under free software terms, with a strong community supporting it, and
available on all major platforms for when you switch to a decent
programmer-friendly operating system.

-- 
 \“When you go in for a job interview, I think a good thing to |
  `\  ask is if they ever press charges.” —Jack Handey |
_o__)  |
Ben Finney

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


Re: id == vs is

2014-10-26 Thread Ben Finney
Ben Finney ben+pyt...@benfinney.id.au writes:

 Dan Stromberg drsali...@gmail.com writes:
  Are the following two expressions the same?
[…]

 It depends what you mean by “the same”.

My apologies, I mis-read the question. My answers were for a different
question (one you didn't ask). Please ignore that.

-- 
 \  “If you ever reach total enlightenment while you're drinking a |
  `\  beer, I bet it makes beer shoot out your nose.” —Jack Handey |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 Of course it won't be clear to *everyone* but it should be clear
 enough to people who are familiar with standard Python idioms. A
 concrete example should be more obvious than the fake example:

 title = ('Mr', 'Ms')[person.sex == 'F']

 which should be clear to anyone who understands indexing in Python and
 that True == 1 and False == 0.

I consider it an accident of history, and one which should not be
necessary to understand Python code.

In other words, I consider code which exploits the equality of True with
1, or False with 0, is code with a leaky abstraction and should be
fixed.

 Although that's probably better written as a dict lookup:

 title = {'M': 'Mr', 'F': 'Ms'}[person.sex]

 which is then more easily extended to support intersex and
 non-traditional[1] gender identities.

It's true that gender is not a binary, but even if it were, this would
be a bad idea.

A schema which blurs the distinction between boolean versus integer is a
code smell: it speaks to the high likelihood that the “flag” really
represents an entity which will soon have more than two states, and
should never have been represented as a boolean.

-- 
 \ “As scarce as truth is, the supply has always been in excess of |
  `\   the demand.” —Josh Billings |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Dan Stromberg drsali...@gmail.com writes:

 EG, if I have 3 mutually exclusive command line options, I'll do
 something like:

 if option_a + option_b + option_c != 1:
sys.stderr.write('{}: -a, -b and -c are mutually 
 exclusive\n'.format(sys.argv[0]))

That is an excellent illustration of why exploiting this accidental
property of True and False leads to obfuscated code. The above test
gives me no clue that we're operating on boolean values, nor that we're
testing for exclusive options.

The error message bears no obvious relation to the test, and if I was
tracking down that error message I'd have no hint from the code why the
test is written that way. An explanatory comment would be needed, but
that's a strong sign IMO that instead the test should be re-written to
be much more obvious.

-- 
 \   “Never express yourself more clearly than you are able to |
  `\   think.” —Niels Bohr |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 I suspect that Guido and the core developers disagree with you, since
 they had the opportunity to fix that in Python 3 and didn't.

That doesn't follow; there are numerous warts in Python 2 that were not
fixed in Python 3. As I understand it, the preservation of bool–int
equality has more to do with preserving backward compatibility.

I agree with the decision, because this isn't an issue which often leads
to *incorrect* code. But I maintain that it's an unfortunate and
needlessly confusing wart of the language.

 One example of where treating True and False as 1 and 0 is useful is
 that it makes counting operations very simple, e.g. counting the
 number of blank lines:

 sum(not line.strip() for line in lines)
 sum(1 if not line.strip() else 0 for line in lines)
 sum({'': 0}.get(line.strip(), 1) for line in lines)

These all look ludicrous and explain nothing about intent, to my
reading. The ‘bool’ type exists precisely because there is a concept to
be represented which is distinct from integers.

Using a sum on non-numeric values just cracks the abstraction open
needlessly. Once I figure out what is going on, I'm left wondering why
the coder chose something so obfuscatory to their intent.

This is short and clear and needs no leaking of the underlying bool
implementation::

len(True for line in lines if line.strip())

 which I consider far less obvious than the straightforward summation
 of True values.

Why sum them at all? You aren't interested in them as numbers, you're
just asking how many objects meet a criterion. That calls not for ‘sum’,
but ‘len’. There's no need to rely on an underlying ‘int’ operation just
to count objects.

The fact that summing them gives the same answer as simply asking how
many there are, demonstrates that nothing is gained by peeking into the
implementation. The example I give above works exactly as well with no
‘int’ underlying the ‘bool’ type at all.

-- 
 \  “The way to build large Python applications is to componentize |
  `\ and loosely-couple the hell out of everything.” —Aahz |
_o__)  |
Ben Finney

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


Re: (test) ? a:b

2014-10-25 Thread Ben Finney
Ben Finney ben+pyt...@benfinney.id.au writes:

 This is short and clear and needs no leaking of the underlying bool
 implementation::

 len(True for line in lines if line.strip())

Correction::

len([True for line in lines if line.strip()])

-- 
 \ “Our task must be to free ourselves from our prison by widening |
  `\our circle of compassion to embrace all humanity and the whole |
_o__)   of nature in its beauty.” —Albert Einstein |
Ben Finney

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


Re: I am out of trial and error again Lists

2014-10-24 Thread Ben Finney
Rustom Mody rustompm...@gmail.com writes:

 On Saturday, October 25, 2014 9:17:12 AM UTC+5:30, Rustom Mody wrote:
  4. The least useful statement to try at the interpreter is print.

 Yeah this is python2 thinking; in python 3, print is technically an
 expression.

This is wrong thinking. In Python 3, print is a function.

-- 
 \   “[W]hoever is able to make you absurd is able to make you |
  `\unjust.” —Voltaire |
_o__)  |
Ben Finney

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


The “trials” in “trial and error” should be as simple as possible (was: I am out of trial and error again Lists)

2014-10-22 Thread Ben Finney
Seymore4Head Seymore4Head@Hotmail.invalid writes:

 Those string errors were desperate attempts to fix the append error
 I didn't understand.

It's normal when learning to get one's code into a mess.

But, when trying to trouble-shoot, please adopt the habit of
*simplifying* the examples, to better understand them.

At the least, when presenting code here for asking questions, ensure
you've make a simple-as-possible example showing the problem.

In other words: rip out any complicated parts to see if they're
relevant; if the same problem happens, that part wasn't relevant to the
example, and you should omit it when presenting it here.

You'll find that this will get you more sensible answers, As a bonus, it
will often lead to you understanding the problem enough to solve it!

-- 
 \  “At my lemonade stand I used to give the first glass away free |
  `\  and charge five dollars for the second glass. The refill |
_o__)contained the antidote.” —Emo Philips |
Ben Finney

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


Re: Struggling with python-daemon and subprocess module to work together

2014-10-21 Thread Ben Finney
Praveen Kumar kumarpraveen.nit...@gmail.com writes:

 Previously this basic server is executed using *openvt* but I thought
 it would be nice to have a daemon process for it and used
 python-daemon.

An important difference is that a daemon process has no controlling
terminal, by definition.

 Issue I am facing is after some time server will stop sending data to
 client which suppose to happen in #120 and get error message Cannot
 run interactive console without a controlling TTY .

So, if the code you're running inside that daemon process needs access
to a terminal, you have at least two options:

* If the code really needs to talk on an interactive terminal, fake it
  with a pseudoterminal, and keep that pseudoterminal (its file handle)
  open.

* If, as is probably the case, the code doesn't actually need to talk on
  an interactive terminal, cut that part of the code out entirely and
  the rest will run fine inside the daemon.

-- 
 \ “I may disagree with what you say, but I will defend to the |
  `\death your right to mis-attribute this quote to Voltaire.” |
_o__)   —Avram Grumer, rec.arts.sf.written, 2000-05-30 |
Ben Finney

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


Re: Quick Question About Setting Up Pytz

2014-10-18 Thread Ben Finney
ryguy7272 ryanshu...@gmail.com writes:

 So, when I run it, the setup.py text file opens. Nothing runs; nothing
 installs.

You have somehow (either manually, or by answering a question to some
program) associated the ‘.py’ suffix with “Open this file in my text
editor”.

That's fine, but it means that if you don't want to edit the file but
instead want to execute it, you need to *explicitly* start Python:

python /whatever/path/to/setup.py install

 This makes no sense whatsoever.

This is an issue with your operating system, so I would hope you can
learn more about that to distinguish what is causing your frustration
:-)

-- 
 \  “I got an answering machine for my phone. Now when someone |
  `\  calls me up and I'm not home, they get a recording of a busy |
_o__)  signal.” —Steven Wright |
Ben Finney

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


Re: Quick Question About Setting Up Pytz

2014-10-18 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 Try learning Python itself, rather than playing around with extension
 packages like pytz.

To be fair, “You need to install ‘pytz’ to work correctly with date and
time values” is correct advice. If the OP doesn't install it early, then
works with timestamps, problems are inevitable — at which point “oh, you
needed to do that first” will be inevitable. It's lose–lose.

It's a sad fact that MS Windows has completely useless timezone support,
and this “install a third-party package” hurdle is a cost that is paid
by all people trying to set up Python on MS Windows.

-- 
 \  “Nothing is more sacred than the facts.” —Sam Harris, _The End |
  `\   of Faith_, 2004 |
_o__)  |
Ben Finney

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


Python 3 is the active language, recommended for newcomers (was: Import Doesn't Import)

2014-10-15 Thread Ben Finney
ryguy7272 ryanshu...@gmail.com writes:

 So, I'm reading this link.
 https://docs.python.org/2/howto/urllib2.html

Note that this is the documentation for Python 2, which is obsolescent.
It has had a long life, so references to Python on the web are still
dominantly about that legacy version. Your confusion is quite normal.

Instead, use Python 3 only (which it seems you are doing), and read the
Python 3 documentation. You'll find that the ‘urllib’ modules
URL:https://docs.python.org/3/library/urllib.html are what you want.

 I don't get it; I just don't get it.

It's unfortunate that a lot of new Python users will be confused by this
long transition. But the situation is a lot better now; more and more
Python articles on the web are referring to Python 3 which is the
actively-developed version, recommended for new users.

-- 
 \ “You don't need a book of any description to help you have some |
  `\kind of moral awareness.” —Dr. Francesca Stavrakoloulou, bible |
_o__)  scholar, 2011-05-08 |
Ben Finney

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


Caching: Access a local file, but ensure it is up-to-date from a remote URL

2014-10-13 Thread Ben Finney
Howdy all,

I'm hoping that the problem I currently have is one already solved,
either in the Python standard library, or with some well-tested obvious
code.

A program I'm working on needs to access a set of files locally; they're
just normal files.

But those files are local cached copies of documents available at remote
URLs — each file has a canonical URL for that file's content.

I'd like an API for ‘get_file_from_cache’ that looks something like::

file_urls = {
foo.txt: http://example.org/spam/;,
bar.data: https://example.net/beans/flonk.xml;,
}

for (filename, url) in file_urls.items():
infile = get_file_from_cache(filename, canonical=url)
do_stuff_with(infile.read())

* If the local file's modification timestamp is not significantly
  earlier than the Last-Modified timestamp for the document at the
  corresponding URL, ‘get_file_from_cache’ just returns the file object
  without changing the file.

* The local file might be out of date (its modification timestamp may be
  significantly older than the Last-Modified timestamp from the
  corresponding URL). In that case, ‘get_file_from_cache’ should first
  read the document's contents into the file, then return the file
  object.

* The local file may not yet exist. In that case, ‘get_file_from_cache’
  should first read the document content from the corresponding URL,
  create the local file, and then return the file object.

* The remote URL may not be available for some reason. In that case,
  ‘get_file_from_cache’ should simply return the file object, or if that
  can't be done, raise an error.

So this is something similar to an HTTP object cache. Except where those
are usually URL-focussed with the local files a hidden implementation
detail, I want an API that focusses on the local files, with the remote
requests a hidden implementation detail.

Does anything like this exist in the Python library, or as simple code
using it? With or without the specifics of HTTP and URLs, is there some
generic caching recipe already implemented with the standard library?

This local file cache (ignoring the spcifics of URLs and network access)
seems like exactly the kind of thing that is easy to get wrong in
countless ways, and so should have a single obvious implementation
available.

Am I in luck? What do you advise?

-- 
 \   “If consumers even know there's a DRM, what it is, and how it |
  `\ works, we've already failed.” —Peter Lee, Disney corporation, |
_o__) 2005 |
Ben Finney

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


Re: help with regex

2014-10-08 Thread Ben Finney
Peter Otten __pete...@web.de writes:

  pattern = re.compile((\d+)$)
  match = pattern.search( LINE: 235 : Primary Shelf Number (attempt 1): 1)
  match.group()
 '1'

An alternative way to accomplish the above using the ‘match’ method::

 import re
 pattern = re.compile(^.*:(? *)(\d+)$)
 match = pattern.match(LINE: 235 : Primary Shelf Number (attempt 1): 1)
 match.groups()
('1',)

 See https://docs.python.org/dev/library/re.html#search-vs-match

Right. Always refer to the API documentation for the API you're
attempting to use.

-- 
 \“Without cultural sanction, most or all of our religious |
  `\  beliefs and rituals would fall into the domain of mental |
_o__) disturbance.” —John F. Schumaker |
Ben Finney

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


Re: operator module functions

2014-10-08 Thread Ben Finney
random...@fastmail.us writes:

 On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote:
  The main reason I bother using the operator module is for the
  readability of not seeing the dunders, and the writability of not
  having to type them.

 I'm not sure what situation you would have to type them (as opposed to
 simply a + b) that the operator module would help with.

Any situation where you need to refer to a function. ‘+’ is not a
function, whereas ‘operator.add’ is.

import operator
import functools

add_three = functools.partial(operator.add, 3)

foo = list(range(10))
bar = map(add_three, foo)

The above ‘map’ invocation – which is useful because it allows any
arbitrary one-parameter function to be used – cannot be used with ‘+’,
which is not a function.

Likewise, ‘functools.partial’ requires a function, and ‘+’ is not a
function.

There are countless such uses for the functions in the ‘operator’
module.

-- 
 \  “It is the integrity of each individual human that is in final |
  `\examination. On personal integrity hangs humanity's fate.” |
_o__)   —Richard Buckminster Fuller, _Critical Path_, 1981 |
Ben Finney

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


Re: Toggle

2014-10-08 Thread Ben Finney
Seymore4Head Seymore4Head@Hotmail.invalid writes:

 I want to toggle between color=Red and color=Blue

It's good to cultivate ongoing familiarity with the standard library
URL:https://docs.python.org/3/library/itertools.html#itertools.cycle
so that you can make use of wheels already invented and maintained::

import itertools

colours = [Red, Blue]
colour_cycle = itertools.cycle(colours)

next(colour_cycle)# → Red
next(colour_cycle)# → Blue
next(colour_cycle)# → Red
next(colour_cycle)# → Blue
next(colour_cycle)# → Red

for colour in colour_cycle:
# … loops indefinitely
# with ‘colour’ bound to each value in turn …

-- 
 \  “My roommate got a pet elephant. Then it got lost. It's in the |
  `\  apartment somewhere.” —Steven Wright |
_o__)  |
Ben Finney

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


Re: program to generate data helpful in finding duplicate large files

2014-09-20 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 I heard one [programmer] mention that even though he sees the words
 are misspelled, he deliberately doesn't bother fixing them because its
 not important. I guess he just liked the look of his text having
 highlighted words scattered throughout the editor.

If it's who I'm thinking of (or, heck, any one of a hundred similar
cow-orkers), the text editor would not show English spelling errors
since they're not interested in the English text in their program code
:-)

-- 
 \“Spam will be a thing of the past in two years' time.” —Bill |
  `\ Gates, 2004-01-24 |
_o__)  |
Ben Finney

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


Re: [OT] Question about Git branches

2014-09-16 Thread Ben Finney
Frank Millman fr...@chagford.com writes:

 I know there some Git experts on this list, so I hope you don't mind
 me posting this question here.

I do. There may be experts on parquetry flooring in this forum, but a
topic is not on-topic merely because some people here may know about it.

Please engage with the Git community URL:http://git-scm.com/community
instead of starting non-Python discussions here.

-- 
 \ “We must become the change we want to see.” —Mohandas K. Gandhi |
  `\   |
_o__)  |
Ben Finney

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


Re: [OT] Question about Git branches

2014-09-16 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 I agree. If a post on parquet flooring were held for moderation, I
 would discard it. Threads that wander off into parquet flooring type
 topics are best let die.

I'm glad to know that, thank you.

  (2) Parquetry flooring has nothing to do with Python programming,
  while source control is very relevant. Asking questions about
  revision control is at least as on-topic as asking what editor one
  should use for Python programming,

 The proper parallel is revision control for Python versus editor for
 Python.

Right. I'd consider “how do I use Emacs?” to be inappropriate here, and
would want the question directed to a more appropriate forum. When it's
“how do I use Emacs to correctly indent Python code?” the question is
appropriate here. I'm of the opinion the original question was of the
first, inappropriate, kind.

 Since Frank is a known Python user, I presume 'for Python' was
 part of his question. Revision control for word processing would be a
 bit far afield for this list.

I didn't see a good reason to think the question had any particular
relevance to Python programming (no more than, say, “how do I use Emacs
correctly?”) and responded on that basis.

I acknowledge that's a judgement call, made by a participant with no
special power here. There is an infinite number of topics we could
discuss, and would likely be of interest to many people here.

Just because some individuals may be found to talk about a topic doesn't
make this forum appropriate for that discussion. That was the explicit
reason given for a question acknowledged to be off-topic, and *that's*
why I responded firmly: the reason given is invalid.

The usefulness of a particular forum is only maintained by maintaining
the common explicit topic of interest as the criterion, and redirecting
most topics away.

-- 
 \ “I believe our future depends powerfully on how well we |
  `\ understand this cosmos, in which we float like a mote of dust |
_o__) in the morning sky.” —Carl Sagan, _Cosmos_, 1980 |
Ben Finney

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


Posting style: interleaved responses (was: My backwards logic)

2014-09-05 Thread Ben Finney
Juan Christian juan0christ...@gmail.com writes:

 @Mark Lawrence: Sorry to ask, but what do you mean by don't top post
 here, thanks., I'm not familiar with mailing lists, so I may be doing
 something wrong and I don't know.

Please post your responses interleaved with the quoted material to
which you're responding. See the article on “interleaved style”
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style. And
trim any quoted material to which you're not responding, so your message
only contains relevant material.

-- 
 \“Human reason is snatching everything to itself, leaving |
  `\   nothing for faith.” —Bernard of Clairvaux, 1090–1153 CE |
_o__)  |
Ben Finney

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


Re: Keeping python code and database in sync

2014-08-29 Thread Ben Finney
Roy Smith r...@panix.com writes:

 Yeah, schema migration is an ugly problem. There's a number of tools
 to help here, most of which reduce the suckitude, but don't eliminate
 it completely. Some things you might want to look at:

 * SQLAlchemy Migrate
 * alembic

I can strongly recommend SQLAlchemy. It has several levels of working
with the RDBMS, and they all work well together; you can code primarily
to one API and occasionally use a different part, and it all works
together.

I've never used Alembic, but it is a migration tool built on SQLAlchemy.

 * South (django-specific)

It's worth noting the South is no longer developed as a separate
library:

Please note that South is now end of lifed in favour of the new
migrations framework in Django 1.7, which is based on South but with
significant design improvements. South will not work with Django
1.7; it supports only versions 1.4, 1.5 and 1.6.

URL:http://south.aeracode.org/

-- 
 \ “I think Western civilization is more enlightened precisely |
  `\ because we have learned how to ignore our religious leaders.” |
_o__)—Bill Maher, 2003 |
Ben Finney

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


Re: Why can not initialize the class?

2014-08-22 Thread Ben Finney
Terry Reedy tjre...@udel.edu writes:

 By posting code with an extra indent, you make it imposible to run by
 just cutting and pasting. You should already know that.

I commonly do that, as I do with most block quotes in plain text.

I think it's a reasonable expectation that programmers, reading a forum
about program code, will have at hand a programmer's editor capable of
stripping a level of indentation from a block of code.

-- 
 \ “Cross country skiing is great if you live in a small country.” |
  `\—Steven Wright |
_o__)  |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-21 Thread Ben Finney
Everything You Need To Know ey...@outlook.com writes:

 You are now simply arguing a negative point for no apparent reason
 other than you want to appear correct, I have already admitted my
 mistake yet you persist with negativity and vitriol, it is quiet
 childish.

Observers will judge the difference between vitriol, compared with calm
criticism of actions. If you see criticism as “negativity and vitriol”,
you'll need to reconsider whether you want to take part in an online
discussion forum.

-- 
 \   “Working out the social politics of who you can trust and why |
  `\  is, quite literally, what a very large part of our brain has |
_o__)   evolved to do.” —Douglas Adams |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-21 Thread Ben Finney
Everything You Need To Know ey...@outlook.com writes:

 On Thursday, 21 August 2014 14:33:19 UTC+9:30, Ian  wrote:
  Google does not own or control this forum. The comp.lang.python
  group is part of Usenet, which is not owned by anybody. The group is
  also bridged to the python-list mailing list hosted by the Python
  Software Foundation. The Google group is just a mirror of the Usenet
  group.

 O! that was a BIG misunderstanding of mine then, and I will seek to
 rectify this again.

Thanks again for learning, I hope to see better participation soon.

-- 
 \ “Here is a test to see if your mission on earth is finished. If |
  `\  you are alive, it isn't.” —Francis Bacon |
_o__)  |
Ben Finney

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


Re: Distinguishing attribute name from varible name to make codes clear and definite

2014-08-21 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 I feel that self.x and x will be confused in the following codes.

I don't see how. The examples you give have the two quite distinct in
every case.

 exam=MyDescriptor(hallo)

 when class MyDescriptor  initiate , the `hallo` was passed into x in
 __init__(self, x);

That's correct; the argument ‘hallo’ (a text string) is the second
argument in the ‘__init__’ call, and the name ‘x’ is bound to that
value while the function executes.

 Literally  self.x maybe understood to be self.hallo ,assign a
 attribute named 'hallo' to instance exam.

No, the attribute ‘self.x’ is not to be understood as ‘self.hallo’. The
value is not the name.

If the value of the argument were 7.03, the attribute would not be named
‘self.7.03’, it would still be named ‘self.x’.

 There is a attribute y  in instance exam , the `hallo` was passed into
 x in __init__(self, x).No any relation between x and y ,`hallo` and y.
 My view is correct or not ?

You are correct that, if you were to name the attribute differently from
the parameter, there would no longer be any clear relationship.

You are, IMO, incorrect that this would help. Rather, the loss of the
clear relationship would make it much more difficult to see why the
relationship exists, and why different names were chosen.

Instead, the programmer is expected to understand that a value is
distinct from any name which is bound to that value.

-- 
 \  “Our products just aren't engineered for security.” —Brian |
  `\ Valentine, senior vice-president of Microsoft Windows |
_o__)development, 2002 |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-21 Thread Ben Finney
Steven D'Aprano steve+comp.lang.pyt...@pearwood.info writes:

 Adam (Everything You Need To Know) has perhaps posted unwisely and
 clumsily, but obnoxiously?

 Obnoxious (noun): 
 very offensive; hateful; odious; reprehensible.

 What did Adam do that was *obnoxious*? Here are some of the
 accusations thrown at him:

 - he posted using a self-aggrandising name instead of his real
 name;

Using one's real name is helpful, but choosing not to is not obnoxious.

Using a name that is clearly not naming a person, and instead is a
marketing name for one's site elsewhere, is odious and reprehensible
because it approaches this community as no more than a market for
one-way messages.

 - his post is spam (commercial, unsolicited advertising);

Spam does not entail commercial; religious screeds that have no
commercial nature can qualify, for example.

His posts, repeatedly giving a link to a video and contributing to no
on-topic discussion, are unsolicited bulk messages. That's spam.

 - he posted as a member of a group instead of an individual.

No, he posted *as the group*, and his explanations made it clear that he
did not intend to engage as an individual. That's obnoxious in a
community discussion forum.

 I reject any suggestion that Adam's post is obnoxious or that it is
 spam. It is clearly on-topic.

I'm one of many who disagree.

 Frankly, I am ashamed at the closed-minded hostility demonstrated here
 in this thread.

Engaging a person with specific details on how their behaviour is
objectionable, and specific requests on how to improve, demonstrates
hope and optimism that the person can contribute positively. I don't
accept the claim of closed-mindedness.

Hostility? Yes, I'm hostile to behaviour which has already descended to
disrespecting the purpose of this community forum. That doesn't extend
to hostility to a person, though I understand it can be difficult for
the person to see the difference at the time their behaviour is
criticised.

 Ben, I believe that your behaviour goes against the spirit of the
 Python Community Code of Conduct, if not the actual letter of CoC. Can
 you honestly say that you have been Open, Considerate, and Respectful
 in telling Adam that his post was obnoxious and that his post is
 not appropriate just because it is hosted on YouTube?

Yes, I have respectfully explained at length to Adam why I'm criticising
his behaviour.

I have not, AFAIK, given any cause to think I lack respect for Adam as a
person — indeed, one of my main criticisms is that Adam should engage
*as a person*.

I also respect Adam enough to recognise that he's likely to be able to
learn what was objectionable about his behaviour and improve it.

 This is supposed to be a welcoming place. Does anyone think we as a
 community have been welcoming to Adam?

When the initial engagement is a continuous repeating of the same
disrespectful behaviour, and it continues oblivious to requests to
correct the mistakes, I think the welcome has worn out. We are not
obligated to endure everything, and respect for all the *other* persons
here is also needed and entailed in the Code of Conduct.

-- 
 \“[It's] best to confuse only one issue at a time.” —Brian W. |
  `\  Kernighan, Dennis M. Ritchie, _The C programming language_, 1988 |
_o__)  |
Ben Finney

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


Re: Very basic question. How do I start again?

2014-08-21 Thread Ben Finney
Seymore4Head Seymore4Head@Hotmail.invalid writes:

 The program works as expected until the computer gets a correct guess.
 I don't know what I should be doing to restart the program when
 pick=guess.

There isn't a “restart the program” code we can give. But I think you
need only something rather simpler:

 while count  100:
 guess = random.randrange(low,high)
 print (pick, guess)
 if guess == pick:
 print (correct)

 #What I need is something here that says start over

You can end the current loop with the ‘break’ statement. See the docs
URL:https://docs.python.org/3/reference/simple_stmts.html#the-break-statement
to see exactly what its semantics are, and try using that in your code.

Feel free to ask further questions when you've tried that, if it's still
not clear.

-- 
 \ “Religious faith is the one species of human ignorance that |
  `\ will not admit of even the *possibility* of correction.” —Sam |
_o__) Harris, _The End of Faith_, 2004 |
Ben Finney

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


Re: How can I get the timezone time of a location?

2014-08-20 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 would you mind sending the video to my mailbox?

Please, remember to post interleaved style. Don't top-post.

 There is no video in the web when i open it in my firefox.

The page describing the video also has a link to the hosted site of the
video, see the “Video origin” field to the right side of that page.

-- 
 \ “Truth would quickly cease to become stranger than fiction, |
  `\ once we got as used to it.” —Henry L. Mencken |
_o__)  |
Ben Finney

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


Re: what is the difference between name and _name?

2014-08-20 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 When i learn property in python , i was confused by somename and
 _somename,what is the difference between them?

Some attributes are exposed in the API for an object (a class, a module,
etc.). Those are effectively a promise from the author that the
attribute is supported for use. A name like ‘foo’ is part of the API.

Other attributes are details of the implementation only, and are
designed to be used only by the object itself or its close
collaborators.

Those attributes which are not published, are not part of the API, are
details of the implementation. Depending on them to remain useful is an
error, since they can change at any time; they are not part of the
promise made by the designer of the object.

The convention on Python is to name implementation-detail attributes
with a single leading underscore. A name like ‘_foo’ is not part of the
API and using it from the outside is a mistake.

You should already have completed the Python tutorial
URL:https://docs.python.org/3/tutorial/ by now. This conventionis
covered there; you should work through the tutorial from beginning to
end in order to get a good grasp of Python basics.

-- 
 \   “Are you pondering what I'm pondering?” “Umm, I think so, |
  `\Brain, but what if the chicken won't wear the nylons?” —_Pinky |
_o__)   and The Brain_ |
Ben Finney

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


Re: How can I get the timezone time of a location?

2014-08-20 Thread Ben Finney
Ben Finney ben+pyt...@benfinney.id.au writes:

 luofeiyu elearn2...@gmail.com writes:

  There is no video in the web when i open it in my firefox.
 The page describing the video also has a link to the hosted site of
 the video, see the “Video origin” field to the right side of that
 page.

The cited video contains good information, but the pace is quite fast
and Lennart's speech might be a little difficult to follow for
non-native speakers.

Here are two weblog articles he wrote on time zones and their problems
URL:http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/
URL:http://regebro.wordpress.com/2008/05/10/python-and-time-zones-part-2-the-beast-returns/.

In brief: Time zones are a still-evolving system to address a thorny
real-world sociopolitical problem; and using Microsoft Windows makes it
significantly worse.

Advice: Use UTC as the canonical timezone (just as you should use
Unicode as the canonical text type) inside your application, and push
other time zones as far to the edge of your application as possible.
Avoid MS Windows entirely.

-- 
 \ “There is more to life than increasing its speed.” —Mohandas K. |
  `\Gandhi |
_o__)  |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-20 Thread Ben Finney
Everything You Need To Know ey...@outlook.com writes:

 I offer something practical and positive to the community, even if the
 wrong community to post.

You choose to offer it with a self-aggrandising name instead of your
real name, which is itself an obnoxious habit.

The links themselves are, as you acknowledge, not appropriate to this
discussion forum, they are a blatant attempt to drive traffic to your
site instead of having a useful discussion here.

 I am by definition working productively with this forum, engaging with
 an audience, which has so far mutually benefited us both, as I have
 already taken requests for tutorials.

No, you are not working with this forum. Your posts are not aiding
discussion here, they are advertisements for your channel elsewhere.
Please don't.

-- 
 \ “[F]reedom of speech does not entail freedom to have your ideas |
  `\accepted by governments and incorporated into law and policy.” |
_o__)   —Russell Blackford, 2010-03-06 |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-20 Thread Ben Finney
Everything You Need To Know ey...@outlook.com writes:

 It is not just one person here! To give my name when we are trying to
 be a small group would not work.

That's not how a community operates. Please post as an individual, with
a person's name, to establish your reputation and continuity.

Others can post as themselves. We don't need organisations posting as if
they were a person with one mind.

 What would you do in my situation...

Deal with a community of individuals *as* an individual.

Deal with a discussion forum by starting *discussions* in that forum.

Consider, every time, the relevance of your message to a *discussion
forum* for the community primarily.

 Do I now have to work more hours, create my own web site as well and
 own forums for given topics and discussions.

Your work expended so far imposes no obligation on us to endure your
spam. Please engage with this community rather than seeing us as a
market for your product — or don't engage at all.

-- 
 \ “To succeed in the world it is not enough to be stupid, you |
  `\must also be well-mannered.” —Voltaire |
_o__)  |
Ben Finney

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


Re: what do you get with 1 divide by 998001, interesting results

2014-08-20 Thread Ben Finney
Everything You Need To Know ey...@outlook.com writes:

 I guess I have to agree and was mistaken, though vitriol I found
 unnecessary and unproductive!

You've behaved obnoxiously, as has been pointed out. We regard this
community highly, and when obnoxious behaviour occurs, emotive responses
are to be expected.

Thank you for acknowledge the mistake, and in advance for working to
improve.

 Just thought it was in best interest if we posted as one rather than
 individuals, if we had each other agreeing with one another it by
 accident or other, it would add extra sway to an individual point of
 view as we are sharing it.

Remember that this is a forum for discussion, for benefit of the Python
community. Not specially for the benefit of any organisation. If there's
a position relevant to be expressed here, and your organisation all
agrees on that position, there's no need for dozens of people to repeat
it — one person can say it.

But it's harmful for community participation if that person's individual
identity is shrouded behind a corporate name. It's important that any
individual's words are accountable over time to an individual's name.

If your messages are so unlike community discussion that you feel the
need to portray them as coming from a corporate entity instead of an
individual open to further discussion, please consider that such
messages are likely of little value to a community discussion forum.

-- 
 \“None can love freedom heartily, but good men; the rest love |
  `\   not freedom, but license.” —John Milton |
_o__)  |
Ben Finney

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


Re: 'is not' or '!='

2014-08-19 Thread Ben Finney
Tim Chase python.l...@tim.thechases.com writes:

 Am I the only one who feels the urge to write

   if i am some_other_object: ...
   if we are some_other_object: ...
   if u are some_other_object: ... # though txtspk bothers me

How often do you need to refer to an object with personal pronouns? I
think for me the answer is “never”. Why not name the specific role the
object is playing, rather than the indirectness of personal pronouns?

So, in short: you may not be the only one, but I find it difficult to
imagine why anyone would be motivated to do that.

-- 
 \  “When I was born I was so surprised I couldn't talk for a year |
  `\and a half.” —Gracie Allen |
_o__)  |
Ben Finney

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


Re: More Pythonic implementation

2014-08-19 Thread Ben Finney
Shubham Tomar tomarshubha...@gmail.com writes:

 Lets say I have a function poker(hands) that takes a list of hands and
 returns the highest ranking hand, and another function hand_rank(hand)
 that takes hand and return its rank.

To make it clearer, I think you mean something like this::

def hand_rank(hand):
 Determine the rank of the poker hand. 
rank = int(some_complex_computation(hand))
return rank

In other words, I'm assuming ‘hand_rank’ returns an integer.

 Which of the following is better and more Pythonic ?

Only one of them does anything useful :-)

 def poker(hands):
 return max(hands, key=hand_rank)

This will return the item from the collection ‘hand’ with the maximum
value as determined by ‘hand_rank’. So this appears to do what you want.

 def poker(hands):
 return max(hand_rank(hands))

This raises “TypeError: 'int' object is not iterable” because you're
operating on one return value from ‘hand_rank’, which is not a
collection.

-- 
 \   “Corporation, n. An ingenious device for obtaining individual |
  `\   profit without individual responsibility.” —Ambrose Bierce, |
_o__)   _The Devil's Dictionary_, 1906 |
Ben Finney

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


Re: How to look up historical time zones by date and location

2014-08-19 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

  tz1
 DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD
  repr(tz1)
 DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD

Yes. Remember that ‘repr’ is for the benefit of the programmer, and
there is no promise of what it contains.

  x=repr(tz1)
  x
 DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD
  import re
  re.search(LMT.+\s,x).group()
 'LMT+8:06:00 '

This is wildly fragile. The ‘repr’ output depends on unpublished
attributes: implementation details not part of the API which therefore
can change without notice. You're then parsing a free-form string
assuming that it will contain a structure for the data you want.

All of those assumptions are subject to change without notification, and
the result would be a bug in your code, not the library.

At the least: Reduce the number of fragile links in that chain. If you
want access to unpublished attributes, then simply access them directly.

 import pytz
 tz1 = pytz.timezone(Asia/Shanghai)
 (zone_name, tzname, utcoffset, is_dst) = (tz1.zone, tz1._tzname, 
tz1._utcoffset, tz1._dst)
 zone_name, tzname, utcoffset, is_dst
('Asia/Shanghai', 'CST', datetime.timedelta(0, 28800), 
datetime.timedelta(0))

Then use those values however you like.

The values will still be subject to change without notice. But at least
you'll avoid parsing structured data from a string, and you'll avoid
whatever quirks go into the ‘repr’ output.

-- 
 \  “The difference between a moral man and a man of honor is that |
  `\   the latter regrets a discreditable act, even when it has worked |
_o__)   and he has not been caught.” —Henry L. Mencken |
Ben Finney

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


Re: why i can't get the sourcecode with inspect module?

2014-08-19 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

  import inspect
  def changer(x,y):
 ... return(x+y)
 ...

At this point, you have defined a function. It is accessible via the
‘changer’ name, and the code is available.

But the source code is not available; Python reads standard input but
doesn't preserve it.

  dir()
 ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__
  'changer', 'inspect']

I don't know what this is meant to demonstrate.

Maybe ‘dir(changer.__code__)’ would be instructive.

  inspect.getsource(changer)
 Traceback (most recent call last):
   File stdin, line 1, in module
   File D:\Python34\lib\inspect.py, line 830, in getsource
 lines, lnum = getsourcelines(object)
   File D:\Python34\lib\inspect.py, line 819, in getsourcelines
 lines, lnum = findsource(object)
   File D:\Python34\lib\inspect.py, line 667, in findsource
 raise OSError('could not get source code')
 OSError: could not get source code
 

Exactly. The ‘inspect.getsource’ function gets the source code, if it's
available. The source code doesn't exist any more, so it's not
available; an OSError is raised.

-- 
 \ “You say I took the name in vain / I don't even know the name / |
  `\But if I did, well, really, what's it to you?” —Leonard Cohen, |
_o__) _Hallelujah_ |
Ben Finney

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


Re: How to look up historical time zones by date and location

2014-08-18 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 http://www.thefreedictionary.com/time+zone

 time zone Any of the 24 divisions of the Earth's surface used to
 determine the local time for any given locality.

Thanks, it's good to know there are dictionaries out there with
incorrect definitions. That one is terrible and unhelpful.

 Urumqi  's localtime is beijin time ,it is decided  by law .
 Urumqi  's timezone is east 6 ,it is decided by geography.

Please use the standard definition of “time zone”, otherwise your
terminology is only got to confuse the conversation.

 There is only one localtime in all over the chian,beijin time,but
 there are 5  timezone time in china .

This just doesn't match the truth of standard time zones. You are free
to think differently, but you will need to find a non-standard time zone
database that agrees with you.

 you are totally wrong ,not me .

You're free to keep on with that belief, but I'll only be providing
information based on standard time zone definitions. If you choose to
deviate from that, you're on your own.

-- 
 \   “The fundamental principle of science, the definition almost, |
  `\ is this: the sole test of the validity of any idea is |
_o__) experiment.” —Richard P. Feynman |
Ben Finney

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


Re: Why Python 4.0 won't be like Python 3.0

2014-08-18 Thread Ben Finney
Grant Edwards invalid@invalid.invalid writes:

 I agree with the comments that the appellation for simply the next
 version after 3.9 should be 3.10 and not 4.0. Everybody I know
 considers SW versions numbers to be dot-separated tuples, not floating
 point numbers.

This consensus is sometimes termed “semantic versioning”, that is,
giving semantic meaning to the structural elements of a version string
URL:http://semver.org/.

I'm glad someone has taken the time to codify that sensible and useful
de-facto standard for version strings.

 I don't think one (or several) blog posts is going to change the
 perceptions and expectations that have been coditioned into us by
 decades of experience with x.0 versions of countless software
 packages. If it's just another in a a series of incremental bug fix
 and minor enhancements without breaking backwards incompatibility
 releases, you simply do not call it vers x.0.

Agreed. The convention is well established and rogues deviate from it at
the peril of unnecessary confusion.

-- 
 \ “Guaranteed to work throughout its useful life.” —packaging for |
  `\  clockwork toy, Hong Kong |
_o__)  |
Ben Finney

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


How to look up historical time zones by date and location (was: How can I get the timezone time of a location?)

2014-08-17 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 I knew there is a difference between localtime and timezone time.
 Localtime: The official time in a local region (adjusted for location
 around the Earth); established by law or custom.
 Timezone: Any of the 24 regions of the globe (loosely divided by
 longitude) throughout which the same standard time is used.

That is not what “time zone” means and you're going to continue being
confused if you apply that definition. See the consensus definition at
URL:https://en.wikipedia.org/wiki/Time_zone.

 For Urumqi,localtime is the time of east 8 timezone, but timezone time
 is the time of east 6 timezone.

How have you determined these? Who declares “east 6” for Urumqi
currently? Why should you expect a timezone database to contain that
timezone for current time in that location.

By the international time zone database, the time zone for Urumqi is
currently “China Standard Time”, UTC+8 hours. That time zone is true for
all dates since 1949 to the present day.

Are you perhaps asking not about *current* time zone, but time zones at
a different point in time? Historical time zones in China have differed
URL:https://en.wikipedia.org/wiki/Historical_time_zones_of_China.
Those historical time zones are in the standard time zone database, but
only apply to specific date ranges.

-- 
 \“… no testimony can be admitted which is contrary to reason; |
  `\   reason is founded on the evidence of our senses.” —Percy Bysshe |
_o__)Shelley, _The Necessity of Atheism_, 1811 |
Ben Finney

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


Re: For using python ability, what should I do???

2014-08-17 Thread Ben Finney
Jm Cho britz...@gmail.com writes:

 Thesedays, I'm studying Python 3.x version. I like Python.

Great! Welcome to the forum.

(You should avoid coming here via Google Groups, since it is a very poor
application for participating in discussion forums
URL:https://wiki.python.org/moin/GoogleGroupsPython.

There is virtually no hope it will ever improve, so you should use e.g.
URL:http://news.gmane.org/gmane.comp.python.general or any other
Usenet client.)

 i read a book, python for kids a playful introduction to programming,
 it is very easy but very effective to me.

Glad to know that book is helpful.

 so, I hope my python ability is higher...
 What should I do??

The Python Wiki has an index of beginner resources, please see
URL:http://wiki.python.org/moin/BeginnersGuide.

 ps. In fect, I did try to Django, but it was very difficult..

Writing a web application is a pretty complex task, and Django provides
a lot of power. You should set your expectations lower until you gain a
lot more skill with the programming language.

 Do you think I will make any program??

Yes! See the tutorials listed at the above Beginner's Guide. You should
also find *existing* projects using Python – preferably ones you use
yourself already – and offer to contribute there as a means of learning.

-- 
 \ “Guaranteed to work throughout its useful life.” —packaging for |
  `\  clockwork toy, Hong Kong |
_o__)  |
Ben Finney

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


Re: timezone argument %z and %Z

2014-08-16 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 In my system : win7+ python3.4 .

AFAIK, Microsoft's Windows OS does not provide correct standard
timezones for programmers. They provide only proprietary data, which do
not match the international standard time zones.

You will need to install timezone support specifically for Python, with
the ‘pytz’ library I directed you to earlier.

 problem 1:
 There are 24 time zone in the world, does any time zone has the time
 zone name  such as EST,CST ?
 Are there 24  time zone  abbreviations in python  ?what are other 22
 except for  EST ,CST ?

There are *many* time zones in the world, much more than 24. Please read
up on time zones, you should already have plenty of pointers instead of
asking here all the time.

-- 
 \  “Software patents provide one more means of controlling access |
  `\  to information. They are the tool of choice for the internet |
_o__) highwayman.” —Anthony Taylor |
Ben Finney

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


Re: how to change the time string into number?

2014-08-14 Thread Ben Finney
Please don't top-post your response. Instead, interleave your response
and remove irrelevant quoted material. Use the Interleaved style
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style.

luofeiyu elearn2...@gmail.com writes:

 in the manual  https://docs.python.org/3.4/library/time.html

 %zTime zone offset […]
 %ZTime zone name (no characters if no time zone exists).

 t1='Sat, 09 Aug 2014  07:36:46  '
 time.strptime(t1,%a, %d %b %Y %H:%M:%S )
 time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7,
 tm_min=36, tm_sec
 =46, tm_wday=5, tm_yday=221, tm_isdst=-1)

Your code examples will be easier to read if you follow PEP 8 (in this
example, spaces around the operators as described in the style guide).

  t2='Sat, 09 Aug 2014  07:36:46  -0700'
  time.strptime(t2,%a, %d %b %Y %H:%M:%S %z)
 time.struct_time(tm_year=2014, tm_mon=8, tm_mday=9, tm_hour=7,
 tm_min=36, tm_sec
 =46, tm_wday=5, tm_yday=221, tm_isdst=-1)

 t1 and t2 is different time ,the timezone in t2 is -0700 ,why we get
 the same result?

The timezone in ‘t2’ will only be understood subject to the caveat:

Support for the %Z directive is based on the values contained in
tzname and whether daylight is true. Because of this, it is
platform-specific except for recognizing UTC and GMT which are
always known (and are considered to be non-daylight savings
timezones).

URL:https://docs.python.org/3/library/time.html#time.strptime

So you'll need to see what your Python implementation supports (see
‘time.tzname’).

The support for time zones is always a pain, because they *change*
rapidly, arbitrarily, and with very little warning. Because of this, the
Python standard library does not attempt to contain a timezone database,
since it would almost immediately be out of date.

Install the ‘pytz’ package to get the latest released timezone database
supported in Python URL:https://pypi.python.org/pypi/pytz.

-- 
 \  “It is better to have loft and lost than to never have loft at |
  `\   all.” —Groucho Marx |
_o__)  |
Ben Finney

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


Re: how to change the time string into number?

2014-08-14 Thread Ben Finney
Dennis Lee Bieber wlfr...@ix.netcom.com writes:

   Android /is/ the flavor G

   Though Google has probably done some things to it that make it
 not-Linux.

Android is definitely Linux, since that is the kernel Android runs.
Remember that Linux is not an operating system; it is one part, the
kernel.

This is where it's very useful to have a distinct name to refer to the
operating system. GNU is an operating system, Android is a completely
different operating system. Both happen to have Linux as their kernel.

-- 
 \ “I went to San Francisco. I found someone's heart.” —Steven |
  `\Wright |
_o__)  |
Ben Finney

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


Re: Captcha identify

2014-08-14 Thread Ben Finney
Denis McMahon denismfmcma...@gmail.com writes:

 On Tue, 12 Aug 2014 18:36:21 -0700, Wesley wrote:

  […]

 We tried polite, it didn't work, now I'm trying robustness and
 profanity.

The thread has been inactive for days, so it seems politeness *did* in
fact work.

Escalating to violent indimidating language (regardless of profanity) is
unhelpful, please don't ever resort to that here.

-- 
 \ “I am the product of millions of generations of individuals who |
  `\  each fought against a hostile universe and won, and I aim to |
_o__)  maintain the tradition.” —Paul Z. Myers, 2009-09-12 |
Ben Finney

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


Re: problem on top-post

2014-08-14 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 the best way is to excerpt only the relevent portions of the parent
 message ,not top-post nor bottom-post , right?

Correct; you should also interleave your responses in the context of the
relevant quoted material. See at the link I provided for this style
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style.

Thanks for endeavouring to learn good communications etiquette.

-- 
 \“I was in Las Vegas, at the roulette table, having a furious |
  `\ argument over what I considered to be an odd number.” —Steven |
_o__)   Wright |
Ben Finney

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


Re: timedelta problem

2014-08-14 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 import datetime
 t1='Sat, 09 Aug 2014 07:36:46 -0700'
 t2='Sat, 09 Aug 2014 07:36:46 +0700'
  datetime.datetime.strptime(t1,%a, %d %b %Y %H:%M:%S %z)
 datetime.datetime(2014, 8, 9, 7, 36, 46,
 tzinfo=datetime.timezone(datetime.timed
 elta(-1, 61200)))
  datetime.datetime.strptime(t2,%a, %d %b %Y %H:%M:%S %z)
 datetime.datetime(2014, 8, 9, 7, 36, 46,
 tzinfo=datetime.timezone(datetime.timed
 elta(0, 25200)))

(Your examples will be easier to read – and you will help those who are
helping you – if you conform to PEP 8 in the code, and don't break up
the output when you copy it here.)

 problem :

 t1 is GMT time   2014  00:36:46
 t2 is GMT time   2014  14:36:46

Not true; t1 and t2 are not in the “GMT” zone, they are in UTC-0700 and
UTC+0700 respectively. Their value includes that.

The instants they *represent* may be equal to the times-plus-timezone
you've listed here, but their value is different. The value includes the
timezone information, so they're different from what you show.

 datetime.datetime.strptime  do not give me the right answer.

What do you think the right answer would be in each case? Why?

-- 
 \ “The aim of science is not to open the door to infinite wisdom, |
  `\but to set some limit on infinite error.” —Bertolt Brecht, |
_o__)_Leben des Galilei_, 1938 |
Ben Finney

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


Re: problem on top-post

2014-08-14 Thread Ben Finney
John Gordon gor...@panix.com writes:

 In mailman.13017.1408067250.18130.python-l...@python.org luofeiyu 
 elearn2...@gmail.com writes:

  the best way is to excerpt only the relevent portions of the parent 
  message ,not top-post nor bottom-post , right?

 The followup text appears underneath the quoted parent message, thus
 bottom-post.

“Bottom-post” usually refers to the inferior practice of quoting a
message (entirely or large amounts) and then indiscriminately responding
to all of it below all of the quoted text.

The preferred style is “interleaved”, where responses are interleaved
among the relevant parts of quoted material. Each response appears below
only the relevant part.

So no, the responses should not appear below the quoted *message*, but
below the relevant *part* of the quoted material, followed potentially
by more relevant quoted material and responses to those.

(We agree that there should be no quoted material after all of your own
responses; if you're not following quoted material with a relevant
response, that part of the quoted material should be removed in your
message.)

With only a small, single point to respond to, the recommended
“interleaved” style is identical to “bottom post” — in this message, for
example.

But “bottom post” is not preferred when there are multiple responses to
multiple points, by one person or several. The “interleaved” style is
the recommended etiquette.

-- 
 \   “The lift is being fixed for the day. During that time we |
  `\regret that you will be unbearable.” —hotel, Bucharest |
_o__)  |
Ben Finney

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


Re: how to change the time string into number?

2014-08-13 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

 s=Aug

 how can i change it into 8 with some python time module?

What is your purpose here? If you want to parse a text value into a
structured time object, don't do it piece by piece. Use the
‘time.strptime’ function.

 import time
 input_time_text = 14 Aug 2014
 input_time = time.strptime(input_text, %d %b %Y)
 input_time.tm_mon
8

-- 
 \“I knew it was a shocking thing to say, but … no-one has the |
  `\right to spend their life without being offended.” —Philip |
_o__)  Pullman, 2010-03-28 |
Ben Finney

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


Re: what is the / mean in __init__(self, /, *args, **kwargs) ?

2014-08-13 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

  help(int.__init__)
 Help on wrapper_descriptor:

 __init__(self, /, *args, **kwargs)
 Initialize self.  See help(type(self)) for accurate signature.

 what is the / mean in __init__(self, /, *args, **kwargs) ?

I don't know, I haven't seen that before. It is confusing.

At least it is acknowledged (“See [elsewhere] for accurate signature”)
to be unhelpful.

I suspect this is an artefact of the impedance mismatch between Python
function signatures and the implementation of ‘int’ in C code. The “/”
may be a placeholder for something the C implementation requires but
that Python's function signature expectation doesn't allow.

Perhaps Python 3's keyword-only arguments may one day help functions
like that get implemented with a more useful signature, but I'm not
holding my breath for that.

-- 
 \ “Religious faith is the one species of human ignorance that |
  `\ will not admit of even the *possibility* of correction.” —Sam |
_o__) Harris, _The End of Faith_, 2004 |
Ben Finney

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


Re: what is the / mean in __init__(self, /, *args, **kwargs) ?

2014-08-13 Thread Ben Finney
Tim Chase python.l...@tim.thechases.com writes:

 On 2014-08-14 10:01, luofeiyu wrote:
help(int.__init__)
  Help on wrapper_descriptor:
  
  __init__(self, /, *args, **kwargs)
   Initialize self.  See help(type(self)) for accurate signature.
  
  what is the / mean in __init__(self, /, *args, **kwargs) ?

 Where are you seeing this?

I see the same output as ‘luofeiyu’ reports. My Python is::

 sys.version
'3.4.1 (default, Jul 26 2014, 13:46:45) \n[GCC 4.9.1]'

-- 
 \“Stop — Drive sideways.” —detour sign, Kyushu, Japan |
  `\   |
_o__)  |
Ben Finney

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


Re: Captcha identify

2014-08-12 Thread Ben Finney
Wesley nisp...@gmail.com writes:

 If my questions make you guys not so happy, I am sorry and please just
 ignore.

You seek to dismiss the valid concerns by calling them “not so happy”.

You assert it is questions we object to, when we are clearly objecting
to your intentions.

Don't be disingenuous. The responses you get are because there are valid
concerns about the motives you are pursuing.

 Why I need to write such program is just having such requirements

This is a circular statement, almost a tautology. If that is the best
you can present in defense of harmful and deceitful actions, then there
is no good reason for what you're doing.

Stop, please.

-- 
 \“The World is not dangerous because of those who do harm but |
  `\  because of those who look at it without doing anything.” |
_o__) —Albert Einstein |
Ben Finney

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


Re: why i can't copy mail with imaplib?

2014-08-10 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

  x.con.copy(b1,[Gmail]/Important)
 ('NO', [b'[TRYCREATE] No folder [Gmail]/Important (Failure)'])

Your questions have mostly been unrelated to Python, and this is another
example. You should search elsewhere for assistance with IMAP and GMail.

-- 
 \“The restriction of knowledge to an elite group destroys the |
  `\   spirit of society and leads to its intellectual |
_o__)impoverishment.” —Albert Einstein |
Ben Finney

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


Re: The right way to use config files

2014-08-09 Thread Ben Finney
Fabien fabien.mauss...@gmail.com writes:

 So I had the idea to define a super-object which parses the config
 file and input data and is given as a single parameter to the
 processing functions, and the functions take the information they need
 from it.

That's not a bad idea, you could do that without embarrassment.

A better technique, though, is to make use of modules as namespaces.
Have one module of your application be responsible for the configuration
of the application::

# app/config.py

import configparser

parser = configparser.ConfigParser()
parser.read(app.conf)

and import that module everywhere else that needs it::

# app/wibble.py

from . import config

def frobnicate():
do_something_with(config.foo)

By using an imported module, the functions don't need to be
parameterised by application-wide configuration; they can simply access
the module from the global scope and thereby get access to that module's
attributes.

 To get to the point: is it good practice to give all elements of a
 program access to the configfile and if yes, how is it done
 properly?

There should be an encapsulation of the responsibility for parsing and
organising the configuration options, and the rest of the application
should access it only via that encapsulation.

Putting that encapsuation in a module is an appropriately Pythonic
technique.

-- 
 \  “Now Maggie, I’ll be watching you too, in case God is busy |
  `\   creating tornadoes or not existing.” —Homer, _The Simpsons_ |
_o__)  |
Ben Finney

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


Re: How to get mac address of bluetooth with python in win7?

2014-08-07 Thread Ben Finney
elearn elearn2...@gmail.com writes:

 How to get  mac address of bluetooth  with python in win7?

This may not be a Python-specific question. How would you get the MAC
adress of a Bluetooth device in Windows, in any programming language?

My advice is for you to do a web search
URL:https://duckduckgo.com/?q=python+bluetooth+%22mac+address%22+windows.

-- 
 \   “You could augment an earwig to the point where it understood |
  `\ nuclear physics, but it would still be a very stupid thing to |
_o__)  do!” —The Doctor, _The Two Doctors_ |
Ben Finney

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


Re: How to delete letters automatically with imaplib?

2014-08-06 Thread Ben Finney
elearn elearn2...@gmail.com writes:

 status,  data=  con.search(None,  ALL)
 print(len(data[0].split()))
 48
 typ,  data=  con.search(None,  'Body',  'x...@gmail.com')
   data
 [b'1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 
 29
  32 33 34 35 36 37 44']

 len(data[0].split())
 36

 How can i delete 48-36=12 letters?

Set operations are designed for this::

# Construct a set of all message numbers.
status, data = con.search(None, ALL)
ids_of_all_messages = set(data[0].split())

# Construct a set of messages mentioning the address.
status, data = con.search(None, 'Body', 'x...@gmail.com')
ids_of_messages_containing_address = set(data[0].split())

# Get the messages to delete.
ids_of_messages_to_delete = (
ids_of_all_messages - ids_of_messages_containing_address)

-- 
 \ “Too many pieces of music finish too long after the end.” —Igor |
  `\   Stravinskey |
_o__)  |
Ben Finney

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


Re: How to delete letters automatically with imaplib?

2014-08-06 Thread Ben Finney
elearn elearn2...@gmail.com writes:

 and how to write the delete command with imaplib?

(Please don't top-post. Instead, compose your responses interleaved
URL:https://en.wikipedia.org/wiki/Posting_style#Interleaved_style so
the conversation is easier to follow in the message.)

I'm not familiar with the API of the ‘imaplib’ module. Start with
URL:https://docs.python.org/3/library/imaplib.html and remember that
it is a library designed to work intimately with the IMAP
command-response protocol.

If, instead, you wish to manipulate mailboxes without needing to know
much about the detailed features of the storage format, use the
URL:https://docs.python.org/3/library/mailbox.html ‘mailbox’ module
for that purpose.

-- 
 \“No matter how cynical you become, it's never enough to keep |
  `\up.” —Jane Wagner, via Lily Tomlin |
_o__)  |
Ben Finney

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


Re: Test for an empty directory that could be very large if it is not empty?

2014-08-06 Thread Ben Finney
Virgil Stokes v...@it.uu.se writes:

 Suppose I have a directory C:/Test that is either empty or contains
 more than 200 files, all with the same extension (e.g. *.txt). How
 can I determine if the directory is empty WITHOUT the generation of a
 list of the file names in it (e.g. using os.listdir('C:/Test')) when
 it is not empty?

What is your goal for that? Have you measured the performance difference
and decided *based on objective observation* that it's too expensive?

Certainly ‘os.listdir(foo)’ is the simplest way to determine the entries
in a directory, and thereby to test whether it is empty. That simplicity
is very valuable, and you should have a compelling, *measured* reason to
do something more complicated. What is it?

-- 
 \ “The most dangerous man to any government is the man who is |
  `\   able to think things out for himself, without regard to the |
_o__)  prevailing superstitions and taboos.” —Henry L. Mencken |
Ben Finney

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


Re: Test for an empty directory that could be very large if it is not empty?

2014-08-06 Thread Ben Finney
Tim Chase python.l...@tim.thechases.com writes:

 The difference in timings when serving a web-request are noticeable
 (in my use-case, I had to change my algorithm and storage structure to
 simplify/avoid heavily-populated directories)

So, if the requirement is “test whether the directory is empty faster
than N microseconds”, that's quite different from “without the
generation of a list of the file names”.

The former may entail the latter, but that's not to be assumed, and
chasing an optimisation prematurely is a common cause of terrible code.

Therefore, I'm asking the OP what is their (so far unstated) reason for
caring about the implementation of a standard library call.

Without that, it would be folly to try to suggest a solution. With that,
it may turn out the stated requirement isn't relevant for satisfying the
actual requirement. I don't know (and it's possible the OP doesn't
know) the relevance of the “create a list of entries” part, so I asked.

-- 
 \ “Science is a way of trying not to fool yourself. The first |
  `\ principle is that you must not fool yourself, and you are the |
_o__)   easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney

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


Re: Wikibooks example doesn't work

2014-08-06 Thread Ben Finney
Larry Hudson org...@yahoo.com.dmarc.invalid writes:

 I just took a look at that web page, and I see what your problem
 actually is...

 You are misunderstanding the problem. The problem does NOT say to end
 the loop at three tries, just to keep track of the number of tries.
 It's not actually specific, but the implication is that AFTER the loop
 display a message depending on the number of actual tires.

Could it be re-phrased to state the exercise requirements more clearly?
Maybe you could edit the wiki page to prevent future confusion on this
exercise.

-- 
 \ “Are you pondering what I'm pondering?” “I think so, Brain, but |
  `\   wouldn't his movies be more suitable for children if he was |
_o__)  named Jean-Claude van Darn?” —_Pinky and The Brain_ |
Ben Finney

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


<    6   7   8   9   10   11   12   13   14   15   >