Regarding the parsing of await expression.

2016-11-06 Thread Shiyao Ma
Hi,

In the pep, 
https://www.python.org/dev/peps/pep-0492/#examples-of-await-expressions 

It is said,

await await coro()  is SyntaxError, instead, we should use await (await coro())
Why? because of await is not left-associative?


also, for 
await -coro() , it should be written as,  await (-coro())

I don't understand the point here.  Why can't the parser figure out it indeed 
is await (-coro()) ?


Is it due to the fact Python uses LL(1) or just because of current impl doesn't 
do that?

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


The order of iterable de-referencing in assignment?

2016-08-24 Thread Shiyao Ma
Hi,

Given a = [1, 2]

a.extend(a) makes a = [1,2, 1,2]

One might guess a.extend(a) would turn into an infinite loop.  It turns out 
here Python first gets all the items of `a' and then append them to `a', so the 
infinite loop is avoided.

My question is, is there any doc on the behavior of things like this?

Another related example might be:
a[:] = a
Hopefully Python first gets all the items on the *right* side and then assigns 
them to the left.

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


Why monkey patching on module object doesn't work ?

2016-08-17 Thread Shiyao Ma
Hi,

I am using Python2.

For the following snippet,

http://ideone.com/i36pKO

I'd suppose the dummy_func would be invoked, but seems not.

Indeed, heapq.heapify does invoke cmp_lt per here:
https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l136

So why this way of monkey patching failed?



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


How to simulate C style integer division?

2016-01-21 Thread Shiyao Ma
Hi,

I wanna simulate C style integer division in Python3.

So far what I've got is:
# a, b = 3, 4

import math
result = float(a) / b
if result > 0:
  result = math.floor(result)
else:
  result = math.ceil(result)


I found it's too laborious. Any quick way?

-- 

吾輩は猫である。ホームーページはhttps://introo.me 。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is the c source code of the import mechanism that ignores invalid directory?

2015-07-21 Thread Shiyao Ma
Yep. I followed from bltmodule.c(the import function) and got to the
import.c file, and finally got lost.


Regards.

On Tue, Jul 21, 2015 at 12:16 PM, Mark Lawrence 
wrote:

> On 21/07/2015 16:35, Shiyao Ma wrote:
>
>> Hi,
>>
>> It looks to me that the import system of Python will ignore invalid
>> directories and cache the result in memory.
>>
>> For example, the following code:
>> paste here: https://bpaste.net/show/b144deb42620
>>
>> #!/usr/bin/env python3
>>
>> import  sys
>> import  os
>> import  shutil
>>
>> sys.path.append("./test")
>> shutil.rmtree("./test",  ignore_errors=True)
>>
>> try:
>>  import  foo
>> except  ImportError:
>>  os.mkdir("./test")
>>  with  open("./test/foo.py",  "w")  as  f:
>>  f.write("print(3)")
>>
>>  import  foo
>>
>> the second import foo will fail even though it's there. This is because
>> when doing the first import foo, the directory .test doesn't exist, and
>> Python ignores that directory forever.
>>
>>
>> I am interested in the c side implementation of this "ignoring" part.
>>
>>
>> Any body help me to pinpoint the exact c source location?
>>
>> Thanks.
>>
>> --
>>
>> 吾輩は猫である。ホームーページはhttps://introo.me <http://introo.me>。
>>
>>
> Start here https://hg.python.org/cpython/file/6629773fef63/Python/import.c
>
> --
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
>
> Mark Lawrence
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 

吾輩は猫である。ホームーページはhttps://introo.me <http://introo.me>。
-- 
https://mail.python.org/mailman/listinfo/python-list


Where is the c source code of the import mechanism that ignores invalid directory?

2015-07-21 Thread Shiyao Ma
Hi,

It looks to me that the import system of Python will ignore invalid
directories and cache the result in memory.

For example, the following code:
paste here: https://bpaste.net/show/b144deb42620

#!/usr/bin/env python3
import sysimport osimport shutil
sys.path.append("./test")shutil.rmtree("./test", ignore_errors=True)
try:
import fooexcept ImportError:
os.mkdir("./test")
with open("./test/foo.py", "w") as f:
f.write("print(3)")

import foo

the second import foo will fail even though it's there. This is because
when doing the first import foo, the directory .test doesn't exist, and
Python ignores that directory forever.


