Ask Your Question
0

How to implement "positional-only parameter" in a user defined function?

asked 2018-10-16 04:23:40 -0600

damodar gravatar image

updated 2018-10-16 06:34:57 -0600

def fun( a, b, /): print(a,b)

o/p:

File "<ipython-input-36-1fceb840aeb9>", line 1 def fun( a, b, /): ^ SyntaxError: invalid syntax

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted
0

answered 2018-10-16 12:29:57 -0600

damodar gravatar image

ok i got it . Those are built-in functions (builtin_function_or_method), not user-defined functions (function). They are implemented in C, into python library. These functions are not exposed at the Python level.

edit flag offensive delete link more
0

answered 2018-10-16 05:20:28 -0600

tmonteil gravatar image

I am not sure to understand your question, but does the following inspire you ?

sage: def fun( a, b, c=None): 
....:     print(a,b)
sage: fun(2,3)
(2, 3)
sage: fun(2,3,4)
(2, 3)

or even

sage: def fun( a, b, *args): 
....:     print(a,b)
sage: fun(2,3)
(2, 3)
sage: fun(2,3,4)
(2, 3)
sage: fun(2,3,4,5)
(2, 3)
edit flag offensive delete link more

Comments

damodar gravatar imagedamodar ( 2018-10-16 06:10:12 -0600 )edit

help(pow)

o/p:
-----
Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.

I want to know can we write a user defined function like pow (), which has positional only parameter.

damodar gravatar imagedamodar ( 2018-10-16 06:16:38 -0600 )edit

Examples:

 def fun( a, b): 
        print(a**b)
 fun(a=5, b=2)   # 25
 fun(b=2,a=5)    # 25
 fun(5,2)        # 25




 def fun( a, b, /): 
        print(a**b)
 fun(5,2)        # 25
 fun(a=5, b=2)   # should show error
damodar gravatar imagedamodar ( 2018-10-16 06:30:20 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-10-16 04:23:40 -0600

Seen: 47 times

Last updated: Oct 16 '18