Re-encode a named tuple

71 views Asked by At

Input:

import mouse
import pickle
from collections import namedtuple

#https://github.com/boppreh/keyboard/blob/master/keyboard/mouse.py

#from ._mouse_event import ButtonEvent, MoveEvent, WheelEvent, LEFT, RIGHT, 
MIDDLE, X, X2, UP, DOWN, DOUBLE


ButtonEvent = namedtuple('ButtonEvent', ['event_type', 'button', 'time'])
WheelEvent = namedtuple('WheelEvent', ['delta', 'time'])
MoveEvent = namedtuple('MoveEvent', ['x', 'y', 'time'])

with open ('outfile', 'rb') as fp:
    itemlist = pickle.load(fp)

#print (type (itemlist))
print (itemlist[:3])

z=0
xx=50
yy=10
itemlist2=[]

for i in itemlist:
    old_event = itemlist[z]
    new_event = MoveEvent(x=xx, y=yy, time=old_event.time)
    itemlist2.append(new_event)
    z=z+1
    xx=xx+1
    yy=yy+1
print ()

print (itemlist2[:3])

print (type (itemlist))
print (type (itemlist[0]))
print (type (itemlist[0][0]))

print()

print (type (itemlist2))
print (type (itemlist2[0]))
print (type (itemlist2[0][0]))

Output:

[MoveEvent(x=1369, y=162, time=1504533266.029788), MoveEvent(x=1358, y=165, time=1504533266.0377884), MoveEvent(x=1350, y=167, time=1504533266.045789)]

[MoveEvent(x=50, y=10, time=1504533266.029788), MoveEvent(x=51, y=11, time=1504533266.0377884), MoveEvent(x=52, y=12, time=1504533266.045789)]
<class 'list'>
<class 'mouse._mouse_event.MoveEvent'>
<class 'int'>

<class 'list'>
<class '__main__.MoveEvent'>
<class 'int'>

New to python here- When I re-assemble the list of named tuples into itemlist2 I need the keep the -class mouse._mouse_event.MoveEvent- - not sure how to do this

I guess I could also try and edit 'itemlist' directly if that is possible

when printed the lists look identical (except for the changed values)

1

There are 1 answers

0
Harvey On

You're creating a new MoveEvent namedtuple type in your file:

MoveEvent = namedtuple('MoveEvent', ['x', 'y', 'time'])

If you want to use the original, you need to use mouse._mouse_event.MoveEvent or rename it above:

MoveEvent = mouse._mouse_event.MoveEvent

Because mouse.py includes this line:

from ._mouse_event import ButtonEvent, MoveEvent, WheelEvent, LEFT, RIGHT, MIDDLE, X, X2, UP, DOWN, DOUBLE

You can probably use this code:

import mouse
from mouse import MoveEvent