I am interested in the c side implementation of this "ignoring" part.


Any body help me to pinpoint the exact c source location?


Thanks.


-- 

吾輩は猫である。ホームーページはhttps://introo.me 。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why PyINCREF on _PyFalseStruct and _PyTrueStruct?

2015-04-08 Thread Shiyao Ma
On Wed, Apr 8, 2015 at 11:24 AM, Ian Kelly  wrote:
> The ref count is incremented because the caller will decrement it when
> it's done with the reference.

That makes sense.

To be generic, the caller won't check what the returned result is. It
just takes it as a normal PyObject. Traditionally, for functions like
above, the reference is assumed to be transferred to the caller.

Regards.

-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Why PyINCREF on _PyFalseStruct and _PyTrueStruct?

2015-04-08 Thread Shiyao Ma
Hi.

While reading the rich_compare of PyLongObject, I noticed this line:

https://hg.python.org/cpython/file/a49737bd6086/Objects/longobject.c#l2785

It increments the ob_ref of the builtin True/False object.

Initializing the ob_ref of True/False to one so that they won't be
garbage collected if fair enough. Why do we increment it?

I don't see the reason behind it, since these two objects should
always stay in the memory and never participate the garbage collecting
system.


Regards.

-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Weird behavior on __dict__ attr

2015-02-09 Thread Shiyao Ma
Hi.

My context is a little hard to reproduce.

NS3 is a network simulation tool written in C++. I am using its Python binding.

So the class I am dealing with is from a .so file.

Say, I do the following:

%

import ns.network.Node as Node

# Node is a class
# it has a __dict__ attr

# Now I instantiate an instance of Node
n = Node()

# I checked, there is no __dict__ on 'n'
# but the following succeeds.

n.foobar = 3



My understanding is the foobar is stored in n.__dict__, but seemingly n has no 
__dict__.

So where does the foobar go?


TIA.



-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with for and if

2015-01-05 Thread Shiyao Ma
On Jan 05 at 22:38 +0800, Shiyao Ma wrote:

> More preferably, you should repetitively use "str.find"
>
> Or just use `max(0,len(zmienna.split(szukana))-1)`

Forgot there was a `str.count`, ;).

-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: problem with for and if

2015-01-05 Thread Shiyao Ma
On Jan 05 at 06:27 -0800, Dariusz Mysior wrote:
> I want search count of szukana in zmienna but code below counting all 12 
> letters from "traktorzysta" word
>
> szukana="t"
> zmienna="traktorzysta"
>
>
> def gen():
> count=int(0)
> for a in zmienna:
> if szukana in zmienna:
> count+=1
> else:
> continue
> return count

def gen():
count = 0
for a in zmienna:
# we assume szukana is a single letter
if szukana == a:
count+=1
else:
continue
return count

More preferably, you should repetitively use "str.find"

Or just use `max(0,len(zmienna.split(szukana))-1)`

-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested loops is strangely slow, totally at a loss.

2014-12-10 Thread Shiyao Ma
Thanks guys.

I was only aware of a limited iterables which themselves are iterators, e.g., 
the generator.

Seems like its really a pitfall. Any glossary, list on the iterables that 
*might* exhaust themselves?


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


Re: Nested loops is strangely slow, totally at a loss.

2014-12-09 Thread Shiyao Ma
One thing to note, the logic of using "in" is not of concern here.
This is a *contrived* example, the problem is the slowness of the first
iteration.
-- 
https://mail.python.org/mailman/listinfo/python-list


Nested loops is strangely slow, totally at a loss.

2014-12-09 Thread Shiyao Ma
When doing nested loop, the very first iteration of the innermost loop ends 
ultimately slow.

Let's the code speak.

The following code is quite contrived. Actually it's derived from my 3d-dct 
script.
The actual difference is way more significant than this example.

In case of any evil of gmail, bpaste here: https://bpaste.net/show/edfef62edb17

# this constructs a space_len x space_len x space_len 3D coordinate
import timeit
from itertools import product
space_len = 580
space = product(xrange(space_len), xrange(space_len), xrange(space_len))


sparse_cloud = product(xrange(1), xrange(1), xrange(1))

for i, j, k in sparse_cloud:
ts = timeit.default_timer()
if (i, j, k) in space: pass
te = timeit.default_timer()
print("A, finish a loop with ", te-ts)
print("Done Test A")


