1

Consider the following simple example:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
mytable["z"] = mytable.x + mytable.y
mytable["q"] = mytable.z**2
mytable

for example with cat test.dat:

x       y
1       5
2       6
3       7
4       8

If I use something like this for example from ipython3 I want to "factor out" the mytable keyword as in this pseudo code:

import pandas as pd
mytable = pd.read_csv('test.dat',sep='\t')
cd mytable
   z = x + y
   q = z**2
mytable

Are there any possibilities to simplify syntax like this. It is ok, if the solutions uses additional ipython features.

Remark: I used a "cd" keyword following pgf/tikz syntax where something like this is possible.

student
  • 1,636
  • 3
  • 29
  • 53
  • 1
    Sounds like the `with` keyword from Pascal. I think there is no such thing in Python possible without massive hacking. After all Python strives to keep each line expressive without too much context. Think of the explicitness of `self` in methods which is exactly the opposite of your approach. See also http://stackoverflow.com/questions/2279180/does-c-have-with-keyword-like-pascal for the same question in C/C++. – Alfe Mar 03 '17 at 10:51

1 Answers1

1

Python's design does not really allow for this as it would lead to ambiguities. See here for a detailed discussion on the topic.

Consider a code like this:

class X(object):
  def __init__(self, q):
    self.q = q

x = X(4)
q = 3

# del x.q

with x:
  print q

This should print 4, I assume.

Now, consider to enable the del statement. Should this then raise an error (because of the missing q in x?) or should it print 3 (because of the more global variable q)? Since this is hard to decide and different people could validly have different opinions, Python decided not to have this feature at all.

Alfe
  • 56,346
  • 20
  • 107
  • 159