Re: Enum with only a single member
Steven D'Aprano writes: > Is it silly to create an enumeration with only a single member? No. > That is, a singleton enum? Why stop there? You can make empty ones too. (Zerotons?) > The reason I ask is that I have two functions that take an enum > argument. Sounds like a good reason. > def spam(arg): > if isinstance(arg, MarxBros): > def ham(arg): > if isinstance(arg, MarxBros) or arg is Unique.FOO: > Good, bad or indifferent? U, that's ugly, but the alternatives are worse unless there's more branches, and maybe even then. -- https://mail.python.org/mailman/listinfo/python-list
Re: Enum with only a single member
On Tue, Jan 10, 2017 at 7:33 PM, Paul Rubin wrote: >> That is, a singleton enum? > > Why stop there? You can make empty ones too. (Zerotons?) Sure you *can*, but I can't think of any time they'd be useful. Can you give an example? ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Is enum iteration order guaranteed?
On 01/09/2017 10:22 PM, Steven D'Aprano wrote: On Tuesday 10 January 2017 16:55, Ethan Furman wrote: On 01/09/2017 09:18 PM, Steven D'Aprano wrote: The docs say that enums can be iterated over, but it isn't clear to me whether they are iterated over in definition order or value order. If I have: class MarxBros(Enum): GROUCHO = 999 CHICO = 5 HARPO = 11 ZEPPO = auto() GUMMO = -1 GROUCHO, CHICO, HARPO, ZEPPO, GUMMO = list(MarxBros) In Python 3 it is always definition order. I only care about Python 3 for this. Did I miss something in the docs, or should this be added? In https://docs.python.org/3/library/enum.html#creating-an-enum, fifth paragraph down: Enumerations support iteration, in definition order ... -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Using namedtuples field names for column indices in a list of lists
On 01/09/2017 11:14 PM, Deborah Swanson wrote: So I guess you should just do your thing and I'll do mine. As you say. Takes all kinds, and I think in the end what will count is the quality of my finished work (which has always been excellent), and not the messy process to get there. Agreed. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Enum with only a single member
On 01/10/2017 12:37 AM, Chris Angelico wrote: On Tue, Jan 10, 2017 at 7:33 PM, Paul Rubin wrote: That is, a singleton enum? Why stop there? You can make empty ones too. (Zerotons?) Sure you *can*, but I can't think of any time they'd be useful. Can you give an example? Sure. Any time you have some base behaviour you want shared amongst multiple Enum classes. ;) -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Enum with only a single member
On 01/10/2017 05:43 AM, Steven D'Aprano wrote: Is it silly to create an enumeration with only a single member? That is, a singleton enum? Don't think so, for the same reason that lists with one element make sense. def ham(arg): if isinstance(arg, MarxBros) or arg is Unique.FOO: ... Good, bad or indifferent? Though I'd write def ham(arg): if arg in MarxBros or arg in Unique: ... JM -- https://mail.python.org/mailman/listinfo/python-list
Re: Enum with only a single member
Steven D'Aprano wrote: > Is it silly to create an enumeration with only a single member? That is, a > singleton enum? > > from enum import Enum > > class Unique(Enum): > FOO = auto() > > > The reason I ask is that I have two functions that take an enum argument. > The first takes one of three enums: > > class MarxBros(Enum): > GROUCHO = 1 > CHICO = 2 > HARPO = 3 > > and the second takes *either* one of those three, or a fourth distinct > value. So in my two functions, I have something like this: > > > def spam(arg): > if isinstance(arg, MarxBros): > ... > > > def ham(arg): > if isinstance(arg, MarxBros) or arg is Unique.FOO: > ... > > > Good, bad or indifferent? I don't see a problem. As it looks like you cannot subclass Enum subclasses alternative spellings might be isintance(args, (MarxBros, Unique)) or BOTH = set(MarxBros) | set(Unique) arg in MarxBros arg in BOTH -- https://mail.python.org/mailman/listinfo/python-list
Re: Temporary variables in list comprehensions
On 01/09/2017 04:53 AM, Steven D'Aprano wrote: Suppose you have an expensive calculation that gets used two or more times in a loop. The obvious way to avoid calculating it twice in an ordinary loop is with a temporary variable: result = [] for x in data: tmp = expensive_calculation(x) result.append((tmp, tmp+1)) But what if you are using a list comprehension? Alas, list comps don't let you have temporary variables, so you have to write this: [(expensive_calculation(x), expensive_calculation(x) + 1) for x in data] Or do you? ... no, you don't! [(tmp, tmp + 1) for x in data for tmp in [expensive_calculation(x)]] I can't decide whether that's an awesome trick or a horrible hack... In any situation, the double list comprehension (also used to flatten lists) is very difficult to read. What about for x in (f(d) for d in data): result.append(x, x+1) There's a double for loop in the same line but the generator parenthesis help a lot. No lame tmp variable involved. JM -- https://mail.python.org/mailman/listinfo/python-list
Re: Temporary variables in list comprehensions
On Monday, 9 January 2017 03:53:37 UTC, Steven D'Aprano wrote: > Suppose you have an expensive calculation that gets used two or more times > in a loop. [...] > [(tmp, tmp + 1) for x in data for tmp in [expensive_calculation(x)]] > > I can't decide whether that's an awesome trick or a horrible hack... My immediate reaction is that it depends on the constraints that made it important for you to use a comprehension rather than an explicit loop in the first place. For a toy example like this it's obviously a horrible hack, and you should simply make an explicit loop: result = [] for x in data: # Don't recalculate this value, as it's expensive! val = expensive_calculation(x) result.append((val, val+1)) In a real world case, maybe there's a good reason why you'd prefer to stick with a comprehension. In that case, you look at trade-offs like def intermediate_tuple(val): return val, val+1 [intermediate_tuple(x) for x in data] or [(lambda val: (val, val+1))(x) for x in data] or your version. All have their own unique uglinesses, as does the explicit loop. Personally my preferences would be the explicit loop, then the intermediate_tuple function, in that order. Paul -- https://mail.python.org/mailman/listinfo/python-list
Re: Announcement: TLSv1.2 will become mandatory in the future for Python.org Sites
On Tue, Jan 10, 2017 at 08:27:21AM -0500, Donald Stufft
wrote:
> python3 -c "import urllib.request,json;
> print(json.loads(urllib.request.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
Fix:
$ python3 -c "import urllib.request,json;
print(json.loads(urllib.request.urlopen('https://www.howsmyssl.com/a/check').read().decode('ascii'))['tls_version'])"
Oleg.
--
Oleg Broytmanhttp://phdru.name/[email protected]
Programmers don't die, they just GOSUB without RETURN.
--
https://mail.python.org/mailman/listinfo/python-list
Re: The hardest problem in computer science...
On Saturday, 7 January 2017 19:14:43 UTC, Ethan Furman wrote: > Ya know, that looks an /awful/ lot like a collection! Maybe even an Enum? ;) > > -- 8< --- > from aenum import Enum # note the 'a' before the 'enum' :) > > class Theme(Enum, init='v vr llc'): > DEFAULT = "│ ", "├─ ", "└─ " > BOLD = "┃ ", "┣━ ", "┗━ " > ASCII = "| ", "|- ", "+- " > > def draw_tree(tree, theme=Theme.DEFAULT): > print(theme.v) > print(theme.vr) > print(theme.v) > print(theme.llc) > > draw_tree(None) I noted the "a" before enum :-) Is the implication that this form (a sort of combined namedtuple/enum) *isn't* possible with the stdlib enum? But rather that it's specific to your aenum module? I don't see any documentation for the "init" parameter in either version, so I'm a little puzzled. The capability seems neat, although (as is probably obvious) the way you declare it seems a little confusing to me. Paul -- https://mail.python.org/mailman/listinfo/python-list
Re: The hardest problem in computer science...
On Tuesday, 10 January 2017 15:47:20 UTC, Paul Moore wrote: > On Saturday, 7 January 2017 19:14:43 UTC, Ethan Furman wrote: > > Ya know, that looks an /awful/ lot like a collection! Maybe even an Enum? > > ;) > > > > -- 8< --- > > from aenum import Enum # note the 'a' before the 'enum' :) > > > > class Theme(Enum, init='v vr llc'): > > DEFAULT = "│ ", "├─ ", "└─ " > > BOLD = "┃ ", "┣━ ", "┗━ " > > ASCII = "| ", "|- ", "+- " > > > > def draw_tree(tree, theme=Theme.DEFAULT): > > print(theme.v) > > print(theme.vr) > > print(theme.v) > > print(theme.llc) > > > > draw_tree(None) > > I noted the "a" before enum :-) > > Is the implication that this form (a sort of combined namedtuple/enum) > *isn't* possible with the stdlib enum? But rather that it's specific to your > aenum module? I don't see any documentation for the "init" parameter in > either version, so I'm a little puzzled. > > The capability seems neat, although (as is probably obvious) the way you > declare it seems a little confusing to me. > > Paul After a bit more digging I found https://docs.python.org/3.6/library/enum.html#planet which looks like a stdlib-supported way of doing the same sort of thing. I assume init is an aenum convenience argument to do the same? Anyway, it's a neat feature - I'd not really looked beyond the surface of the new enum module, looks like I missed some good stuff :-) Paul -- https://mail.python.org/mailman/listinfo/python-list
Re: Announcement: TLSv1.2 will become mandatory in the future for Python.org Sites
> On Jan 10, 2017, at 9:59 AM, Oleg Broytman wrote:
>
> On Tue, Jan 10, 2017 at 08:27:21AM -0500, Donald Stufft
> wrote:
>>python3 -c "import urllib.request,json;
>> print(json.loads(urllib.request.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"
>
> Traceback (most recent call last):
> File "", line 1, in
> File "/usr/lib/python3.4/json/__init__.py", line 312, in loads
>s.__class__.__name__))
> TypeError: the JSON object must be str, not ‘bytes'
>
Huh, just tested, my original snippet works on Python 3.6 but fails on Python
3.5.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Announcement: TLSv1.2 will become mandatory in the future for Python.org Sites
On 10-1-2017 16:01, Donald Stufft wrote: >> TypeError: the JSON object must be str, not ‘bytes' > Huh, just tested, my original snippet works on Python 3.6 but fails on Python > 3.5. My guess is that is due to an improvement in 3.6 mentioned here: https://docs.python.org/3/whatsnew/3.6.html#json Irmen -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with this code
On Monday, January 9, 2017 at 12:50:11 PM UTC-8, Joaquin Alzola wrote:
> >> elements. For example, if we have a list_a=["a","b","c","d"] and
> >> list_b=["a","b"] I want to obtain a new list_c containing elements that
> >> match between these lists (a and b here),
>
> >Perhaps this might work:
>
> list(set(list_a).intersection(set(list_b)))
> >['a', 'b']
>
> >>> list_a={"a","b","c","d"}
> >>> list_b={"a","b"}
> > sorted(list_a & list_b)
> ['a', 'b']
You might want to use some other names for the objects you defined: "list_a"
and "list_b" are not lists, they are sets. Of course it doesn't matter if it's
two throw-away lines typed into the interpreter, but in code that you share
with someone else (especially a beginner like the OP), it could be confusing.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Work between multiple processes
Hi Irmen,
I have successfully got it to work with both side as python but so far having
trouble with pyrolite.jar which is downloaded from
https://mvnrepository.com/artifact/net.razorvine/pyrolite/4.4
Having simple codes as:
public static void main(String[] args) {
//System.out.println("Hello world");
try {
String uri =
"PYRO:obj_12a65b09f95f4ee9bec5958f819ced45@localhost:64404";
PyroURI pyURI = new PyroURI(uri);
PyroProxy pyroP = new PyroProxy(pyURI);
Object result = pyroP.call("getDst");
String message = (String) result;
System.out.println("result message=" + message);
pyroP.close();
}
catch (IOException e1) {
System.out.println(e1.getMessage());
}
catch (PickleException e2)
{
System.out.println(e2.getMessage());
}
catch (PyroException e3)
{
System.out.println(e3.getMessage());
}
}
which "getDst" works on Java but hangs on handshake() in the call function.
Any thought? Thanks. -P
--
https://mail.python.org/mailman/listinfo/python-list
Re: Temporary variables in list comprehensions
On Tuesday 10 January 2017 00:12, Antoon Pardon wrote: > Op 09-01-17 om 04:53 schreef Steven D'Aprano: >> Suppose you have an expensive calculation that gets used two or more times >> in a loop. The obvious way to avoid calculating it twice in an ordinary loop >> is with a temporary variable: [...] >> I can't decide whether that's an awesome trick or a horrible hack... > > Maybe this in an occasion to use your recipe. > > http://code.activestate.com/recipes/580625-collection-pipeline-in-python/ > > result = data | Map(expensive_calculation) | Map(lambda tmp: (tmp, tmp + 1)) > | List > Indeed :-) -- Steven "Ever since I learned about confirmation bias, I've been seeing it everywhere." - Jon Ronson -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about abstract base classes and abstract properties -- Python 2.7
I was rereading the 2.7 docs about abstract base classes the other day. I found this line in the usage section of the abc.abstractproperty function: "This defines a read-only property; you can also define a read-write abstract property using the ‘long’ form of property declaration:" along with an example. so I copied the example and put in a little surrounding code: from abc import ABCMeta, abstractproperty class C(object): __metaclass__ = ABCMeta def getx(self): pass def setx(self, value): pass x = abstractproperty(getx, setx) class D(C): @property def x(self):self._x d = D() print(d) When I ran this, I expected an exception, since I defined a read/write abstract property but only implemented the read operation. However, the example runs fine. That is the class D can be instantiated without error. Of course I cannot set the property since I didn't implement that part. Now, If I don't implement the property at all, I can't instantiate the class. I get: "TypeError: Can't instantiate abstract class D with abstract methods x" which is what I would expect. What I don't understand is why I don't get a similar error when I implement the read operation for the property but not the write operation. If this actually doesn't work (catching the non-implementation at instantiation time), then would it be appropriate to amend the documentation? To me at least the doc implies that it *will* raise on the missing write property implementation (otherwise, what's the point of the example?) Or, am I just not grokking it properly? -- https://mail.python.org/mailman/listinfo/python-list
Re: The hardest problem in computer science...
On 01/10/2017 08:06 AM, Paul Moore wrote: On Tuesday, 10 January 2017 15:47:20 UTC, Paul Moore wrote: On Saturday, 7 January 2017 19:14:43 UTC, Ethan Furman wrote: Ya know, that looks an /awful/ lot like a collection! Maybe even an Enum? ;) -- 8< --- from aenum import Enum # note the 'a' before the 'enum' :) class Theme(Enum, init='v vr llc'): DEFAULT = "│ ", "├─ ", "└─ " BOLD = "┃ ", "┣━ ", "┗━ " ASCII = "| ", "|- ", "+- " def draw_tree(tree, theme=Theme.DEFAULT): print(theme.v) print(theme.vr) print(theme.v) print(theme.llc) draw_tree(None) I noted the "a" before enum :-) Is the implication that this form (a sort of combined namedtuple/enum) *isn't* possible with the stdlib enum? But rather that it's specific to your aenum module? It's possible with the stdlib version, and a built-in convenience with aenum. I don't see any documentation for the "init" parameter in either version, so I'm a little puzzled. It's in the docs for aenum, which you will get with the source download. I need to figure out how to get them included in the wheels. :( The capability seems neat, although (as is probably obvious) the way you declare it seems a little confusing to me. Yes, it is possible to pass keyword arguments in a class header, although (as far as I know) very few make use of this. Anyway, it's a neat feature - I'd not really looked beyond the surface of the new enum module, looks like I missed some good stuff :-) Lot's of good stuff in the stdlib, but who has time to learn it all? :( -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about abstract base classes and abstract properties -- Python 2.7
On Wednesday 11 January 2017 12:26, Gerald Britton wrote: > I was rereading the 2.7 docs about abstract base classes the other day. I > found this line in the usage section of the abc.abstractproperty function: > > "This defines a read-only property; you can also define a read-write > abstract property using the ‘long’ form of property declaration:" > > along with an example. so I copied the example and put in a little > surrounding code: > > > from abc import ABCMeta, abstractproperty > > class C(object): > __metaclass__ = ABCMeta > def getx(self): pass > def setx(self, value): pass > x = abstractproperty(getx, setx) > > class D(C): > @property > def x(self):self._x > > d = D() > print(d) > > When I ran this, I expected an exception, since I defined a read/write > abstract property but only implemented the read operation. I expected the same thing. [...] > If this actually doesn't work (catching the non-implementation at > instantiation time), then would it be appropriate to amend the > documentation? To me at least the doc implies that it *will* raise on the > missing write property implementation (otherwise, what's the point of the > example?) Personally, I consider this a design bug: as designed, abstractproperty is broken. But I couldn't call it a functional bug: it looks like it is working as documented, as useless as that it. Note that in Python 3.3 and better, abstractproperty is deprecated: the ABC metaclass is smart enough to work with the regular property decorator: https://docs.python.org/3.6/library/abc.html#abc.abstractproperty > Or, am I just not grokking it properly? No, I agree with you. I think that a bug request to improve the documentation is appropriate. -- Steven "Ever since I learned about confirmation bias, I've been seeing it everywhere." - Jon Ronson -- https://mail.python.org/mailman/listinfo/python-list
RE: Using namedtuples field names for column indices in a list of lists
On Tuesday 10 January 2017 18:14, Deborah Swanson wrote:
> I'm guessing that you (and those who
> see things like you do) might not be used to working with quick learners
> who make mistakes at first but catch up with them real fast, or you're
> very judgemental about people who make mistakes, period. I certainly
> don't care if you want to judge me, you're entitled to your opinion.
Be fair. We're not mind-readers, and we're trying to help you, not attack you.
It is true that we're often extremely pedantic. Sometimes annoyingly so, but on
the other hand precision is important, especially in technical fields. There's
a *huge* difference between a MTA and a MUA, even though they differ only by
one letter and both are related to email.
One of the techs I work with has the same habit of correcting me, and when I'm
invariably forced to agree that he is technical correct, he replies "technical
correctness is the best kind of correctness". Annoying as it is to be on the
receiving end, he is right: at least half the time I learn something from his
pedantry. (The other half of the time, its a difference that makes no
difference.)
What are we supposed to do when somebody asks a question based on an obvious
mistake? Assume that they're a quick learner who has probably already worked
out their mistake and doesn't need an answer? That would certainly make our
life easier: we can just ignore everybody's questions.
Sometimes people make errors of terminology that doesn't affect the semantics
of what they're asking:
"I have an array [1, 2, 3, 4] and I want to ..."
It's very likely that they have a list and they're merely using a term they're
familiar with from another language, rather than the array module.
But what are we supposed to make of mistakes that *do* affect the semantics of
the question:
"I have a dict of ints {1, 2, 3, 4} and want to sort the values by
key so that I get [4, 2, 3, 1], how do I do that?"
How can we answer that without correcting their misuse of terminology and
asking for clarification of what data structure they *actually* have?
We get questions like this very frequently. How would you answer it?
Or:
"I have a list l = namedtuple('l', 'field1 field2') and can't
extract fields by index, l[0] doesn't work..."
Of course it doesn't work. How would you respond to that if you were in our
place?
- ignore the question because the poster is ever so smart and will have
worked it out by now?
- point out that l is not a list, or even a tuple, and of course l[0]
doesn't work because l is actually a class?
Its easy to criticise us for answering the questions you ask instead of the
questions you intended, but we're not mind-readers. We don't know what you're
thinking, we only know what you communicate to us. Telling us off for answering
your questions is hardly likely to encourage us to answer them in the future.
--
Steven
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." - Jon Ronson
--
https://mail.python.org/mailman/listinfo/python-list