sparse_cloud = product(xrange(1000), xrange(1000), xrange(1000))
for i, j, k in sparse_cloud:
ts = timeit.default_timer()
if (i, j, k) in space: pass
te = timeit.default_timer()
print("B, finish a loop with ", te-ts)
print("Done Test B")


# example output
"""
('A, finish a loop with ', 2.1457672119140625e-06)
Done Test A
('B, finish a loop with ', 8.736134052276611)
('B, finish a loop with ', 1.9073486328125e-06)
('B, finish a loop with ', 0.0)
('B, finish a loop with ', 0.0)
('B, finish a loop with ', 1.1920928955078125e-06)
('B, finish a loop with ', 9.5367431640625e-07)
('B, finish a loop with ', 9.5367431640625e-07)
...
"""

We can see that the first iteration of B ends rather slow, 8.7 seconds here.

Why? I am curious about the internals, what's happening under the hood that 
makes this happen?

Thanks in advance!


-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python re.search simple question

2014-12-07 Thread Shiyao Ma
On Dec 08 at 12:22 +0530, Ganesh Pal wrote:
> Hi Folks ,
>
> This  might seem to be very trivial question but iam breaking my head over
> it for a while .
>
>  My understanding is that re.search should search for the match anywhere in
> the string .
>
>
> why is re.search failing in the below case  ??
>
> >>> pattern
> 'Token-based migrations cannot be mixed with level-based: [prev 0 , now 1]'

I sense a bad smell. Be sure to escape the bracket [ ]

> >>> text
> ' LogMessage {type NDMP_LOG_DBG} {msg_id 0} {msg The process id for NDMP
> service is 0x9c216370} {associated_msg 0} {associated_msg_seq 0} Source
> filer:DartOS  Error: Token-based migrations cannot be mixed with
> level-based: [prev 0 , now 1]'
>
> >>> if (re.search(pattern,text)):
> ...print "Hi"
> ... else:
> ... print "BYE"
> ...

so see here: https://bpaste.net/show/d2f1cf66a492 . It prints "HI"

/me always wishes code is sent without others doing some extra formatting 
before testing.

Hope that helps.




-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Setting default_factory of defaultdict to key

2014-12-07 Thread Shiyao Ma
On Dec 07 at 11:31 -0500, Dave Angel wrote:
> Since this clearly is intended to be part of the earlier thread, please make
> it so by using reply-list or whatever equivalent your email program has.

Kinda OT. But interested what's the difference between reply-list and to.
In addition, based on what information a thread is formed?

-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Tuple of lists concatenation - function vs comprehension

2014-12-07 Thread Shiyao Ma
On 12/07, Ivan Evstegneev wrote:
> Hello,
>
> When I have worked  in Python shell (IDLE) I found this issue:
>
> >>>x = ([1, 2], [3, 4], [5, 6])
> >>>L = []
> >>>for I in x:
>   L.extend(i)
>
> >>>L
> [1,2,3,4,5,6]
>
> But when I try to make comprehension using above expression, I get this:
>
> >>>x = ([1, 2], [3, 4], [5, 6])
> >>>L = []
> >>> [L.extend(i) for i in x]
> [None, None, None]

Yes. per the doc, list.extend() returns None.

>
> But this works fine within function:
>
> >>> def myfunc():
>   x = ([1, 2], [3, 4], [5, 6])
>   L = []
>   [L.extend(i) for i in x]
>   print(L)
>
> >>>myfunc()
> [1, 2, 3, 4, 5, 6]

This is also so true, as you are print the var 'L'.

>
> The question is why I'm getting empty list while working with comprehension
> in interactive console?

You are also getting [None]*3 in comprenhension inside a function.

-- 
Shiyao Ma
http://introo.me
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you use self in __str__

2014-11-28 Thread Shiyao Ma
2014-11-29 11:36 GMT+08:00 Chris Angelico :
> You can use id() on any object. You are guaranteed to get back an
> integer which is both stable and unique among all ids of objects that
> exist at the same time as the one you called it on. For as long as the
> object continues to exist, that number *will* stay the same. Sometimes
> that's all you need; for instance, imagine a simple mail server which
> produces logs like this:
>
> [142857] Beginning processing of message
> [142857] Parsing headers
> [314159] Beginning processing of message
> [314159] Parsing headers
> [142857] Storing in destination mailbox
> [314159] Connecting to destination server
> [142857] Finished processing of message
> [314159] Message accepted by destination
> [271871] Beginning processing of message
> [314159] Finished processing of message
>
> You can easily see, from the initial numbers, what log lines are
> associated with what messages. (Note that emails have their own IDs,
> which could in theory be used, but the id() of an internal dict can be
> used even before the email's ID has been read - as you see from the
> example, a log entry for "Parsing headers" has to be made prior to
> info from the headers being used.) It's not a problem if another
> 142857 comes up later on; there's a very clear begin and end to the
> message, and you're guaranteed that nothing can possibly be
> interspersed with a colliding ID.
>
> In other implementations of Python, these numbers might look less
> arbitrary (Jython, I believe, allocates them sequentially); but the
> code will work just as well on any compliant implementation of the
> language, because everything I've said above is a language guarantee,
> not a CPython implementation detail.
>
> ChrisA


Thanks. Informed.
The implementation dependent thing is "id(obj)" == virtual mem addr
(which caused my bad feeling).
Apparently have nothing to do with it here, though.

And 'id' is seemingly great to differentiate each obj.



--

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you use self in __str__

2014-11-28 Thread Shiyao Ma
2014-11-28 13:00 GMT+08:00 Chris Angelico :
> On Fri, Nov 28, 2014 at 2:04 PM, Shiyao Ma  wrote:
>> What if it's in the local namespace of a function or method? IDK, try
>> to get that thing first.
>
Sure enough. I will even avoid using "id" as it's dependent on CPython
implementation. :)

> What if it's in multiple namespaces? What if it's not in any at all?
> Your solution is not going to work in the general case, AND it's a bad
> idea.
> Please don't do this in any code that I'll ever have to
> maintain.
No way. You will never get my project code in such a form. I am way
more peculiar about readability and robustness than most of my other
ppl.
The point is, the bpate is just for demonstration to show there is a
*possible* way to find the name even you didn't specify it at first
hand.




-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Can you use self in __str__

2014-11-27 Thread Shiyao Ma
2014-11-28 9:26 GMT+08:00 Seymore4Head :
> def __str__(self):
> s = "Hand contains "
> for x in self.hand:
> s = s + str(x) + " "
> return s
>
> This is part of a Hand class.  I need a hand for the dealer and a hand
> for the player.
> dealer=Hand()
> player=Hand()
> This prints out 'Hand contains " foo bar
> for both the dealer's hand and the player's hand.
>
> Is there a way to include "self" in the __string__ so it reads
> Dealer hand contains foo bar
> Player hand contains foo bar

I bet you want the object name (aka, dealer, player) be included in
the string 's'.
To that end, you need to access the namespace where 'self' is in.
But I dunno where the namespace 'self' resides in.
Does PyObject has a field to store the namespace of an object?
Appreciated if anyone could
inform me on this.

Now, make a little assumption that the instance lives in the module
level. Then we can do
this:

#!/usr/bin/env python

class Hand(object):
def __init__(self):
self.hand = [1, 2, 3, 4]

def __str__(self):
s = self._myname + " hand contains "
for x in self.hand:
s = s + str(x) + " "
return s

@property
def _myname(self):
# get the module
mod = self.__module__
import sys
ns = vars(sys.modules[mod])
# NB only works the instance is at the module level
for name, obj in ns.iteritems():
if id(obj) == id(self):
break
else:
#nothing found
return ""
return name

John = Hand()
print(John)

# this prints
# John hand contains 1 2 3 4

bad indentation with my wasavi plugin, see paste:

https://bpaste.net/show/f5b86957295f


What if it's in the local namespace of a function or method? IDK, try
to get that thing first.


Regards






--

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Understanding co_lnotab

2014-09-26 Thread Shiyao Ma
When reading the notes on co_lnotab

I totally got lost at this
line:https://hg.python.org/cpython/file/fd0c02c3df31/Objects/lnotab_notes.txt#l31

It says,"In case #b, there's no way to know
 from looking at the table later how many were written."


No way to know "what" is written?
And why no way to know "how many" times?


Regards


-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


What's the function location that reads the cached .pyc file from disk.

2014-09-15 Thread Shiyao Ma
Hi.

what's the location of the function that reads the .pyc file ?

I bet it should lie in somewhere in
https://hg.python.org/cpython/file/322ee2f2e922/Lib/importlib

But what's the actual location?


Btw, why I need it?
I want to know the structure of a .pyc file. Of course the function
that reads the .pyc must know something about it.
(I am aware of the structure of a typical .pyc file from some clicks
of google pages, but I am interested in the *source* and the most
authoritative answer, aka, the source code).

Thanks.


-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyWart(2.7.8) IDLE is more buggy than "Joe's apartment"!

2014-07-21 Thread Shiyao Ma
No intent to pollute this thread.

But really interested in the invalid@invalid.invalid mailing address.
And,,, obviously, I cannot send to invalid@invalid.invalid, so

How does you(he) make this?

2014-07-21 22:27 GMT+08:00 Grant Edwards :

> I was always taught that it's a "bug" is when a program doesn't do
> what a reasonable user expects -- that it's got nothing to do with the
> programmer's intent.
>
> --
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Python3+Vim dev environment

2014-07-17 Thread Shiyao Ma
Hi.

Anyone with working experience on setting up Python3 dev with vim?
functionalities needed: code completion and jump to defintion

YCM suffices but only with py2.
Any vim (plugin) for py3?

Or do you have any experience both running YCM and jedi-vim(for py3) ?
How's that going?


Regards

-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


How do you use `help` when write your code

2014-07-06 Thread Shiyao Ma
Hi Pythonistas

I often heard people mention use help(ob) as a way of documentation
look up. Personally I seldom/never do that. My normal workflow is use
ipython, obj? or obj?? for quick look up or use docs.python.org for a
detailed read.


Do you use `help`? How does it integrate into your workflow?

Or instead, what similar tools do you use?


Regards.

shiyao

-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how can i get the source code of goagent.exe?

2014-07-02 Thread Shiyao Ma
Ask on the goagent googlecode?


exe is fow win, dig out more on the linux version. I bet it should be
delivered with py source in that version.


Regards.

2014-07-03 10:20 GMT+08:00 liuerfire Wang :
> Hi 水静流深
> the source code is on https://github.com/goagent/goagent
>
> Hi Terry,
> GoAgent, a tool to help cross the GFW, is written by Python not Go. So this
> may be not off-topic. :P
>
>
> On Thu, Jul 3, 2014 at 6:40 AM, 水静流深 <1248283...@qq.com> wrote:
>>
>> There is a open source project-goagent,when you download it and extract
>> it,
>> code.google.com/p/goagent/downloads‍
>>
>>  in the local diretory, a file named goagent.exe in it.
>>
>> how can i get the source code of goagent.exe ,not the binary form ,the
>> text form.
>>
>>
>>
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> Best regards.
> /**
> google+: +liuerfire twitter: @liuerfire
> 蛋疼不蛋疼的都可以试着点一下~^_^~
> ***/
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: First time I looked at Python was(...)

2014-06-10 Thread Shiyao Ma
I wonder if it's opensourced. I am kinda interested in its implementation.
On the whole, the performance is rather good.


2014-06-10 22:39 GMT+08:00 Mark H Harris :

> On 6/9/14 3:54 PM, Carlos Anselmo Dias wrote:
>
>> Hi ...
>>
>> I'm finishing my messages with this ...
>>
>> The first time I looked into Python was +- 10 years ago ... and in the
>> last 10 years I did not spent more than 30 minutes looking at ... but I
>> like it ... it's easy to read ... even if I'm not familiar with the
>> syntax of ...
>>
>> When you look at the script I provided you in my first post ... if
>> you're capable of thinking about it ... yoy can see countless
>> terabytes/petabytes of information indexed .. it doesn't matter what
>> you're daling with ...it might be millions of databases or billions of
>> files ...
>>
>> I spent the last two days thinking about what I want to implement(...)
>> ... looking at your posts ... thinking in the wideness and in the
>> particularity of the detail ...
>>
>> I really consider that Python is one good option(probably the best) ...
>> the programmers need less lines of code to achieve what must be achieved
>> ... and this is one great advantage ...
>>
>> If you read what I wrote in my first post ->'Python team(...)' and if
>> somehow you're capable of visualize that integrated with logs ,etc ...
>> advertisement included, manipulation of the search string in the client
>> apis, etc ... you're very probably very capable of ...
>>
>> (...)
>>
>> Best regards,
>> Carlos
>>
>
> This is the funniest troll I have see in a while... and a bot to boot!
>
> ~cool
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: try/except/finally

2014-06-09 Thread Shiyao Ma
It would be great if someone could discuss it from the viewpoint of
bytecode. e.g., how the stack is popped, etc.


2014-06-09 17:40 GMT+08:00 Marko Rauhamaa :

> Philip Shaw :
>
> > OTOH, it could just be that Guido didn't think of banning [return from
> > finally] when exceptions were first added and doesn't want to
> > introduce an incompatability later.
>
> You don't have to ban all nonsensical things. Most guns allow you to
> shoot yourself in the foot, even those with static type checking.
>
>
> Marko
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: None in string => TypeError?

2014-06-09 Thread Shiyao Ma
2014-06-09 23:34 GMT+08:00 Roy Smith :

> We noticed recently that:
>
> >>> None in 'foo'
>
> raises (at least in Python 2.7)
>
> TypeError: 'in ' requires string as left operand, not NoneType
>
> This is surprising.  The description of the 'in' operatator is, 'True if
> an item of s is equal to x, else False '.  From that, I would assume it
> behaves as if it were written:
>
> for item in iterable:
> if item == x:
> return True
> else:
> return False
>
> why the extra type check for str.__contains__()?  That seems very
> unpythonic.  Duck typing, and all that.
>

It's a little bit inconsistent.  But it's clearly documented here:
https://docs.python.org/3/reference/expressions.html#in

Which, according to its own logic, the string is not  a *container* type.
It's just some chars, and that totally makes sense for to restrict the type
of x in "str" to be convertible to type str. On the other hand, containers
like list, and tuple, they are heterogeneous by default in Python, so a
item by item comparison is needed.



-- 

吾輩は猫である。ホームーページはhttp://introo.me。
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bug? ( () == [] ) != ( ().__eq__([]) )

2013-08-07 Thread Shiyao Ma
Sorry. I don't quite get it. As you said, it first tries,
leftOperand.__eq__(rightOperand) then if it returns NotImplemented, it goes
to invoke rightOperand.__eq__(leftOperand). But for any reason, [] == ()
returns false, why?


On Mon, Aug 5, 2013 at 7:06 AM, Chris Angelico  wrote:

> On Sun, Aug 4, 2013 at 11:35 PM, Markus Rother 
> wrote:
> > Hello,
> >
> > The following behaviour seen in 3.2 seems very strange to me:
> >
> > As expected:
>  () == []
> > False
> >
> > However:
>  ().__eq__([])
> > NotImplemented
>  [].__eq__(())
> > NotImplemented
>
> You don't normally want to be calling dunder methods directly. The
> reasoning behind this behaviour goes back to a few things, including a
> way to handle "1 == Foo()" where Foo is a custom type that implements
> __eq__; obviously the integer 1 won't know whether it's equal to a Foo
> instance or not, so it has to defer to the second operand to get a
> result. This deferral is done by returning NotImplemented, which is an
> object, and so is true by default. I don't see any particular reason
> for it to be false, as you shouldn't normally be using it; it's more
> like a "null" state, it means "I don't know if we're equal or not". If
> neither side knows whether they're equal, then they're presumed to be
> unequal, but you can't determine that from a single call to __eq__.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: At a loss on python scoping.

2013-03-26 Thread Shiyao Ma
After read Dave's answer, I think I confused LEGB with attribute lookup.
So, a.r has nothing to do with LEGB.

On Tue, Mar 26, 2013 at 7:03 PM, Shiyao Ma  wrote:

> Thx, really a nice and detailed explanation.
>
>
> On Tue, Mar 26, 2013 at 6:07 PM, Dave Angel  wrote:
>
>> On 03/26/2013 02:17 AM, Shiyao Ma wrote:
>>
>>> Hi,
>>> suppose I have a file like this:
>>> class A:
>>>  r = 5
>>>  def func(self, s):
>>>  self.s = s
>>> a = A()
>>> print(a.r)# this should print 5, but where does py store the name of
>>> r
>>>
>>> a.func(3)
>>> print(a.s)# this should print 3, also where does py store this name.
>>> what's the underlying difference between the above example?
>>>
>>>
>> I don't think this is a scoping question at all.  These references are
>> fully qualified, so scoping doesn't enter in.
>>
>> The class A has a dictionary containing the names of r and func.  These
>> are class attributes.  Each instance has a dictionary which will contain
>> the name s AFTER the A.func() is called.  Ideally such an attribute will be
>> assigned in the __init__() method, in which case every instance will have s
>> in its dictionary.
>>
>> When you use a.qqq  the attribute qqq is searched for in the instance
>> dictionary and, if not found, in the class dictionary.  If still not found,
>> in the parent classes' dictionary(s).
>>
>> You can use dir(A) and dir(a) to look at these dictionaries, but it shows
>> you the combination of them, so it's not as clear.  In other words, dir(a)
>> shows you both dictionaries, merged.  (Seems to me dir also sometimes
>> censors some of the names, but that's a vague memory. It's never left out
>> anything I cared about, so maybe it's things like single-underscore names,
>> or maybe just a poor memory.)
>>
>>
>> --
>> DaveA
>> --
>> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>>
>
>
>
> --
> My gpg pubring is available via: gpg --keyserver subkeys.pgp.net--recv-keys 
> 307CF736
>
> More on: http://about.me/introom
>
>


-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: At a loss on python scoping.

2013-03-26 Thread Shiyao Ma
Thx, really a nice and detailed explanation.

On Tue, Mar 26, 2013 at 6:07 PM, Dave Angel  wrote:

> On 03/26/2013 02:17 AM, Shiyao Ma wrote:
>
>> Hi,
>> suppose I have a file like this:
>> class A:
>>  r = 5
>>  def func(self, s):
>>  self.s = s
>> a = A()
>> print(a.r)# this should print 5, but where does py store the name of r
>>
>> a.func(3)
>> print(a.s)# this should print 3, also where does py store this name.
>> what's the underlying difference between the above example?
>>
>>
> I don't think this is a scoping question at all.  These references are
> fully qualified, so scoping doesn't enter in.
>
> The class A has a dictionary containing the names of r and func.  These
> are class attributes.  Each instance has a dictionary which will contain
> the name s AFTER the A.func() is called.  Ideally such an attribute will be
> assigned in the __init__() method, in which case every instance will have s
> in its dictionary.
>
> When you use a.qqq  the attribute qqq is searched for in the instance
> dictionary and, if not found, in the class dictionary.  If still not found,
> in the parent classes' dictionary(s).
>
> You can use dir(A) and dir(a) to look at these dictionaries, but it shows
> you the combination of them, so it's not as clear.  In other words, dir(a)
> shows you both dictionaries, merged.  (Seems to me dir also sometimes
> censors some of the names, but that's a vague memory. It's never left out
> anything I cared about, so maybe it's things like single-underscore names,
> or maybe just a poor memory.)
>
>
> --
> DaveA
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python3 string format

2013-03-26 Thread Shiyao Ma
Thx for your reply.
I am using pycharm and simply press "go to declaration" which directs me to
a py file, containing the following code:
def format(*args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> string

Return a formatted version of S, using substitutions from args and
kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass
I am curious how you find the corresponding c source code.

On Tue, Mar 26, 2013 at 2:16 PM, Ian Kelly  wrote:

> On Mon, Mar 25, 2013 at 10:24 PM, Shiyao Ma  wrote:
> > HI.
> > one thing confuses me.
> > It is said in the pep3101 that "{}".format (x) will invoke the method
> > x.__format__
> > However, I looked at the src of python3 and found:
> > in class str(object), the format simply contains a pass statement
> > in class int(object), things is the same.
>
> I don't know what source you're looking at.  In CPython, both of those
> types are implemented in C, not Python, so there would be no pass
> statements involved.
>
> The int.__format__ method is implemented at:
>
> http://hg.python.org/cpython/file/3c437e591499/Objects/longobject.c#l4373
>
> It mainly just calls the _PyLong_FormatAdvancedWriter function, which is
> at:
>
>
> http://hg.python.org/cpython/file/3c437e591499/Python/formatter_unicode.c#l1399
>
> The str.__format__ method similarly is implemented at:
>
>
> http://hg.python.org/cpython/file/3c437e591499/Objects/unicodeobject.c#l12851
>
> and calls the _PyUnicode_FormatAdvancedWriter function at:
>
>
> http://hg.python.org/cpython/file/3c437e591499/Python/formatter_unicode.c#l1363
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: At a loss on python scoping.

2013-03-26 Thread Shiyao Ma
Sorry for my obscure description.
"the name of r" , AFAIK, everything in python is just a reference. For
example, a = 3, means a points to a small integer; b= [] means b points to
a list somewhere in the memory. So I call r as the name of r.

To clarify my question.
say I wanna look up a.r
I guess the first step is to look inside a, maybe in the __dict__?
As proved in my ipython, the __dict__ is empty.
So, it will look up in A.__dict__
Here comes my first question, where does the scope of class A falls in when
considering LEGB.

On Tue, Mar 26, 2013 at 2:29 PM, Chris Angelico  wrote:

> On Tue, Mar 26, 2013 at 5:17 PM, Shiyao Ma  wrote:
> > class A:
> > r = 5
> > def func(self, s):
> > self.s = s
> > a = A()
> > print(a.r)# this should print 5, but where does py store the name of
> r
>
> What do you mean by "the name of r"?
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: At a loss on python scoping.

2013-03-25 Thread Shiyao Ma
PS, I now python's scoping rule is lexical rule (aka static rule). How does
LEGB apply to class?

On Tue, Mar 26, 2013 at 2:17 PM, Shiyao Ma  wrote:

> Hi,
> suppose I have a file like this:
> class A:
> r = 5
> def func(self, s):
> self.s = s
> a = A()
> print(a.r)# this should print 5, but where does py store the name of r
>
> a.func(3)
> print(a.s)# this should print 3, also where does py store this name.
> what's the underlying difference between the above example?
>
>
> --
> My gpg pubring is available via: gpg --keyserver subkeys.pgp.net--recv-keys 
> 307CF736
>
> More on: http://about.me/introom
>
>


-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


At a loss on python scoping.

2013-03-25 Thread Shiyao Ma
Hi,
suppose I have a file like this:
class A:
r = 5
def func(self, s):
self.s = s
a = A()
print(a.r)# this should print 5, but where does py store the name of r

a.func(3)
print(a.s)# this should print 3, also where does py store this name.
what's the underlying difference between the above example?


-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


python3 string format

2013-03-25 Thread Shiyao Ma
HI.
one thing confuses me.
It is said in the pep3101 that "{}".format (x) will invoke the method
x.__format__
However, I looked at the src of python3 and found:
in class str(object), the format simply contains a pass statement
in class int(object), things is the same.

So, what's the mechanism that "{}" works?
Thx

-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to quickly set up a multithreaded server that can handle http file post.

2013-03-11 Thread Shiyao Ma
Yes, sounds good. I should give it a try.

On Tue, Mar 12, 2013 at 1:02 AM, Xavier L.  wrote:

> On 13-03-11 10:42 AM, Shiyao Ma wrote:
>
>> Today I come across a problem.
>> Basically, my need is that I want to launch a http server that can not
>> only support get but also support post (including post file).
>> My first idea is to use -m http.sever. However, it only supports get.
>> Later I find some one extended basehttpserver and made it  support post.
>> However it is not multithreaded.
>>
>> Is it easy to write a RELIABLE (I mean under normal cases) multithreaded
>> server that suits my need.
>> Also, are there any already invented wheel I can use?
>>
>> Thx
>>
>>
>> --
>> My gpg pubring is available via: gpg --keyserver subkeys.pgp.net
>> <http://subkeys.pgp.net> --recv-keys 307CF736
>>
>> More on: http://about.me/introom
>>
>>  The best would be to use an existing webserver, such as Apache, Nginx,
> Lighttpd, etc. with python running as a fcgi or cgi script.
>
> Those webservers have been tested for longer and there is no need to
> reinvent the wheel.
>
> X
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list


How to quickly set up a multithreaded server that can handle http file post.

2013-03-11 Thread Shiyao Ma
Today I come across a problem.
Basically, my need is that I want to launch a http server that can not only
support get but also support post (including post file).
My first idea is to use -m http.sever. However, it only supports get.
Later I find some one extended basehttpserver and made it  support post.
However it is not multithreaded.

Is it easy to write a RELIABLE (I mean under normal cases) multithreaded
server that suits my need.
Also, are there any already invented wheel I can use?

Thx


-- 
My gpg pubring is available via: gpg --keyserver
subkeys.pgp.net--recv-keys 307CF736

More on: http://about.me/introom
-- 
http://mail.python.org/mailman/listinfo/python-list